From cf7a4f31f1f191f4eea84bb79c6aeffbccb7140e Mon Sep 17 00:00:00 2001 From: Michael Taylor Date: Tue, 24 Feb 2026 19:49:23 +1300 Subject: [PATCH 001/140] Allow Swift projects that use JavaScriptKit to compile on Windows (#673) --- .../BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift | 7 +++++++ Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift | 7 +++++++ Plugins/PackageToJS/Sources/PackageToJS.swift | 7 +++++++ 3 files changed, 21 insertions(+) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift index a45a06188..23fbae567 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift @@ -1,4 +1,7 @@ #if canImport(PackagePlugin) +#if os(Windows) +import WinSDK +#endif import PackagePlugin @preconcurrency import Foundation @@ -180,7 +183,11 @@ extension Foundation.Process { let signalSource = DispatchSource.makeSignalSource(signal: signalNo) signalSource.setEventHandler { [self] in signalSource.cancel() + #if os(Windows) + _ = TerminateProcess(processHandle, 0) + #else kill(processIdentifier, signalNo) + #endif } signalSource.resume() return signalSource diff --git a/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift b/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift index 6337dcf27..42a6775ff 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift +++ b/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift @@ -13,6 +13,9 @@ import class Dispatch.DispatchSource import SwiftParser import SwiftSyntax +#if os(Windows) +import WinSDK +#endif #if canImport(BridgeJSCore) import BridgeJSCore #endif @@ -141,7 +144,11 @@ extension Foundation.Process { let signalSource = DispatchSource.makeSignalSource(signal: signalNo) signalSource.setEventHandler { [self] in signalSource.cancel() + #if os(Windows) + _ = TerminateProcess(processHandle, 0) + #else kill(processIdentifier, signalNo) + #endif } signalSource.resume() return signalSource diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index 3e22736be..ff3e2ce5a 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -1,5 +1,8 @@ import Foundation +#if os(Windows) +import WinSDK +#endif struct PackageToJS { struct PackageOptions { enum Platform: String, CaseIterable { @@ -785,7 +788,11 @@ extension Foundation.Process { let signalSource = DispatchSource.makeSignalSource(signal: signalNo) signalSource.setEventHandler { [self] in signalSource.cancel() + #if os(Windows) + _ = TerminateProcess(processHandle, 0) + #else kill(processIdentifier, signalNo) + #endif } signalSource.resume() return signalSource From 3badf17d1e1d214dbaa6cd5179c480d2db6f1dbe Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Wed, 25 Feb 2026 18:58:48 +0900 Subject: [PATCH 002/140] BridgeJS: Simplify Stack ABI for Optional (#674) Now `Optional` conforms to `_BridgedSwiftStackType` whenever `Wrapped` conforms to `_BridgedSwiftStackType`. This makes generic programming easier and reduces boilerplate in intrinsics and codegen. For specialized handling of certain types like associated value enums, where the presence of a value is encoded as a sentinel case ID (-1), we implement `bridgeJSStack{Push,Pop}AsOptional` methods, which is on the witness table of `_BridgedSwiftStackType`. Also now some of optional types no longer pushes placeholders values for `nil` cases when pushing in JS and popping in Swift. --- Benchmarks/Sources/Generated/BridgeJS.swift | 18 +- .../Sources/BridgeJSCore/ExportSwift.swift | 54 +-- .../Sources/BridgeJSLink/JSGlueGen.swift | 294 ++++----------- .../BridgeJSCodegenTests/ArrayTypes.swift | 30 +- .../EnumAssociatedValue.swift | 66 +--- .../ImportedTypeInExportedInterface.swift | 12 +- .../BridgeJSCodegenTests/SwiftStruct.swift | 36 +- .../BridgeJSLinkTests/ArrayTypes.js | 11 - .../BridgeJSLinkTests/DictionaryTypes.js | 2 - .../BridgeJSLinkTests/EnumAssociatedValue.js | 238 ++++++------ .../ImportedTypeInExportedInterface.js | 52 +-- .../BridgeJSLinkTests/SwiftStruct.js | 139 +++---- .../JavaScriptKit/BridgeJSIntrinsics.swift | 348 +++++++----------- .../ArraySupportTests.swift | 11 - .../Generated/BridgeJS.swift | 267 ++++---------- .../Generated/JavaScript/BridgeJS.json | 108 ++++-- .../JavaScript/OptionalSupportTests.mjs | 6 + .../OptionalSupportTests.swift | 30 ++ 18 files changed, 603 insertions(+), 1119 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index a19e2c53a..77fefad8a 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -230,11 +230,7 @@ extension Person: _BridgedSwiftStruct { self.name.bridgeJSStackPush() self.age.bridgeJSStackPush() self.address.bridgeJSStackPush() - let __bjs_isSome_email = self.email != nil - if let __bjs_unwrapped_email = self.email { - __bjs_unwrapped_email.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) + self.email.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -1603,11 +1599,7 @@ public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPo #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalIntArray() for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -1630,11 +1622,7 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutable return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index b7c66dcd2..12d472cbe 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -824,16 +824,12 @@ struct StackCodegen { switch type { case .string, .int, .uint, .bool, .float, .double, .jsValue, .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, - .caseEnum, .rawValueEnum: + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, .nullable: return ["\(raw: accessor).bridgeJSStackPush()"] case .jsObject(_?): return ["\(raw: accessor).jsObject.bridgeJSStackPush()"] case .swiftProtocol: return ["(\(raw: accessor) as! \(raw: type.swiftType)).bridgeJSStackPush()"] - case .associatedValueEnum, .swiftStruct: - return ["\(raw: accessor).bridgeJSStackPush()"] - case .nullable(let wrappedType, _): - return lowerOptionalStatements(wrappedType: wrappedType, accessor: accessor, varPrefix: varPrefix) case .void, .namespaceEnum: return [] case .array(let elementType): @@ -946,54 +942,6 @@ struct StackCodegen { statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") return statements } - - private func lowerOptionalStatements( - wrappedType: BridgeType, - accessor: String, - varPrefix: String - ) -> [CodeBlockItemSyntax] { - switch wrappedType { - case .array, .dictionary, .swiftStruct: - return ["\(raw: accessor).bridgeJSStackPush()"] - default: - break - } - - var statements: [String] = [] - statements.append("let __bjs_isSome_\(varPrefix) = \(accessor) != nil") - statements.append("if let __bjs_unwrapped_\(varPrefix) = \(accessor) {") - - let innerStatements = lowerUnwrappedOptionalStatements( - wrappedType: wrappedType, - unwrappedVar: "__bjs_unwrapped_\(varPrefix)" - ) - for stmt in innerStatements { - statements.append(stmt.description) - } - - statements.append("}") - statements.append("_swift_js_push_i32(__bjs_isSome_\(varPrefix) ? 1 : 0)") - let parsed: CodeBlockItemListSyntax = "\(raw: statements.joined(separator: "\n"))" - return Array(parsed) - } - - private func lowerUnwrappedOptionalStatements( - wrappedType: BridgeType, - unwrappedVar: String - ) -> [CodeBlockItemSyntax] { - switch wrappedType { - case .jsObject(_?): - return ["\(raw: unwrappedVar).jsObject.bridgeJSStackPush()"] - case .swiftProtocol: - return ["(\(raw: unwrappedVar) as! \(raw: wrappedType.swiftType)).bridgeJSStackPush()"] - case .string, .int, .uint, .bool, .float, .double, .jsValue, - .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, - .caseEnum, .rawValueEnum, .associatedValueEnum: - return ["\(raw: unwrappedVar).bridgeJSStackPush()"] - default: - return ["preconditionFailure(\"BridgeJS: unsupported optional wrapped type\")"] - } - } } // MARK: - EnumCodegen diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 63eb6cc0b..ba0d0d86c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -1204,22 +1204,8 @@ struct IntrinsicJSFragment: Sendable { } } - @discardableResult - private static func emitOptionalPlaceholders( - for wrappedType: BridgeType, - scope: JSGlueVariableScope, - printer: CodeFragmentPrinter - ) -> Bool { - let params = wrappedType.wasmParams - if params.isEmpty { - return false - } - for param in params { - emitPush(for: param.type, value: param.type.jsZeroLiteral, scope: scope, printer: printer) - } - return true - } - + /// 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, @@ -1244,23 +1230,7 @@ struct IntrinsicJSFragment: Sendable { for line in ifBodyPrinter.lines { printer.write(line) } - let placeholderPrinter = CodeFragmentPrinter() - let hasPlaceholders = emitOptionalPlaceholders( - for: wrappedType, - scope: scope, - printer: placeholderPrinter - ) - if hasPlaceholders { - printer.write("} else {") - printer.indent { - for line in placeholderPrinter.lines { - printer.write(line) - } - } - printer.write("}") - } else { - printer.write("}") - } + printer.write("}") scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) return [] } @@ -1744,109 +1714,21 @@ struct IntrinsicJSFragment: Sendable { private static func associatedValuePushPayload(type: BridgeType) throws -> IntrinsicJSFragment { switch type { case .nullable(let wrappedType, let kind): - return try associatedValueOptionalPushPayload(wrappedType: wrappedType, kind: kind) + return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) default: return try stackLowerFragment(elementType: type) } } - private static func associatedValueOptionalPushPayload( - wrappedType: BridgeType, - kind: JSOptionalKind - ) throws -> IntrinsicJSFragment { - if wrappedType.isSingleParamScalar { - let wasmType = wrappedType.wasmParams[0].type - let stackCoerce = wrappedType.stackLowerCoerce - return 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));") - var coerced: String - if let coerce = stackCoerce { - coerced = coerce.replacingOccurrences(of: "$0", with: value) - if coerced.contains("?") && !coerced.hasPrefix("(") { - coerced = "(\(coerced))" - } - } else { - coerced = value - } - emitPush( - for: wasmType, - value: "\(isSomeVar) ? \(coerced) : \(wasmType.jsZeroLiteral)", - scope: scope, - printer: printer - ) - scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) - return [] - } - ) - } - - let innerFragment = try stackLowerFragment(elementType: wrappedType) - return stackOptionalLower( - wrappedType: wrappedType, - kind: kind, - innerFragment: innerFragment - ) - } - private static func associatedValuePopPayload(type: BridgeType) throws -> IntrinsicJSFragment { switch type { case .nullable(let wrappedType, let kind): - return associatedValueOptionalPopPayload(wrappedType: wrappedType, kind: kind) + return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) default: return try stackLiftFragment(elementType: type) } } - private static func associatedValueOptionalPopPayload( - wrappedType: BridgeType, - kind: JSOptionalKind - ) -> IntrinsicJSFragment { - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let optVar = scope.variable("optional") - let isSomeVar = scope.variable("isSome") - - printer.write("const \(isSomeVar) = \(scope.popI32());") - printer.write("let \(optVar);") - printer.write("if (\(isSomeVar)) {") - try printer.indent { - // For optional associated value enums, Swift uses bridgeJSLowerParameter() - // which pushes caseId to i32Stack (same as bridgeJSLowerReturn()). - if case .associatedValueEnum(let fullName) = wrappedType { - let base = fullName.components(separatedBy: ".").last ?? fullName - let caseIdVar = scope.variable("caseId") - printer.write("const \(caseIdVar) = \(scope.popI32());") - printer.write( - "\(optVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar));" - ) - } else { - let wrappedFragment = try associatedValuePopPayload(type: wrappedType) - let wrappedResults = try wrappedFragment.printCode([], context) - if let wrappedResult = wrappedResults.first { - printer.write("\(optVar) = \(wrappedResult);") - } else { - printer.write("\(optVar) = undefined;") - } - } - } - printer.write("} else {") - printer.indent { - printer.write("\(optVar) = \(kind.absenceLiteral);") - } - printer.write("}") - - return [optVar] - } - ) - } - private static func swiftStructLower(structBase: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: ["value"], @@ -2252,6 +2134,35 @@ 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: [], @@ -2283,10 +2194,42 @@ struct IntrinsicJSFragment: Sendable { ) } + /// Lower an optional element to the stack using the **conditional** protocol: + /// push isSome flag, then conditionally push the payload (no placeholders for nil). private static func optionalElementLowerFragment( 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 @@ -2304,23 +2247,7 @@ struct IntrinsicJSFragment: Sendable { context ) } - let placeholderPrinter = CodeFragmentPrinter() - let hasPlaceholders = emitOptionalPlaceholders( - for: wrappedType, - scope: scope, - printer: placeholderPrinter - ) - if hasPlaceholders { - printer.write("} else {") - printer.indent { - for line in placeholderPrinter.lines { - printer.write(line) - } - } - printer.write("}") - } else { - printer.write("}") - } + printer.write("}") scope.emitPushI32Parameter(isSomeVar, printer: printer) return [] @@ -2506,47 +2433,7 @@ struct IntrinsicJSFragment: Sendable { } ) case .nullable(let wrappedType, let kind): - if wrappedType.isSingleParamScalar { - let wasmType = wrappedType.wasmParams[0].type - let stackCoerce = wrappedType.stackLowerCoerce - return 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 coerced: String - if let coerce = stackCoerce { - coerced = coerce.replacingOccurrences(of: "$0", with: value) - } else { - coerced = value - } - printer.write("if (\(isSomeVar)) {") - printer.indent { - emitPush(for: wasmType, value: coerced, scope: scope, printer: printer) - } - printer.write("} else {") - printer.indent { - emitPush(for: wasmType, value: wasmType.jsZeroLiteral, scope: scope, printer: printer) - } - printer.write("}") - scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) - return [] - } - ) - } - - let innerFragment = try structFieldLowerFragment( - type: wrappedType, - fieldName: fieldName, - allStructs: allStructs - ) - return stackOptionalLower( - wrappedType: wrappedType, - kind: kind, - innerFragment: innerFragment - ) + return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) case .swiftStruct(let nestedName): return IntrinsicJSFragment( parameters: ["value"], @@ -2584,50 +2471,7 @@ struct IntrinsicJSFragment: Sendable { case .jsValue: preconditionFailure("Struct field of JSValue is not supported yet") case .nullable(let wrappedType, let kind): - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let isSomeVar = scope.variable("isSome") - let optVar = scope.variable("optional") - printer.write("const \(isSomeVar) = \(scope.popI32());") - printer.write("let \(optVar);") - printer.write("if (\(isSomeVar)) {") - try printer.indent { - // Special handling for associated value enum - in struct fields, case ID is pushed to i32Stack - if case .associatedValueEnum(let enumName) = wrappedType { - let base = enumName.components(separatedBy: ".").last ?? enumName - let caseIdVar = scope.variable("enumCaseId") - printer.write("const \(caseIdVar) = \(scope.popI32());") - printer.write( - "\(optVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar));" - ) - } else { - let wrappedFragment = try structFieldLiftFragment( - field: ExportedProperty( - name: field.name, - type: wrappedType, - isReadonly: true, - isStatic: false - ), - allStructs: allStructs - ) - let wrappedResults = try wrappedFragment.printCode([], context) - if let wrappedResult = wrappedResults.first { - printer.write("\(optVar) = \(wrappedResult);") - } else { - printer.write("\(optVar) = undefined;") - } - } - } - printer.write("} else {") - printer.indent { - printer.write("\(optVar) = \(kind.absenceLiteral);") - } - printer.write("}") - return [optVar] - } - ) + return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) case .swiftStruct(let nestedName): return IntrinsicJSFragment( parameters: [], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index 6b6b59fce..6ced24393 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -239,11 +239,7 @@ public func _bjs_processOptionalIntArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -266,11 +262,7 @@ public func _bjs_processOptionalStringArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -327,11 +319,7 @@ public func _bjs_processOptionalDirectionArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -354,11 +342,7 @@ public func _bjs_processOptionalStatusArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -447,11 +431,7 @@ public func _bjs_processOptionalJSObjectArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 838c55122..fc3a18453 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -171,40 +171,16 @@ extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0, let param1): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - __bjs_unwrapped_param1.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) case .status(let param0, let param1, let param2): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - __bjs_unwrapped_param1.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - __bjs_unwrapped_param2.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(2) } } @@ -283,18 +259,10 @@ extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { param0.bridgeJSStackPush() return Int32(1) case .optPrecision(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .optDirection(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(3) case .empty: return Int32(4) @@ -371,25 +339,13 @@ extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { param0.bridgeJSStackPush() return Int32(0) case .optClass(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(1) case .optJSObject(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .optNestedEnum(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(3) case .optArray(let param0): param0.bridgeJSStackPush() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index c72cda7ed..809dfb43a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -7,11 +7,7 @@ extension FooContainer: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.foo.jsObject.bridgeJSStackPush() - let __bjs_isSome_optionalFoo = self.optionalFoo != nil - if let __bjs_unwrapped_optionalFoo = self.optionalFoo { - __bjs_unwrapped_optionalFoo.jsObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalFoo ? 1 : 0) + self.optionalFoo.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -101,11 +97,7 @@ public func _bjs_processOptionalFooArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.jsObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 2adffc113..6fccb3280 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -15,16 +15,8 @@ extension DataPoint: _BridgedSwiftStruct { self.x.bridgeJSStackPush() self.y.bridgeJSStackPush() self.label.bridgeJSStackPush() - let __bjs_isSome_optCount = self.optCount != nil - if let __bjs_unwrapped_optCount = self.optCount { - __bjs_unwrapped_optCount.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optCount ? 1 : 0) - let __bjs_isSome_optFlag = self.optFlag != nil - if let __bjs_unwrapped_optFlag = self.optFlag { - __bjs_unwrapped_optFlag.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optFlag ? 1 : 0) + self.optCount.bridgeJSStackPush() + self.optFlag.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -85,11 +77,7 @@ extension Address: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.street.bridgeJSStackPush() self.city.bridgeJSStackPush() - let __bjs_isSome_zipCode = self.zipCode != nil - if let __bjs_unwrapped_zipCode = self.zipCode { - __bjs_unwrapped_zipCode.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_zipCode ? 1 : 0) + self.zipCode.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -141,11 +129,7 @@ extension Person: _BridgedSwiftStruct { self.name.bridgeJSStackPush() self.age.bridgeJSStackPush() self.address.bridgeJSStackPush() - let __bjs_isSome_email = self.email != nil - if let __bjs_unwrapped_email = self.email { - __bjs_unwrapped_email.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) + self.email.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -243,11 +227,7 @@ extension Measurement: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.value.bridgeJSStackPush() self.precision.bridgeJSStackPush() - let __bjs_isSome_optionalPrecision = self.optionalPrecision != nil - if let __bjs_unwrapped_optionalPrecision = self.optionalPrecision { - __bjs_unwrapped_optionalPrecision.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalPrecision ? 1 : 0) + self.optionalPrecision.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -414,11 +394,7 @@ extension Container: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.object.bridgeJSStackPush() - let __bjs_isSome_optionalObject = self.optionalObject != nil - if let __bjs_unwrapped_optionalObject = self.optionalObject { - __bjs_unwrapped_optionalObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalObject ? 1 : 0) + self.optionalObject.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index d0665da73..81b432012 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -598,8 +598,6 @@ export async function createInstantiator(options, swift) { const isSome = elem != null ? 1 : 0; if (isSome) { i32Stack.push((elem | 0)); - } else { - i32Stack.push(0); } i32Stack.push(isSome); } @@ -629,9 +627,6 @@ export async function createInstantiator(options, swift) { const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - } else { - i32Stack.push(0); - i32Stack.push(0); } i32Stack.push(isSome); } @@ -710,8 +705,6 @@ export async function createInstantiator(options, swift) { const isSome = elem != null ? 1 : 0; if (isSome) { i32Stack.push((elem | 0)); - } else { - i32Stack.push(0); } i32Stack.push(isSome); } @@ -738,8 +731,6 @@ export async function createInstantiator(options, swift) { const isSome = elem != null ? 1 : 0; if (isSome) { i32Stack.push((elem | 0)); - } else { - i32Stack.push(0); } i32Stack.push(isSome); } @@ -901,8 +892,6 @@ export async function createInstantiator(options, swift) { if (isSome) { const objId = swift.memory.retain(elem); i32Stack.push(objId); - } else { - i32Stack.push(0); } i32Stack.push(isSome); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 268caf407..8627b2c80 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -386,8 +386,6 @@ export async function createInstantiator(options, swift) { const isSome = value != null ? 1 : 0; if (isSome) { ptrStack.push(value.pointer); - } else { - ptrStack.push(0); } i32Stack.push(isSome); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 55967a6a3..8e9dfa65f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -379,46 +379,48 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case APIOptionalResultValues.Tag.Success: { - const isSome = value.param0 != null; + 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); - } else { - i32Stack.push(0); - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); return APIOptionalResultValues.Tag.Success; } case APIOptionalResultValues.Tag.Failure: { - const isSome = value.param1 != null; - i32Stack.push(isSome ? (value.param1 ? 1 : 0) : 0); - i32Stack.push(isSome ? 1 : 0); - const isSome1 = value.param0 != null; - i32Stack.push(isSome1 ? (value.param0 | 0) : 0); - i32Stack.push(isSome1 ? 1 : 0); + 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); return APIOptionalResultValues.Tag.Failure; } case APIOptionalResultValues.Tag.Status: { - const isSome = value.param2 != null; + 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); - } else { - i32Stack.push(0); - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); - const isSome1 = value.param1 != null; - i32Stack.push(isSome1 ? (value.param1 | 0) : 0); - i32Stack.push(isSome1 ? 1 : 0); - const isSome2 = value.param0 != null; - i32Stack.push(isSome2 ? (value.param0 ? 1 : 0) : 0); - i32Stack.push(isSome2 ? 1 : 0); + 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); return APIOptionalResultValues.Tag.Status; } default: throw new Error("Unknown APIOptionalResultValues tag: " + String(enumTag)); @@ -429,60 +431,60 @@ export async function createInstantiator(options, swift) { switch (tag) { case APIOptionalResultValues.Tag.Success: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const string = strStack.pop(); - optional = string; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const string = strStack.pop(); + optValue = string; } - return { tag: APIOptionalResultValues.Tag.Success, param0: optional }; + return { tag: APIOptionalResultValues.Tag.Success, param0: optValue }; } case APIOptionalResultValues.Tag.Failure: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const bool = i32Stack.pop() !== 0; - optional = bool; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const bool = i32Stack.pop() !== 0; + optValue = bool; } const isSome1 = i32Stack.pop(); - let optional1; - if (isSome1) { - const int = i32Stack.pop(); - optional1 = int; + let optValue1; + if (isSome1 === 0) { + optValue1 = null; } else { - optional1 = null; + const int = i32Stack.pop(); + optValue1 = int; } - return { tag: APIOptionalResultValues.Tag.Failure, param0: optional1, param1: optional }; + return { tag: APIOptionalResultValues.Tag.Failure, param0: optValue1, param1: optValue }; } case APIOptionalResultValues.Tag.Status: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const string = strStack.pop(); - optional = string; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const string = strStack.pop(); + optValue = string; } const isSome1 = i32Stack.pop(); - let optional1; - if (isSome1) { - const int = i32Stack.pop(); - optional1 = int; + let optValue1; + if (isSome1 === 0) { + optValue1 = null; } else { - optional1 = null; + const int = i32Stack.pop(); + optValue1 = int; } const isSome2 = i32Stack.pop(); - let optional2; - if (isSome2) { - const bool = i32Stack.pop() !== 0; - optional2 = bool; + let optValue2; + if (isSome2 === 0) { + optValue2 = null; } else { - optional2 = null; + const bool = i32Stack.pop() !== 0; + optValue2 = bool; } - return { tag: APIOptionalResultValues.Tag.Status, param0: optional2, param1: optional1, param2: optional }; + return { tag: APIOptionalResultValues.Tag.Status, param0: optValue2, param1: optValue1, param2: optValue }; } default: throw new Error("Unknown APIOptionalResultValues tag returned from Swift: " + String(tag)); } @@ -501,15 +503,19 @@ export async function createInstantiator(options, swift) { return TypedPayloadResultValues.Tag.Direction; } case TypedPayloadResultValues.Tag.OptPrecision: { - const isSome = value.param0 != null; - f32Stack.push(isSome ? Math.fround(value.param0) : 0.0); - i32Stack.push(isSome ? 1 : 0); + const isSome = value.param0 != null ? 1 : 0; + if (isSome) { + f32Stack.push(Math.fround(value.param0)); + } + i32Stack.push(isSome); return TypedPayloadResultValues.Tag.OptPrecision; } case TypedPayloadResultValues.Tag.OptDirection: { - const isSome = value.param0 != null; - i32Stack.push(isSome ? (value.param0 | 0) : 0); - i32Stack.push(isSome ? 1 : 0); + const isSome = value.param0 != null ? 1 : 0; + if (isSome) { + i32Stack.push((value.param0 | 0)); + } + i32Stack.push(isSome); return TypedPayloadResultValues.Tag.OptDirection; } case TypedPayloadResultValues.Tag.Empty: { @@ -531,25 +537,25 @@ export async function createInstantiator(options, swift) { } case TypedPayloadResultValues.Tag.OptPrecision: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const rawValue = f32Stack.pop(); - optional = rawValue; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const rawValue = f32Stack.pop(); + optValue = rawValue; } - return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optional }; + return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optValue }; } case TypedPayloadResultValues.Tag.OptDirection: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const caseId = i32Stack.pop(); - optional = caseId; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const caseId = i32Stack.pop(); + optValue = caseId; } - return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optional }; + return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optValue }; } case TypedPayloadResultValues.Tag.Empty: return { tag: TypedPayloadResultValues.Tag.Empty }; default: throw new Error("Unknown TypedPayloadResultValues tag returned from Swift: " + String(tag)); @@ -633,54 +639,49 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - const isSome = value.param0 != null; + const isSome = value.param0 != null ? 1 : 0; if (isSome) { structHelpers.Point.lower(value.param0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); return OptionalAllTypesResultValues.Tag.OptStruct; } case OptionalAllTypesResultValues.Tag.OptClass: { - const isSome = value.param0 != null; + const isSome = value.param0 != null ? 1 : 0; if (isSome) { ptrStack.push(value.param0.pointer); - } else { - ptrStack.push(0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); return OptionalAllTypesResultValues.Tag.OptClass; } case OptionalAllTypesResultValues.Tag.OptJSObject: { - const isSome = value.param0 != null; + const isSome = value.param0 != null ? 1 : 0; if (isSome) { const objId = swift.memory.retain(value.param0); i32Stack.push(objId); - } else { - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); return OptionalAllTypesResultValues.Tag.OptJSObject; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const isSome = value.param0 != null; + const isSome = value.param0 != null ? 1 : 0; if (isSome) { const caseId = enumHelpers.APIResult.lower(value.param0); i32Stack.push(caseId); } else { - i32Stack.push(0); + i32Stack.push(-1); } - i32Stack.push(isSome ? 1 : 0); return OptionalAllTypesResultValues.Tag.OptNestedEnum; } case OptionalAllTypesResultValues.Tag.OptArray: { - const isSome = value.param0 != null; + 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 ? 1 : 0); + i32Stack.push(isSome); return OptionalAllTypesResultValues.Tag.OptArray; } case OptionalAllTypesResultValues.Tag.Empty: { @@ -694,55 +695,56 @@ export async function createInstantiator(options, swift) { switch (tag) { case OptionalAllTypesResultValues.Tag.OptStruct: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const struct = structHelpers.Point.lift(); - optional = struct; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const struct = structHelpers.Point.lift(); + optValue = struct; } - return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optional }; + return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptClass: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { + let optValue; + if (isSome === 0) { + optValue = null; + } else { const ptr = ptrStack.pop(); const obj = _exports['User'].__construct(ptr); - optional = obj; - } else { - optional = null; + optValue = obj; } - return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optional }; + return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptJSObject: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { + let optValue; + if (isSome === 0) { + optValue = null; + } else { const objId = i32Stack.pop(); const obj = swift.memory.getObject(objId); swift.memory.release(objId); - optional = obj; - } else { - optional = null; + optValue = obj; } - return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optional }; + return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const caseId = i32Stack.pop(); - optional = enumHelpers.APIResult.lift(caseId); + const caseId = i32Stack.pop(); + let optValue; + if (caseId === -1) { + optValue = null; } else { - optional = null; + optValue = enumHelpers.APIResult.lift(caseId); } - return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optional }; + return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptArray: { const isSome = i32Stack.pop(); - let optional; - if (isSome) { + let optValue; + if (isSome === 0) { + optValue = null; + } else { const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { @@ -750,11 +752,9 @@ export async function createInstantiator(options, swift) { arrayResult.push(int); } arrayResult.reverse(); - optional = arrayResult; - } else { - optional = null; + optValue = arrayResult; } - return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optional }; + return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optValue }; } case OptionalAllTypesResultValues.Tag.Empty: return { tag: OptionalAllTypesResultValues.Tag.Empty }; default: throw new Error("Unknown OptionalAllTypesResultValues tag returned from Swift: " + String(tag)); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index c0c9704ef..8b938f75a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -37,45 +37,33 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const isSome = value.optionalFoo != null; + const isSome = value.optionalFoo != null ? 1 : 0; if (isSome) { - let id1; - if (value.optionalFoo != null) { - id1 = swift.memory.retain(value.optionalFoo); - } else { - id1 = undefined; - } - i32Stack.push(id1 !== undefined ? id1 : 0); - } else { - i32Stack.push(0); + const objId = swift.memory.retain(value.optionalFoo); + i32Stack.push(objId); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const objectId = i32Stack.pop(); - let value; - if (objectId !== 0) { - value = swift.memory.getObject(objectId); - swift.memory.release(objectId); - } else { - value = null; - } - optional = value; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; - } - const objectId1 = i32Stack.pop(); - let value1; - if (objectId1 !== 0) { - value1 = swift.memory.getObject(objectId1); - swift.memory.release(objectId1); + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + optValue = obj; + } + const objectId = i32Stack.pop(); + let value; + if (objectId !== 0) { + value = swift.memory.getObject(objectId); + swift.memory.release(objectId); } else { - value1 = null; + value = null; } - return { foo: value1, optionalFoo: optional }; + return { foo: value, optionalFoo: optValue }; } }); @@ -303,8 +291,6 @@ export async function createInstantiator(options, swift) { if (isSome) { const objId = swift.memory.retain(elem); i32Stack.push(objId); - } else { - i32Stack.push(0); } i32Stack.push(isSome); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index cc973e379..617bda36b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -41,42 +41,38 @@ export async function createInstantiator(options, swift) { const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - const isSome = value.optCount != null; + const isSome = value.optCount != null ? 1 : 0; if (isSome) { i32Stack.push((value.optCount | 0)); - } else { - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); - const isSome1 = value.optFlag != null; + i32Stack.push(isSome); + const isSome1 = value.optFlag != null ? 1 : 0; if (isSome1) { i32Stack.push(value.optFlag ? 1 : 0); - } else { - i32Stack.push(0); } - i32Stack.push(isSome1 ? 1 : 0); + i32Stack.push(isSome1); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const bool = i32Stack.pop() !== 0; - optional = bool; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const bool = i32Stack.pop() !== 0; + optValue = bool; } const isSome1 = i32Stack.pop(); - let optional1; - if (isSome1) { - const int = i32Stack.pop(); - optional1 = int; + let optValue1; + if (isSome1 === 0) { + optValue1 = null; } else { - optional1 = null; + const int = i32Stack.pop(); + optValue1 = int; } const string = strStack.pop(); const f64 = f64Stack.pop(); const f641 = f64Stack.pop(); - return { x: f641, y: f64, label: string, optCount: optional1, optFlag: optional }; + return { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; } }); const __bjs_createAddressHelpers = () => ({ @@ -89,26 +85,24 @@ export async function createInstantiator(options, swift) { const id1 = swift.memory.retain(bytes1); i32Stack.push(bytes1.length); i32Stack.push(id1); - const isSome = value.zipCode != null; + const isSome = value.zipCode != null ? 1 : 0; if (isSome) { i32Stack.push((value.zipCode | 0)); - } else { - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const int = i32Stack.pop(); - optional = int; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const int = i32Stack.pop(); + optValue = int; } const string = strStack.pop(); const string1 = strStack.pop(); - return { street: string1, city: string, zipCode: optional }; + return { street: string1, city: string, zipCode: optValue }; } }); const __bjs_createPersonHelpers = () => ({ @@ -119,31 +113,28 @@ export async function createInstantiator(options, swift) { i32Stack.push(id); i32Stack.push((value.age | 0)); structHelpers.Address.lower(value.address); - const isSome = value.email != null; + 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); - } else { - i32Stack.push(0); - i32Stack.push(0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const string = strStack.pop(); - optional = string; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const string = strStack.pop(); + optValue = string; } const struct = structHelpers.Address.lift(); const int = i32Stack.pop(); const string1 = strStack.pop(); - return { name: string1, age: int, address: struct, email: optional }; + return { name: string1, age: int, address: struct, email: optValue }; } }); const __bjs_createSessionHelpers = () => ({ @@ -162,26 +153,24 @@ export async function createInstantiator(options, swift) { lower: (value) => { f64Stack.push(value.value); f32Stack.push(Math.fround(value.precision)); - const isSome = value.optionalPrecision != null; + const isSome = value.optionalPrecision != null ? 1 : 0; if (isSome) { f32Stack.push(Math.fround(value.optionalPrecision)); - } else { - f32Stack.push(0.0); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const rawValue = f32Stack.pop(); - optional = rawValue; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; + const rawValue = f32Stack.pop(); + optValue = rawValue; } const rawValue1 = f32Stack.pop(); const f64 = f64Stack.pop(); - return { value: f64, precision: rawValue1, optionalPrecision: optional }; + return { value: f64, precision: rawValue1, optionalPrecision: optValue }; } }); const __bjs_createConfigStructHelpers = () => ({ @@ -200,45 +189,33 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const isSome = value.optionalObject != null; + const isSome = value.optionalObject != null ? 1 : 0; if (isSome) { - let id1; - if (value.optionalObject != null) { - id1 = swift.memory.retain(value.optionalObject); - } else { - id1 = undefined; - } - i32Stack.push(id1 !== undefined ? id1 : 0); - } else { - i32Stack.push(0); + const objId = swift.memory.retain(value.optionalObject); + i32Stack.push(objId); } - i32Stack.push(isSome ? 1 : 0); + i32Stack.push(isSome); }, lift: () => { const isSome = i32Stack.pop(); - let optional; - if (isSome) { - const objectId = i32Stack.pop(); - let value; - if (objectId !== 0) { - value = swift.memory.getObject(objectId); - swift.memory.release(objectId); - } else { - value = null; - } - optional = value; + let optValue; + if (isSome === 0) { + optValue = null; } else { - optional = null; - } - const objectId1 = i32Stack.pop(); - let value1; - if (objectId1 !== 0) { - value1 = swift.memory.getObject(objectId1); - swift.memory.release(objectId1); + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + optValue = obj; + } + const objectId = i32Stack.pop(); + let value; + if (objectId !== 0) { + value = swift.memory.getObject(objectId); + swift.memory.release(objectId); } else { - value1 = null; + value = null; } - return { object: value1, optionalObject: optional }; + return { object: value, optionalObject: optValue }; } }); diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 5adccdc04..2f1e7feb0 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -146,6 +146,37 @@ public protocol _BridgedSwiftStackType { associatedtype StackLiftResult = Self static func bridgeJSStackPop() -> StackLiftResult consuming func bridgeJSStackPush() + + // MARK: Specialization points + + /// Specialization point for popping an `Optional` + static func bridgeJSStackPopAsOptional() -> StackLiftResult? + /// Specialization point for pushing an `Optional` + static func bridgeJSStackPushAsOptional(_ value: consuming Self?) +} + +extension _BridgedSwiftStackType { + /// Default implementation for popping an `Optional` using + /// a leading discriminator on the stack (0 for nil, 1 for some). + public static func bridgeJSStackPopAsOptional() -> StackLiftResult? { + let isSome = _swift_js_pop_i32() + if isSome == 0 { + return nil + } + return Self.bridgeJSStackPop() + } + + /// Default implementation for pushing an `Optional` using + /// a leading discriminator on the stack (0 for nil, 1 for some). + public static func bridgeJSStackPushAsOptional(_ value: consuming Self?) { + switch consume value { + case .none: + _swift_js_push_i32(0) + case .some(let value): + value.bridgeJSStackPush() + _swift_js_push_i32(1) + } + } } /// Types that bridge with the same (isSome, value) ABI as Optional. @@ -604,7 +635,8 @@ extension _BridgedSwiftCaseEnum { /// A protocol that Swift associated value enum types conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftAssociatedValueEnum: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftStackType { +public protocol _BridgedSwiftAssociatedValueEnum: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftStackType +where StackLiftResult == Self { /// Pops the payload of the associated value enum from the stack. /// /// - Parameter caseId: The enum case ID. @@ -626,6 +658,23 @@ 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) } @@ -646,7 +695,8 @@ extension _BridgedSwiftAssociatedValueEnum { /// A protocol that Swift struct types conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftStruct: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftGenericOptionalStackType { +public protocol _BridgedSwiftStruct: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftStackType +where StackLiftResult == Self { // MARK: ExportSwift @_spi(BridgeJS) static func bridgeJSStackPop() -> Self @_spi(BridgeJS) consuming func bridgeJSStackPush() -> Void @@ -1227,7 +1277,9 @@ extension Optional { } } -public protocol _BridgedSwiftOptionalScalarBridge: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +public protocol _BridgedSwiftOptionalScalarBridge: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, + _BridgedSwiftStackType +where StackLiftResult == Self { @_spi(BridgeJS) static func bridgeJSPopOptionalScalarPayload() -> WasmCoreType @_spi(BridgeJS) static var bridgeJSOptionalScalarNonePayload: WasmCoreType { get } @_spi(BridgeJS) static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: WasmCoreType) @@ -1324,12 +1376,6 @@ extension Optional where Wrapped: _BridgedSwiftOptionalScalarBridge { return Wrapped.bridgeJSLiftParameter(wrappedValue) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = Wrapped.bridgeJSPopOptionalScalarPayload() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { switch consume self { case .none: @@ -1378,13 +1424,6 @@ extension Optional where Wrapped == String { _bridgeJSLiftParameter(isSome, (bytes, count), liftWrapped: { String.bridgeJSLiftParameter($0.0, $0.1) }) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> String? { - let isSome = _swift_js_pop_i32() - let bytes = _swift_js_pop_i32() - let count = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, bytes, count) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> String? { let length = _swift_js_get_optional_string() if length < 0 { @@ -1418,12 +1457,6 @@ extension Optional where Wrapped == JSObject { _bridgeJSLiftParameter(isSome, objectId, liftWrapped: JSObject.bridgeJSLiftParameter) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> JSObject? { - let isSome = _swift_js_pop_i32() - let objectId = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, objectId) - } - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { _bridgeJSLowerReturn( noneValue: 0, @@ -1466,32 +1499,14 @@ extension Optional where Wrapped == JSValue { } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> JSValue? { - let isSome = _swift_js_pop_i32() - if isSome == 0 { - return nil - } - let payload2 = _swift_js_pop_f64() - let payload1 = _swift_js_pop_i32() - let kind = _swift_js_pop_i32() - return JSValue.bridgeJSLiftParameter(kind, payload1, payload2) - } - - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { - switch self { - case .none: - _swift_js_push_i32(0) - case .some(let value): - value.bridgeJSLowerReturn() - _swift_js_push_i32(1) - } + @_spi(BridgeJS) public func bridgeJSLowerReturn() { + self.bridgeJSStackPush() } } -extension Optional where Wrapped == [JSValue] { - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { +extension Optional { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 + where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { switch consume self { case .none: return 0 @@ -1501,30 +1516,48 @@ extension Optional where Wrapped == [JSValue] { } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> [JSValue]? { - if isSome == 0 { - return nil - } - return [JSValue].bridgeJSLiftParameter() + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> [Element]? + where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { + return self.bridgeJSStackPop() } - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [JSValue]? { - let isSome = _swift_js_pop_i32() - if isSome == 0 { - return nil - } - return [JSValue].bridgeJSLiftReturn() + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [Element]? + where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { + return self.bridgeJSStackPop() } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void + where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { + self.bridgeJSStackPush() + } +} + +extension Optional { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 + where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { switch consume self { case .none: - _swift_js_push_i32(0) - case .some(let array): - array.bridgeJSLowerReturn() - _swift_js_push_i32(1) + return 0 + case .some(let value): + value.bridgeJSLowerReturn() + return 1 } } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> [String: Value]? + where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { + return self.bridgeJSStackPop() + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Value]? + where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { + return self.bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void + where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { + self.bridgeJSStackPush() + } } extension Optional where Wrapped: _BridgedSwiftProtocolWrapper { @@ -1583,12 +1616,6 @@ extension Optional where Wrapped: _BridgedSwiftHeapObject { _bridgeJSLiftParameter(isSome, pointer, liftWrapped: Wrapped.bridgeJSLiftParameter) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let pointer = _swift_js_pop_pointer() - return bridgeJSLiftParameter(isSome, pointer) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let pointer = _swift_js_get_optional_heap_object_pointer() if pointer == UnsafeMutableRawPointer(bitPattern: 0) { @@ -1620,12 +1647,6 @@ extension Optional where Wrapped: _BridgedSwiftCaseEnum { _bridgeJSLiftParameter(isSome, wrappedValue, liftWrapped: Wrapped.bridgeJSLiftParameter) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Wrapped? { if value == -1 { return nil @@ -1687,12 +1708,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres let optionalRawValue: String? = self?.rawValue optionalRawValue.bridgeJSLowerReturn() } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let bytes = _swift_js_pop_i32() - let count = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, bytes, count) - } } extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { @@ -1711,12 +1726,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_int_presence() if isSome == 0 { @@ -1741,12 +1750,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { let optionalRawValue: Bool? = self?.rawValue optionalRawValue.bridgeJSLowerReturn() @@ -1772,12 +1775,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = _swift_js_pop_f32() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_float_presence() if isSome == 0 { @@ -1813,12 +1810,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let wrappedValue = _swift_js_pop_f64() - return bridgeJSLiftParameter(isSome, wrappedValue) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_double_presence() if isSome == 0 { @@ -1838,22 +1829,6 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres // MARK: Optional Associated Value Enum Support extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { - private static func bridgeJSStackPopPayload(_ discriminant: Int32) -> Wrapped? { - if discriminant == -1 { - return nil - } else { - return Wrapped.bridgeJSStackPopPayload(discriminant) - } - } - private consuming func bridgeJSStackPushPayload() -> Int32 { - switch consume self { - case .none: - return -1 - case .some(let value): - return value.bridgeJSStackPushPayload() - } - } - // MARK: ExportSwift @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { @@ -1874,27 +1849,16 @@ extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Wrapped? { - return bridgeJSStackPopPayload(caseId) + if caseId == -1 { + return nil + } else { + return Wrapped.bridgeJSStackPopPayload(caseId) + } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { bridgeJSStackPush() } - - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - let caseId = _swift_js_pop_i32() - return bridgeJSLiftParameter(isSome, caseId) - } - - @_spi(BridgeJS) public consuming func bridgeJSStackPush() -> Void { - switch consume self { - case .none: - _swift_js_push_i32(-1) // Use -1 as sentinel for null - case .some(let value): - value.bridgeJSStackPush() - } - } } // MARK: Optional Struct Support @@ -1907,53 +1871,45 @@ extension Optional where Wrapped: _BridgedSwiftStruct { return Wrapped.bridgeJSStackPop() } } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + bridgeJSStackPush() + } + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Wrapped? { - return bridgeJSStackPop() + bridgeJSStackPop() } } -// MARK: - Generic Optional Stack Support - -/// Marker protocol for types whose Optional wrapper should use the generic -/// stack-based ABI (`_BridgedSwiftStackType`). Only Array, Dictionary, and -/// `_BridgedSwiftStruct` conform. Primitives and other types keep their -/// own type-specific Optional extensions. -public protocol _BridgedSwiftGenericOptionalStackType: _BridgedSwiftStackType -where StackLiftResult == Self {} +// MARK: - Optional _BridgedSwiftStackType conformance +// The default push/pop implementation just goes through +// `_BridgedSwiftStackType.bridgeJSStackPushAsOptional`, but some +// Wrapped types (e.g. case enums) have a more efficient implementation. extension Optional: _BridgedSwiftStackType -where Wrapped: _BridgedSwiftGenericOptionalStackType { +where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { public typealias StackLiftResult = Wrapped? @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - let isSome = _swift_js_pop_i32() - if isSome == 0 { - return nil - } - return Wrapped.bridgeJSStackPop() + return Wrapped.bridgeJSStackPopAsOptional() } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - switch consume self { - case .none: - _swift_js_push_i32(0) - case .some(let value): - value.bridgeJSStackPush() - _swift_js_push_i32(1) - } + Wrapped.bridgeJSStackPushAsOptional(self) } +} - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Wrapped? { - return bridgeJSStackPop() - } +// MARK: - _BridgedAsOptional (JSUndefinedOr) delegating to Optional - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - bridgeJSStackPush() +extension _BridgedAsOptional where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + asOptional.bridgeJSStackPush() } } -// MARK: - _BridgedAsOptional (JSUndefinedOr) delegating to Optional - extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarBridge { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Wrapped.WasmCoreType @@ -1968,10 +1924,6 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarBridge { Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { asOptional.bridgeJSLowerReturn() } @@ -2002,10 +1954,6 @@ extension _BridgedAsOptional where Wrapped == String { Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2024,10 +1972,6 @@ extension _BridgedAsOptional where Wrapped == JSObject { Self(optional: Optional.bridgeJSLiftParameter(isSome, objectId)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { asOptional.bridgeJSLowerReturn() } @@ -2056,10 +2000,6 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftHeapObject { Self(optional: Optional.bridgeJSLiftParameter(isSome, pointer)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2078,10 +2018,6 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { Self(optional: Optional.bridgeJSLiftReturn(caseId)) } @@ -2105,10 +2041,6 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2128,10 +2060,6 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2147,10 +2075,6 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { asOptional.bridgeJSLowerReturn() } @@ -2166,10 +2090,6 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2189,10 +2109,6 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) } @@ -2211,10 +2127,6 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) } - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { Self(optional: Optional.bridgeJSLiftReturn(caseId)) } @@ -2232,20 +2144,10 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftStruct { @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { asOptional.bridgeJSLowerReturn() } - - // MARK: Stack ABI - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - asOptional.bridgeJSStackPush() - } } // MARK: - Array Support -extension Array: _BridgedSwiftGenericOptionalStackType -where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element {} extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element { public typealias StackLiftResult = [Element] @@ -2286,14 +2188,12 @@ extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, E // MARK: - Dictionary Support public protocol _BridgedSwiftDictionaryStackType: _BridgedSwiftTypeLoweredIntoVoidType, - _BridgedSwiftGenericOptionalStackType -{ + _BridgedSwiftStackType +where StackLiftResult == Self { associatedtype DictionaryValue: _BridgedSwiftStackType where DictionaryValue.StackLiftResult == DictionaryValue } -extension Dictionary: _BridgedSwiftGenericOptionalStackType -where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value {} extension Dictionary: _BridgedSwiftStackType where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { public typealias StackLiftResult = [String: Value] @@ -2372,6 +2272,10 @@ extension Optional where Wrapped: _BridgedSwiftDictionaryStackType { @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Wrapped.DictionaryValue]? { return bridgeJSStackPopPayload(_swift_js_pop_i32()) } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + bridgeJSStackPush() + } } extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { diff --git a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift index ea4ffea44..e4875486a 100644 --- a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift @@ -16,10 +16,6 @@ import JavaScriptKit @JSFunction static func jsRoundTripBoolArray(_ values: [Bool]) throws(JSException) -> [Bool] @JSFunction static func jsRoundTripJSValueArray(_ v: [JSValue]) throws(JSException) -> [JSValue] - @JSFunction static func jsRoundTripOptionalJSValueArray( - _ v: Optional<[JSValue]> - ) throws(JSException) -> Optional<[JSValue]> - @JSFunction static func jsRoundTripJSObjectArray(_ values: [JSObject]) throws(JSException) -> [JSObject] @JSFunction static func jsRoundTripJSClassArray( @@ -93,13 +89,6 @@ final class ArraySupportTests: XCTestCase { XCTAssertEqual(try ArraySupportImports.jsRoundTripJSValueArray([]), []) } - func testRoundTripOptionalJSValueArray() throws { - XCTAssertNil(try ArraySupportImports.jsRoundTripOptionalJSValueArray(nil)) - let values: [JSValue] = [.number(1), .undefined, .null] - let result = try ArraySupportImports.jsRoundTripOptionalJSValueArray(values) - XCTAssertEqual(result, values) - } - func testRoundTripJSObjectArray() throws { let values: [JSObject] = [.global, JSObject(), ["a": 1, "b": 2]] let result = try ArraySupportImports.jsRoundTripJSObjectArray(values) diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 8acb0a347..048400d42 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -2689,18 +2689,10 @@ extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { param0.bridgeJSStackPush() return Int32(1) case .optPrecision(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .optDirection(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(3) case .empty: return Int32(4) @@ -3041,35 +3033,19 @@ extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { param0.bridgeJSStackPush() return Int32(0) case .optClass(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(1) case .optJSObject(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .optNestedEnum(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(3) case .optArray(let param0): param0.bridgeJSStackPush() return Int32(4) case .optJsClass(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.jsObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(5) case .empty: return Int32(6) @@ -3094,40 +3070,16 @@ extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0, let param1): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - __bjs_unwrapped_param1.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) case .status(let param0, let param1, let param2): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - __bjs_unwrapped_param0.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - __bjs_unwrapped_param1.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - __bjs_unwrapped_param2.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(2) } } @@ -3260,16 +3212,8 @@ extension DataPoint: _BridgedSwiftStruct { self.x.bridgeJSStackPush() self.y.bridgeJSStackPush() self.label.bridgeJSStackPush() - let __bjs_isSome_optCount = self.optCount != nil - if let __bjs_unwrapped_optCount = self.optCount { - __bjs_unwrapped_optCount.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optCount ? 1 : 0) - let __bjs_isSome_optFlag = self.optFlag != nil - if let __bjs_unwrapped_optFlag = self.optFlag { - __bjs_unwrapped_optFlag.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optFlag ? 1 : 0) + self.optCount.bridgeJSStackPush() + self.optFlag.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -3389,11 +3333,7 @@ extension Address: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.street.bridgeJSStackPush() self.city.bridgeJSStackPush() - let __bjs_isSome_zipCode = self.zipCode != nil - if let __bjs_unwrapped_zipCode = self.zipCode { - __bjs_unwrapped_zipCode.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_zipCode ? 1 : 0) + self.zipCode.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -3446,11 +3386,7 @@ extension Contact: _BridgedSwiftStruct { self.name.bridgeJSStackPush() self.age.bridgeJSStackPush() self.address.bridgeJSStackPush() - let __bjs_isSome_email = self.email != nil - if let __bjs_unwrapped_email = self.email { - __bjs_unwrapped_email.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) + self.email.bridgeJSStackPush() self.secondaryAddress.bridgeJSStackPush() } @@ -3501,16 +3437,8 @@ extension Config: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.name.bridgeJSStackPush() - let __bjs_isSome_theme = self.theme != nil - if let __bjs_unwrapped_theme = self.theme { - __bjs_unwrapped_theme.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_theme ? 1 : 0) - let __bjs_isSome_direction = self.direction != nil - if let __bjs_unwrapped_direction = self.direction { - __bjs_unwrapped_direction.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_direction ? 1 : 0) + self.theme.bridgeJSStackPush() + self.direction.bridgeJSStackPush() self.status.bridgeJSStackPush() } @@ -3559,11 +3487,7 @@ extension SessionData: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.id.bridgeJSStackPush() - let __bjs_isSome_owner = self.owner != nil - if let __bjs_unwrapped_owner = self.owner { - __bjs_unwrapped_owner.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_owner ? 1 : 0) + self.owner.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -3614,16 +3538,8 @@ extension ValidationReport: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.id.bridgeJSStackPush() self.result.bridgeJSStackPush() - let __bjs_isSome_status = self.status != nil - if let __bjs_unwrapped_status = self.status { - __bjs_unwrapped_status.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_status ? 1 : 0) - let __bjs_isSome_outcome = self.outcome != nil - if let __bjs_unwrapped_outcome = self.outcome { - __bjs_unwrapped_outcome.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_outcome ? 1 : 0) + self.status.bridgeJSStackPush() + self.outcome.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -3683,16 +3599,8 @@ extension AdvancedConfig: _BridgedSwiftStruct { self.enabled.bridgeJSStackPush() self.theme.bridgeJSStackPush() self.status.bridgeJSStackPush() - let __bjs_isSome_result = self.result != nil - if let __bjs_unwrapped_result = self.result { - __bjs_unwrapped_result.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_result ? 1 : 0) - let __bjs_isSome_metadata = self.metadata != nil - if let __bjs_unwrapped_metadata = self.metadata { - __bjs_unwrapped_metadata.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_metadata ? 1 : 0) + self.result.bridgeJSStackPush() + self.metadata.bridgeJSStackPush() self.location.bridgeJSStackPush() self.defaults.bridgeJSStackPush() self.overrideDefaults.bridgeJSStackPush() @@ -3746,16 +3654,8 @@ extension MeasurementConfig: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.precision.bridgeJSStackPush() self.ratio.bridgeJSStackPush() - let __bjs_isSome_optionalPrecision = self.optionalPrecision != nil - if let __bjs_unwrapped_optionalPrecision = self.optionalPrecision { - __bjs_unwrapped_optionalPrecision.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalPrecision ? 1 : 0) - let __bjs_isSome_optionalRatio = self.optionalRatio != nil - if let __bjs_unwrapped_optionalRatio = self.optionalRatio { - __bjs_unwrapped_optionalRatio.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalRatio ? 1 : 0) + self.optionalPrecision.bridgeJSStackPush() + self.optionalRatio.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -3893,11 +3793,7 @@ extension CopyableCart: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.x.bridgeJSStackPush() - let __bjs_isSome_note = self.note != nil - if let __bjs_unwrapped_note = self.note { - __bjs_unwrapped_note.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_note ? 1 : 0) + self.note.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -4177,11 +4073,7 @@ extension JSObjectContainer: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.object.bridgeJSStackPush() - let __bjs_isSome_optionalObject = self.optionalObject != nil - if let __bjs_unwrapped_optionalObject = self.optionalObject { - __bjs_unwrapped_optionalObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalObject ? 1 : 0) + self.optionalObject.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -4229,11 +4121,7 @@ extension FooContainer: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { self.foo.jsObject.bridgeJSStackPush() - let __bjs_isSome_optionalFoo = self.optionalFoo != nil - if let __bjs_unwrapped_optionalFoo = self.optionalFoo { - __bjs_unwrapped_optionalFoo.jsObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_optionalFoo ? 1 : 0) + self.optionalFoo.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { @@ -5815,11 +5703,7 @@ public func _bjs_roundTripOptionalIntArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -5842,11 +5726,7 @@ public func _bjs_roundTripOptionalStringArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -5892,11 +5772,7 @@ public func _bjs_roundTripOptionalDirectionArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -5919,11 +5795,7 @@ public func _bjs_roundTripOptionalStatusArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -6144,11 +6016,7 @@ public func _bjs_roundTripOptionalJSObjectArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -6182,11 +6050,7 @@ public func _bjs_roundTripOptionalFooArray() -> Void { return __result }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.jsObject.bridgeJSStackPush() - } - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + __bjs_elem_ret.bridgeJSStackPush() } _swift_js_push_i32(Int32(ret.count)) #else @@ -9511,18 +9375,6 @@ fileprivate func bjs_ArraySupportImports_jsRoundTripJSValueArray_static_extern() return bjs_ArraySupportImports_jsRoundTripJSValueArray_static_extern() } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static") -fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern(_ v: Int32) -> Void -#else -fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern(_ v: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static(_ v: Int32) -> Void { - return bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern(v) -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripJSObjectArray_static") fileprivate func bjs_ArraySupportImports_jsRoundTripJSObjectArray_static_extern() -> Void @@ -9625,15 +9477,6 @@ func _$ArraySupportImports_jsRoundTripJSValueArray(_ v: [JSValue]) throws(JSExce return [JSValue].bridgeJSLiftReturn() } -func _$ArraySupportImports_jsRoundTripOptionalJSValueArray(_ v: Optional<[JSValue]>) throws(JSException) -> Optional<[JSValue]> { - let vIsSome = v.bridgeJSLowerParameter() - bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static(vIsSome) - if let error = _swift_js_take_exception() { - throw error - } - return Optional<[JSValue]>.bridgeJSLiftReturn() -} - func _$ArraySupportImports_jsRoundTripJSObjectArray(_ values: [JSObject]) throws(JSException) -> [JSObject] { let _ = values.bridgeJSLowerParameter() bjs_ArraySupportImports_jsRoundTripJSObjectArray_static() @@ -11445,6 +11288,30 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_s return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameValue) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(_ v: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(_ v: Int32) -> 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) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(_ v: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(_ v: Int32) -> 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) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void @@ -11493,6 +11360,24 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringUndefined(_ name: JSUndef return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() } +func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull(_ v: Optional<[JSValue]>) throws(JSException) -> Optional<[JSValue]> { + let vIsSome = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static(vIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional<[JSValue]>.bridgeJSLiftReturn() +} + +func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull(_ v: Optional<[String: String]>) throws(JSException) -> Optional<[String: String]> { + let vIsSome = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static(vIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional<[String: String]>.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 42b6abfbb..4b33632b5 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -13996,42 +13996,6 @@ } } }, - { - "name" : "jsRoundTripOptionalJSValueArray", - "parameters" : [ - { - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { - - } - } - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { - - } - } - } - }, - "_1" : "null" - } - } - }, { "name" : "jsRoundTripJSObjectArray", "parameters" : [ @@ -16118,6 +16082,78 @@ } } }, + { + "name" : "jsRoundTripOptionalJSValueArrayNull", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "jsRoundTripOptionalStringToStringDictionaryNull", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, { "name" : "runJsOptionalSupportTests", "parameters" : [ diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index 58215560c..1a41cc43f 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -32,6 +32,12 @@ export function getImports(importsContext) { jsRoundTripOptionalStringUndefined: (v) => { return v === undefined ? undefined : v; }, + jsRoundTripOptionalJSValueArrayNull: (v) => { + return v ?? null; + }, + jsRoundTripOptionalStringToStringDictionaryNull: (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 a99bb0bb1..c8cc9894b 100644 --- a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -10,6 +10,20 @@ import JavaScriptEventLoop _ name: JSUndefinedOr ) throws -> JSUndefinedOr + @JSFunction static func jsRoundTripOptionalJSValueArrayNull( + _ v: Optional<[JSValue]> + ) throws(JSException) -> Optional<[JSValue]> + // @JSFunction static func jsRoundTripOptionalJSValueArrayUndefined( + // _ v: JSUndefinedOr<[JSValue]> + // ) throws(JSException) -> JSUndefinedOr<[JSValue]> + + @JSFunction static func jsRoundTripOptionalStringToStringDictionaryNull( + _ v: Optional<[String: String]> + ) throws(JSException) -> Optional<[String: String]> + // @JSFunction static func jsRoundTripOptionalStringToStringDictionaryUndefined( + // _ v: JSUndefinedOr<[String: String]> + // ) throws(JSException) -> JSUndefinedOr<[String: String]> + @JSFunction static func runJsOptionalSupportTests() throws(JSException) } @@ -51,6 +65,22 @@ final class OptionalSupportTests: XCTestCase { func testRoundTripOptionalNumberUndefined() throws { try roundTripTest(OptionalSupportImports.jsRoundTripOptionalNumberUndefined, 42) } + + func testRoundTripOptionalJSValueArrayNull() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalJSValueArrayNull, [.number(1), .undefined, .null]) + } + + // func testRoundTripOptionalJSValueArrayUndefined() throws { + // try roundTripTest(OptionalSupportImports.jsRoundTripOptionalJSValueArrayUndefined, [.number(1), .undefined, .null]) + // } + + func testRoundTripOptionalStringToStringDictionaryNull() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryNull, ["key": "value"]) + } + + // func testRoundTripOptionalStringToStringDictionaryUndefined() throws { + // try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryUndefined, ["key": "value"]) + // } } // MARK: - Optional Bridging From 1746d9791d43d725d9fae6c995ee73cf7969654d Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Wed, 25 Feb 2026 17:36:05 +0900 Subject: [PATCH 003/140] BridgeJS: Remove inline array lifting/lowering codegen --- Benchmarks/Sources/Generated/BridgeJS.swift | 64 ++-------- .../Sources/BridgeJSCore/ExportSwift.swift | 66 +--------- .../BridgeJSCodegenTests/ArrayTypes.swift | 96 ++------------- .../ImportedTypeInExportedInterface.swift | 20 +-- .../Generated/BridgeJS.swift | 116 +++--------------- 5 files changed, 41 insertions(+), 321 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 77fefad8a..bf033ae21 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -1578,16 +1578,7 @@ public func _bjs_ArrayRoundtrip_roundtripNestedPointArray(_ _self: UnsafeMutable @_cdecl("bjs_ArrayRoundtrip_takeOptionalIntArray") public func _bjs_ArrayRoundtrip_takeOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalIntArray(_: [Optional].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1598,10 +1589,7 @@ public func _bjs_ArrayRoundtrip_takeOptionalIntArray(_ _self: UnsafeMutableRawPo public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalIntArray() - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1611,20 +1599,8 @@ public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalIntArray") public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalIntArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1634,16 +1610,7 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutable @_cdecl("bjs_ArrayRoundtrip_takeOptionalPointArray") public func _bjs_ArrayRoundtrip_takeOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalPointArray(_: [Optional].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1654,10 +1621,7 @@ public func _bjs_ArrayRoundtrip_takeOptionalPointArray(_ _self: UnsafeMutableRaw public func _bjs_ArrayRoundtrip_makeOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalPointArray() - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1667,20 +1631,8 @@ public func _bjs_ArrayRoundtrip_makeOptionalPointArray(_ _self: UnsafeMutableRaw @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalPointArray") public func _bjs_ArrayRoundtrip_roundtripOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalPointArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 12d472cbe..4280b266d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -713,14 +713,12 @@ struct StackCodegen { switch type { case .string, .int, .uint, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, - .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum: + .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array: return "\(raw: type.swiftType).bridgeJSStackPop()" case .jsObject(let className?): return "\(raw: className)(unsafelyWrapping: JSObject.bridgeJSStackPop())" case .nullable(let wrappedType, let kind): return liftNullableExpression(wrappedType: wrappedType, kind: kind) - case .array(let elementType): - return liftArrayExpression(elementType: elementType) case .dictionary(let valueType): return liftDictionaryExpression(valueType: valueType) case .closure: @@ -730,36 +728,6 @@ struct StackCodegen { } } - func liftArrayExpression(elementType: BridgeType) -> ExprSyntax { - switch elementType { - case .jsObject(let className?) where className != "JSObject": - return "[JSObject].bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" - case .nullable, .closure: - return liftArrayExpressionInline(elementType: elementType) - case .void, .namespaceEnum: - fatalError("Invalid array element type: \(elementType)") - default: - return "[\(raw: elementType.swiftType)].bridgeJSStackPop()" - } - } - - private func liftArrayExpressionInline(elementType: BridgeType) -> ExprSyntax { - let elementLift = liftExpression(for: elementType) - let swiftTypeName = elementType.swiftType - return """ - { - let __count = Int(_swift_js_pop_i32()) - var __result: [\(raw: swiftTypeName)] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(\(elementLift)) - } - __result.reverse() - return __result - }() - """ - } - func liftDictionaryExpression(valueType: BridgeType) -> ExprSyntax { switch valueType { case .jsObject(let className?) where className != "JSObject": @@ -845,16 +813,8 @@ struct StackCodegen { varPrefix: String ) -> [CodeBlockItemSyntax] { switch elementType { - case .jsObject(let className?) where className != "JSObject": - return ["\(raw: accessor).map { $0.jsObject }.bridgeJSStackPush()"] case .swiftProtocol: return ["\(raw: accessor).map { $0 as! \(raw: elementType.swiftType) }.bridgeJSStackPush()"] - case .nullable, .closure: - return lowerArrayStatementsInline( - elementType: elementType, - accessor: accessor, - varPrefix: varPrefix - ) case .void, .namespaceEnum: fatalError("Invalid array element type: \(elementType)") default: @@ -862,30 +822,6 @@ struct StackCodegen { } } - private func lowerArrayStatementsInline( - elementType: BridgeType, - accessor: String, - varPrefix: String - ) -> [CodeBlockItemSyntax] { - var statements: [String] = [] - let elementVarName = "__bjs_elem_\(varPrefix)" - statements.append("for \(elementVarName) in \(accessor) {") - - let elementStatements = lowerStatements( - for: elementType, - accessor: elementVarName, - varPrefix: "\(varPrefix)_elem" - ) - for stmt in elementStatements { - statements.append(stmt.description) - } - - statements.append("}") - statements.append("_swift_js_push_i32(Int32(\(accessor).count))") - let parsed: CodeBlockItemListSyntax = "\(raw: statements.joined(separator: "\n"))" - return Array(parsed) - } - private func lowerDictionaryStatements( valueType: BridgeType, accessor: String, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index 6ced24393..0d95a5b7f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -228,20 +228,8 @@ public func _bjs_processOpaquePointerArray() -> Void { @_cdecl("bjs_processOptionalIntArray") public func _bjs_processOptionalIntArray() -> Void { #if arch(wasm32) - let ret = processOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalIntArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -251,20 +239,8 @@ public func _bjs_processOptionalIntArray() -> Void { @_cdecl("bjs_processOptionalStringArray") public func _bjs_processOptionalStringArray() -> Void { #if arch(wasm32) - let ret = processOptionalStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalStringArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -285,20 +261,8 @@ public func _bjs_processOptionalArray() -> Void { @_cdecl("bjs_processOptionalPointArray") public func _bjs_processOptionalPointArray() -> Void { #if arch(wasm32) - let ret = processOptionalPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalPointArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -308,20 +272,8 @@ public func _bjs_processOptionalPointArray() -> Void { @_cdecl("bjs_processOptionalDirectionArray") public func _bjs_processOptionalDirectionArray() -> Void { #if arch(wasm32) - let ret = processOptionalDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalDirectionArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -331,20 +283,8 @@ public func _bjs_processOptionalDirectionArray() -> Void { @_cdecl("bjs_processOptionalStatusArray") public func _bjs_processOptionalStatusArray() -> Void { #if arch(wasm32) - let ret = processOptionalStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalStatusArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -420,20 +360,8 @@ public func _bjs_processJSObjectArray() -> Void { @_cdecl("bjs_processOptionalJSObjectArray") public func _bjs_processOptionalJSObjectArray() -> Void { #if arch(wasm32) - let ret = processOptionalJSObjectArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index 809dfb43a..f3c3f2fc1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -75,8 +75,8 @@ public func _bjs_makeFoo() -> Int32 { @_cdecl("bjs_processFooArray") public func _bjs_processFooArray() -> Void { #if arch(wasm32) - let ret = processFooArray(_: [JSObject].bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) - ret.map { $0.jsObject }.bridgeJSStackPush() + let ret = processFooArray(_: [Foo].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -86,20 +86,8 @@ public func _bjs_processFooArray() -> Void { @_cdecl("bjs_processOptionalFooArray") public func _bjs_processOptionalFooArray() -> Void { #if arch(wasm32) - let ret = processOptionalFooArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = processOptionalFooArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 048400d42..6a7ce73c2 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -5692,20 +5692,8 @@ public func _bjs_roundTripGreeterArray() -> Void { @_cdecl("bjs_roundTripOptionalIntArray") public func _bjs_roundTripOptionalIntArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalIntArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -5715,20 +5703,8 @@ public func _bjs_roundTripOptionalIntArray() -> Void { @_cdecl("bjs_roundTripOptionalStringArray") public func _bjs_roundTripOptionalStringArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalStringArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -5738,20 +5714,8 @@ public func _bjs_roundTripOptionalStringArray() -> Void { @_cdecl("bjs_roundTripOptionalDataPointArray") public func _bjs_roundTripOptionalDataPointArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalDataPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalDataPointArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -5761,20 +5725,8 @@ public func _bjs_roundTripOptionalDataPointArray() -> Void { @_cdecl("bjs_roundTripOptionalDirectionArray") public func _bjs_roundTripOptionalDirectionArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalDirectionArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -5784,20 +5736,8 @@ public func _bjs_roundTripOptionalDirectionArray() -> Void { @_cdecl("bjs_roundTripOptionalStatusArray") public func _bjs_roundTripOptionalStatusArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalStatusArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -6005,20 +5945,8 @@ public func _bjs_roundTripJSObjectArray() -> Void { @_cdecl("bjs_roundTripOptionalJSObjectArray") public func _bjs_roundTripOptionalJSObjectArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSObjectArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -6028,8 +5956,8 @@ public func _bjs_roundTripOptionalJSObjectArray() -> Void { @_cdecl("bjs_roundTripFooArray") public func _bjs_roundTripFooArray() -> Void { #if arch(wasm32) - let ret = roundTripFooArray(_: [JSObject].bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) - ret.map { $0.jsObject }.bridgeJSStackPush() + let ret = roundTripFooArray(_: [Foo].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -6039,20 +5967,8 @@ public func _bjs_roundTripFooArray() -> Void { @_cdecl("bjs_roundTripOptionalFooArray") public func _bjs_roundTripOptionalFooArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalFooArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0..<__count { - __result.append(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSStackPush() - } - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalFooArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif From 966039292f942450c5f46feadc8219d3449dc780 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Fri, 27 Feb 2026 11:44:59 +0900 Subject: [PATCH 004/140] [NFC] BridgeJS: Cover more Array cases in runtime tests (#678) BridgeJS: Cover more Array cases in runtime tests --- .../ArraySupportTests.swift | 114 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 157 - .../Generated/BridgeJS.swift | 3013 +++--- .../Generated/JavaScript/BridgeJS.json | 8559 +++++++++-------- .../JavaScript/ArraySupportTests.mjs | 166 +- Tests/prelude.mjs | 148 - 6 files changed, 6479 insertions(+), 5678 deletions(-) diff --git a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift index e4875486a..6795c79ec 100644 --- a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift @@ -7,6 +7,10 @@ import JavaScriptKit @JSFunction init(id: String) throws(JSException) } +@JS protocol ArrayElementProtocol { + var value: Int { get set } +} + @JSClass struct ArraySupportImports { @JSFunction static func jsIntArrayLength(_ items: [Int]) throws(JSException) -> Int @@ -22,12 +26,27 @@ import JavaScriptKit _ values: [ArrayElementObject] ) throws(JSException) -> [ArrayElementObject] + @JSFunction static func jsRoundTripOptionalIntArray(_ values: [Int?]) throws(JSException) -> [Int?] + @JSFunction static func jsRoundTripOptionalStringArray(_ values: [String?]) throws(JSException) -> [String?] + @JSFunction static func jsRoundTripOptionalBoolArray(_ values: [Bool?]) throws(JSException) -> [Bool?] + @JSFunction static func jsRoundTripOptionalJSValueArray(_ values: [JSValue?]) throws(JSException) -> [JSValue?] + @JSFunction static func jsRoundTripOptionalJSObjectArray(_ values: [JSObject?]) throws(JSException) -> [JSObject?] + @JSFunction static func jsRoundTripOptionalJSClassArray( + _ values: [ArrayElementObject?] + ) throws(JSException) -> [ArrayElementObject?] + @JSFunction static func jsSumNumberArray(_ values: [Double]) throws(JSException) -> Double @JSFunction static func jsCreateNumberArray() throws(JSException) -> [Double] + + @JSFunction static func runJsArraySupportTests() throws(JSException) } final class ArraySupportTests: XCTestCase { + func testRunJsArraySupportTests() throws { + try ArraySupportImports.runJsArraySupportTests() + } + func testRoundTripIntArray() throws { let values = [1, 2, 3, 4, 5] let result = try ArraySupportImports.jsRoundTripIntArray(values) @@ -105,4 +124,99 @@ final class ArraySupportTests: XCTestCase { XCTAssertEqual(try ArraySupportImports.jsRoundTripJSClassArray([]), []) } + + func testRoundTripOptionalIntArray() throws { + let values = [1, nil, 3, nil, 5] + let result = try ArraySupportImports.jsRoundTripOptionalIntArray(values) + XCTAssertEqual(result, values) + } + + func testRoundTripOptionalStringArray() throws { + let values = ["hello", nil, "world", nil, "🎉"] + let result = try ArraySupportImports.jsRoundTripOptionalStringArray(values) + XCTAssertEqual(result, values) + } + + func testRoundTripOptionalBoolArray() throws { + let values = [true, nil, false, nil, true] + let result = try ArraySupportImports.jsRoundTripOptionalBoolArray(values) + XCTAssertEqual(result, values) + } + + func testRoundTripOptionalJSValueArray() throws { + let values: [JSValue?] = [.number(1), nil, .string("hello"), nil, .object(.global)] + let result = try ArraySupportImports.jsRoundTripOptionalJSValueArray(values) + XCTAssertEqual(result, values) + } + + func testRoundTripOptionalJSObjectArray() throws { + let values = [.global, nil, JSObject(), nil, ["a": 1, "b": 2]] + let result = try ArraySupportImports.jsRoundTripOptionalJSObjectArray(values) + XCTAssertEqual(result, values) + } + + func testRoundTripOptionalJSClassArray() throws { + let values = try [ + ArrayElementObject(id: "1"), nil, ArrayElementObject(id: "2"), nil, ArrayElementObject(id: "3"), + ] + let result = try ArraySupportImports.jsRoundTripOptionalJSClassArray(values) + XCTAssertEqual(result, values) + XCTAssertEqual(try result[0]?.id, "1") + XCTAssertEqual(result[1], nil) + XCTAssertEqual(try result[2]?.id, "2") + XCTAssertEqual(result[3], nil) + XCTAssertEqual(try result[4]?.id, "3") + + XCTAssertEqual(try ArraySupportImports.jsRoundTripOptionalJSClassArray([]), []) + } +} + +@JS enum ArraySupportExports { + @JS static func roundTripIntArray(_ v: [Int]) -> [Int] { v } + @JS static func roundTripStringArray(_ v: [String]) -> [String] { v } + @JS static func roundTripDoubleArray(_ v: [Double]) -> [Double] { v } + @JS static func roundTripBoolArray(_ v: [Bool]) -> [Bool] { v } + @JS static func roundTripUnsafeRawPointerArray(_ v: [UnsafeRawPointer]) -> [UnsafeRawPointer] { v } + @JS static func roundTripUnsafeMutableRawPointerArray(_ v: [UnsafeMutableRawPointer]) -> [UnsafeMutableRawPointer] { + v + } + @JS static func roundTripOpaquePointerArray(_ v: [OpaquePointer]) -> [OpaquePointer] { v } + @JS static func roundTripUnsafePointerArray(_ v: [UnsafePointer]) -> [UnsafePointer] { v } + @JS static func roundTripUnsafeMutablePointerArray( + _ v: [UnsafeMutablePointer] + ) -> [UnsafeMutablePointer] { v } + @JS static func roundTripJSValueArray(_ v: [JSValue]) -> [JSValue] { v } + @JS static func roundTripJSObjectArray(_ v: [JSObject]) -> [JSObject] { v } + @JS static func roundTripCaseEnumArray(_ v: [Direction]) -> [Direction] { v } + @JS static func roundTripStringRawValueEnumArray(_ v: [Theme]) -> [Theme] { v } + @JS static func roundTripIntRawValueEnumArray(_ v: [HttpStatus]) -> [HttpStatus] { v } + @JS static func roundTripStructArray(_ v: [DataPoint]) -> [DataPoint] { v } + @JS static func roundTripSwiftClassArray(_ v: [Greeter]) -> [Greeter] { v } + @JS static func roundTripNamespacedSwiftClassArray(_ v: [Utils.Converter]) -> [Utils.Converter] { v } + @JS static func roundTripProtocolArray(_ v: [ArrayElementProtocol]) -> [ArrayElementProtocol] { v } + @JS static func roundTripJSClassArray(_ v: [ArrayElementObject]) -> [ArrayElementObject] { v } + + @JS static func roundTripOptionalIntArray(_ v: [Int?]) -> [Int?] { v } + @JS static func roundTripOptionalStringArray(_ v: [String?]) -> [String?] { v } + @JS static func roundTripOptionalJSObjectArray(_ v: [JSObject?]) -> [JSObject?] { v } + @JS static func roundTripOptionalCaseEnumArray(_ v: [Direction?]) -> [Direction?] { v } + @JS static func roundTripOptionalStringRawValueEnumArray(_ v: [Theme?]) -> [Theme?] { v } + @JS static func roundTripOptionalIntRawValueEnumArray(_ v: [HttpStatus?]) -> [HttpStatus?] { v } + @JS static func roundTripOptionalStructArray(_ v: [DataPoint?]) -> [DataPoint?] { v } + @JS static func roundTripOptionalSwiftClassArray(_ v: [Greeter?]) -> [Greeter?] { v } + @JS static func roundTripOptionalJSClassArray(_ v: [ArrayElementObject?]) -> [ArrayElementObject?] { v } + + @JS static func roundTripNestedIntArray(_ v: [[Int]]) -> [[Int]] { v } + @JS static func roundTripNestedStringArray(_ v: [[String]]) -> [[String]] { v } + @JS static func roundTripNestedDoubleArray(_ v: [[Double]]) -> [[Double]] { v } + @JS static func roundTripNestedBoolArray(_ v: [[Bool]]) -> [[Bool]] { v } + @JS static func roundTripNestedStructArray(_ v: [[DataPoint]]) -> [[DataPoint]] { v } + @JS static func roundTripNestedCaseEnumArray(_ v: [[Direction]]) -> [[Direction]] { v } + @JS static func roundTripNestedSwiftClassArray(_ v: [[Greeter]]) -> [[Greeter]] { v } + + // MARK: - Multiple Array Parameters + @JS static func multiArrayFirst(_ a: [Int], _ b: [String]) -> [Int] { a } + @JS static func multiArraySecond(_ a: [Int], _ b: [String]) -> [String] { b } + @JS static func multiOptionalArrayFirst(_ a: [Int]?, _ b: [String]?) -> [Int]? { a } + @JS static func multiOptionalArraySecond(_ a: [Int]?, _ b: [String]?) -> [String]? { b } } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 26f587fa3..ead7e0841 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -68,10 +68,6 @@ func runJsWorks() -> Void return v } -@JS func roundTripJSValueArray(v: [JSValue]) -> [JSValue] { - return v -} - @JS func roundTripOptionalJSValueArray(v: [JSValue]?) -> [JSValue]? { return v } @@ -1275,71 +1271,6 @@ enum GraphOperations { // MARK: - Array Tests -// Primitive arrays -@JS func roundTripIntArray(_ values: [Int]) -> [Int] { - return values -} - -@JS func roundTripStringArray(_ values: [String]) -> [String] { - return values -} - -@JS func roundTripDoubleArray(_ values: [Double]) -> [Double] { - return values -} - -@JS func roundTripBoolArray(_ values: [Bool]) -> [Bool] { - return values -} - -// Enum arrays -@JS func roundTripDirectionArray(_ values: [Direction]) -> [Direction] { - return values -} - -@JS func roundTripStatusArray(_ values: [Status]) -> [Status] { - return values -} - -@JS func roundTripThemeArray(_ values: [Theme]) -> [Theme] { - return values -} - -@JS func roundTripHttpStatusArray(_ values: [HttpStatus]) -> [HttpStatus] { - return values -} - -// Struct arrays -@JS func roundTripDataPointArray(_ points: [DataPoint]) -> [DataPoint] { - return points -} - -// Class arrays -@JS func roundTripGreeterArray(_ greeters: [Greeter]) -> [Greeter] { - return greeters -} - -// Arrays of optional elements -@JS func roundTripOptionalIntArray(_ values: [Int?]) -> [Int?] { - return values -} - -@JS func roundTripOptionalStringArray(_ values: [String?]) -> [String?] { - return values -} - -@JS func roundTripOptionalDataPointArray(_ points: [DataPoint?]) -> [DataPoint?] { - return points -} - -@JS func roundTripOptionalDirectionArray(_ directions: [Direction?]) -> [Direction?] { - return directions -} - -@JS func roundTripOptionalStatusArray(_ statuses: [Status?]) -> [Status?] { - return statuses -} - // Optional arrays @JS func roundTripOptionalIntArrayType(_ values: [Int]?) -> [Int]? { return values @@ -1353,94 +1284,6 @@ enum GraphOperations { return greeters } -// Nested arrays - -@JS func roundTripNestedIntArray(_ values: [[Int]]) -> [[Int]] { - return values -} - -@JS func roundTripNestedStringArray(_ values: [[String]]) -> [[String]] { - return values -} - -@JS func roundTripNestedDoubleArray(_ values: [[Double]]) -> [[Double]] { - return values -} - -@JS func roundTripNestedBoolArray(_ values: [[Bool]]) -> [[Bool]] { - return values -} - -@JS func roundTripNestedDataPointArray(_ points: [[DataPoint]]) -> [[DataPoint]] { - return points -} - -@JS func roundTripNestedDirectionArray(_ directions: [[Direction]]) -> [[Direction]] { - return directions -} - -@JS func roundTripNestedGreeterArray(_ greeters: [[Greeter]]) -> [[Greeter]] { - return greeters -} - -@JS func roundTripUnsafeRawPointerArray(_ values: [UnsafeRawPointer]) -> [UnsafeRawPointer] { - return values -} -@JS func roundTripUnsafeMutableRawPointerArray(_ values: [UnsafeMutableRawPointer]) -> [UnsafeMutableRawPointer] { - return values -} -@JS func roundTripOpaquePointerArray(_ values: [OpaquePointer]) -> [OpaquePointer] { - return values -} -@JS func roundTripUnsafePointerArray(_ values: [UnsafePointer]) -> [UnsafePointer] { - return values -} -@JS func roundTripUnsafeMutablePointerArray(_ values: [UnsafeMutablePointer]) -> [UnsafeMutablePointer] { - return values -} - -@JS func consumeDataProcessorArrayType(_ processors: [DataProcessor]) -> Int { - return processors.count -} - -@JS func roundTripDataProcessorArrayType(_ processors: [DataProcessor]) -> [DataProcessor] { - return processors -} - -@JS func roundTripJSObjectArray(_ objects: [JSObject]) -> [JSObject] { - return objects -} - -@JS func roundTripOptionalJSObjectArray(_ objects: [JSObject?]) -> [JSObject?] { - return objects -} - -@JS func roundTripFooArray(_ foos: [Foo]) -> [Foo] { - return foos -} - -@JS func roundTripOptionalFooArray(_ foos: [Foo?]) -> [Foo?] { - return foos -} - -// MARK: - Multiple stack-based parameters (regression test for LIFO ordering) - -@JS func multiArrayFirstNums(nums: [Int], strs: [String]) -> [Int] { - return nums -} - -@JS func multiArrayFirstStrs(nums: [Int], strs: [String]) -> [String] { - return strs -} - -@JS func multiOptionalArrayFirstA(a: [Int]?, b: [String]?) -> [Int]? { - return a -} - -@JS func multiOptionalArrayFirstB(a: [Int]?, b: [String]?) -> [String]? { - return b -} - class ExportAPITests: XCTestCase { func testAll() { var hasDeinitGreeter = false diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 6a7ce73c2..96731a282 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -1643,6 +1643,51 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y #endif } +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_ArrayElementProtocol_value_get") +fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@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_ArrayElementProtocol_value_set") +fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + 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) +} + struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { let jsObject: JSObject @@ -2205,192 +2250,467 @@ fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) } -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() - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripIntArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripIntArray") +public func _bjs_ArraySupportExports_static_roundTripIntArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripIntArray(_: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .north - case 1: - self = .south - case 2: - self = .east - case 3: - self = .west - default: - return nil - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripStringArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripStringArray") +public func _bjs_ArraySupportExports_static_roundTripStringArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripStringArray(_: [String].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private var bridgeJSRawValue: Int32 { - switch self { - case .north: - return 0 - case .south: - return 1 - case .east: - return 2 - case .west: - return 3 - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripDoubleArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripDoubleArray") +public func _bjs_ArraySupportExports_static_roundTripDoubleArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripDoubleArray(_: [Double].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -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() - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripBoolArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripBoolArray") +public func _bjs_ArraySupportExports_static_roundTripBoolArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripBoolArray(_: [Bool].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .loading - case 1: - self = .success - case 2: - self = .error - default: - return nil - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray") +public func _bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private var bridgeJSRawValue: Int32 { - switch self { - case .loading: - return 0 - case .success: - return 1 - case .error: - return 2 - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray") +public func _bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOpaquePointerArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOpaquePointerArray") +public func _bjs_ArraySupportExports_static_roundTripOpaquePointerArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripUnsafePointerArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripUnsafePointerArray") +public func _bjs_ArraySupportExports_static_roundTripUnsafePointerArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripUnsafePointerArray(_: [UnsafePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray") +public func _bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripUnsafeMutablePointerArray(_: [UnsafeMutablePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripJSValueArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripJSValueArray") +public func _bjs_ArraySupportExports_static_roundTripJSValueArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripJSValueArray(_: [JSValue].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -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() - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripJSObjectArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripJSObjectArray") +public func _bjs_ArraySupportExports_static_roundTripJSObjectArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripJSObjectArray(_: [JSObject].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .north - case 1: - self = .south - case 2: - self = .east - case 3: - self = .west - default: - return nil - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripCaseEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripCaseEnumArray") +public func _bjs_ArraySupportExports_static_roundTripCaseEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripCaseEnumArray(_: [Direction].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private var bridgeJSRawValue: Int32 { - switch self { - case .north: - return 0 - case .south: - return 1 - case .east: - return 2 - case .west: - return 3 - } - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripStringRawValueEnumArray(_: [Theme].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif } -extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripIntRawValueEnumArray(_: [HttpStatus].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #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_ArraySupportExports_static_roundTripStructArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripStructArray") +public func _bjs_ArraySupportExports_static_roundTripStructArray() -> Void { #if arch(wasm32) - let ret = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) - return ret.bridgeJSLowerReturn() + let ret = ArraySupportExports.roundTripStructArray(_: [DataPoint].bridgeJSStackPop()) + ret.bridgeJSStackPush() #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_ArraySupportExports_static_roundTripSwiftClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripSwiftClassArray") +public func _bjs_ArraySupportExports_static_roundTripSwiftClassArray() -> Void { #if arch(wasm32) - let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) - return ret.bridgeJSLowerReturn() + let ret = ArraySupportExports.roundTripSwiftClassArray(_: [Greeter].bridgeJSStackPop()) + ret.bridgeJSStackPush() #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() - } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray") +public func _bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNamespacedSwiftClassArray(_: [Utils.Converter].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - private init?(bridgeJSRawValue: Int32) { +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripProtocolArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripProtocolArray") +public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripProtocolArray(_: [AnyArrayElementProtocol].bridgeJSStackPop()) + ret.map { $0 as! AnyArrayElementProtocol }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripJSClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripJSClassArray") +public func _bjs_ArraySupportExports_static_roundTripJSClassArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripJSClassArray(_: [ArrayElementObject].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalIntArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalIntArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalIntArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalIntArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalStringArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStringArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalStringArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalStringArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalCaseEnumArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalStringRawValueEnumArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalIntRawValueEnumArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalStructArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStructArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalStructArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalStructArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalSwiftClassArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalJSClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalJSClassArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalJSClassArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalJSClassArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedIntArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedIntArray") +public func _bjs_ArraySupportExports_static_roundTripNestedIntArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedIntArray(_: [[Int]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedStringArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedStringArray") +public func _bjs_ArraySupportExports_static_roundTripNestedStringArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedStringArray(_: [[String]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedDoubleArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedDoubleArray") +public func _bjs_ArraySupportExports_static_roundTripNestedDoubleArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedDoubleArray(_: [[Double]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedBoolArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedBoolArray") +public func _bjs_ArraySupportExports_static_roundTripNestedBoolArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedBoolArray(_: [[Bool]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedStructArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedStructArray") +public func _bjs_ArraySupportExports_static_roundTripNestedStructArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedStructArray(_: [[DataPoint]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray") +public func _bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedCaseEnumArray(_: [[Direction]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray") +public func _bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripNestedSwiftClassArray(_: [[Greeter]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_multiArrayFirst") +@_cdecl("bjs_ArraySupportExports_static_multiArrayFirst") +public func _bjs_ArraySupportExports_static_multiArrayFirst() -> Void { + #if arch(wasm32) + let _tmp_b = [String].bridgeJSStackPop() + let _tmp_a = [Int].bridgeJSStackPop() + let ret = ArraySupportExports.multiArrayFirst(_: _tmp_a, _: _tmp_b) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_multiArraySecond") +@_cdecl("bjs_ArraySupportExports_static_multiArraySecond") +public func _bjs_ArraySupportExports_static_multiArraySecond() -> Void { + #if arch(wasm32) + let _tmp_b = [String].bridgeJSStackPop() + let _tmp_a = [Int].bridgeJSStackPop() + let ret = ArraySupportExports.multiArraySecond(_: _tmp_a, _: _tmp_b) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_multiOptionalArrayFirst") +@_cdecl("bjs_ArraySupportExports_static_multiOptionalArrayFirst") +public func _bjs_ArraySupportExports_static_multiOptionalArrayFirst() -> Void { + #if arch(wasm32) + let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() + let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() + let ret = ArraySupportExports.multiOptionalArrayFirst(_: _tmp_a, _: _tmp_b) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #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 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() + } + + private init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: - self = .get + self = .north case 1: - self = .post + self = .south case 2: - self = .put + self = .east case 3: - self = .delete + self = .west default: return nil } @@ -2398,33 +2718,27 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { private var bridgeJSRawValue: Int32 { switch self { - case .get: + case .north: return 0 - case .post: + case .south: return 1 - case .put: + case .east: return 2 - case .delete: + case .west: return 3 } } } -extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { +extension Status: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Internal.SupportedMethod { + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Status { return bridgeJSLiftParameter(value) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Internal.SupportedMethod { - return Internal.SupportedMethod(bridgeJSRawValue: 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() @@ -2433,9 +2747,11 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { private init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: - self = .get + self = .loading case 1: - self = .post + self = .success + case 2: + self = .error default: return nil } @@ -2443,29 +2759,195 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { private var bridgeJSRawValue: Int32 { switch self { - case .get: + case .loading: return 0 - case .post: + case .success: return 1 + case .error: + return 2 } } } -extension APIResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { - switch caseId { +extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension HttpStatus: _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() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { case 0: - return .success(String.bridgeJSStackPop()) + self = .north case 1: - return .failure(Int.bridgeJSStackPop()) + self = .south case 2: - return .flag(Bool.bridgeJSStackPop()) + self = .east case 3: - return .rate(Float.bridgeJSStackPop()) - case 4: - return .precise(Double.bridgeJSStackPop()) - case 5: - return .info + self = .west + default: + return nil + } + } + + private 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 { +} + +@_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 = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + 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 { + #if arch(wasm32) + let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + 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() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .get + case 1: + self = .post + case 2: + self = .put + case 3: + self = .delete + default: + return nil + } + } + + private var bridgeJSRawValue: Int32 { + switch self { + case .get: + return 0 + case .post: + return 1 + case .put: + return 2 + case .delete: + return 3 + } + } +} + +extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +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() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .get + case 1: + self = .post + default: + return nil + } + } + + private 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)") } @@ -4032,1994 +4514,1568 @@ public func _bjs_ConfigStruct_static_maxRetries_get() -> Int32 { #endif } -@_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 -} - -@_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 -} - -@_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 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 { - 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())) - } -} - -#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 { - fatalError("Only available on WebAssembly") -} -#endif -@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_FooContainer") -fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { - fatalError("Only available on WebAssembly") -} -#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())) - } -} - -#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_roundTripVoid") -@_cdecl("bjs_roundTripVoid") -public func _bjs_roundTripVoid() -> Void { - #if arch(wasm32) - roundTripVoid() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripInt") -@_cdecl("bjs_roundTripInt") -public func _bjs_roundTripInt(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = roundTripInt(v: Int.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripUInt") -@_cdecl("bjs_roundTripUInt") -public func _bjs_roundTripUInt(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = roundTripUInt(v: UInt.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripFloat") -@_cdecl("bjs_roundTripFloat") -public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { - #if arch(wasm32) - let ret = roundTripFloat(v: Float.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripDouble") -@_cdecl("bjs_roundTripDouble") -public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { - #if arch(wasm32) - let ret = roundTripDouble(v: Double.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripBool") -@_cdecl("bjs_roundTripBool") -public func _bjs_roundTripBool(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = roundTripBool(v: Bool.bridgeJSLiftParameter(v)) - 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 { - #if arch(wasm32) - let ret = roundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripSwiftHeapObject") -@_cdecl("bjs_roundTripSwiftHeapObject") -public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = roundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripUnsafeRawPointer") -@_cdecl("bjs_roundTripUnsafeRawPointer") -public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = roundTripUnsafeRawPointer(v: UnsafeRawPointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointer") -@_cdecl("bjs_roundTripUnsafeMutableRawPointer") -public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = roundTripUnsafeMutableRawPointer(v: UnsafeMutableRawPointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_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 -} - -@_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 -} - -@_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 -} - -@_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 -} - -@_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 -} - -@_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 -} - -@_expose(wasm, "bjs_roundTripJSValue") -@_cdecl("bjs_roundTripJSValue") -public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { - #if arch(wasm32) - let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) - return ret.bridgeJSLowerReturn() - #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 { - #if arch(wasm32) - let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripJSValueArray") -@_cdecl("bjs_roundTripJSValueArray") -public func _bjs_roundTripJSValueArray() -> Void { - #if arch(wasm32) - let ret = roundTripJSValueArray(v: [JSValue].bridgeJSStackPop()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalJSValueArray") -@_cdecl("bjs_roundTripOptionalJSValueArray") -public func _bjs_roundTripOptionalJSValueArray() -> Void { - #if arch(wasm32) - let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_makeImportedFoo") -@_cdecl("bjs_makeImportedFoo") -public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> 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 - } - #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 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_throwsWithIntResult") -@_cdecl("bjs_throwsWithIntResult") -public func _bjs_throwsWithIntResult() -> Int32 { - #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 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_throwsWithStringResult") -@_cdecl("bjs_throwsWithStringResult") -public func _bjs_throwsWithStringResult() -> Void { - #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 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_throwsWithBoolResult") -@_cdecl("bjs_throwsWithBoolResult") -public func _bjs_throwsWithBoolResult() -> Int32 { - #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 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_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: String(describing: error)) - 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: String(describing: error)) - 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 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 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_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: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripVoid") -@_cdecl("bjs_asyncRoundTripVoid") -public func _bjs_asyncRoundTripVoid() -> Int32 { - #if arch(wasm32) - let ret = JSPromise.async { - await asyncRoundTripVoid() - }.jsObject - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripInt") -@_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() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripFloat") -@_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() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripDouble") -@_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() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripBool") -@_cdecl("bjs_asyncRoundTripBool") -public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { +@_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 = JSPromise.async { - return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = ConfigStruct.timeout 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_ConfigStruct_static_timeout_set") +@_cdecl("bjs_ConfigStruct_static_timeout_set") +public func _bjs_ConfigStruct_static_timeout_set(_ value: Float64) -> Void { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + ConfigStruct.timeout = Double.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripSwiftHeapObject") -@_cdecl("bjs_asyncRoundTripSwiftHeapObject") -public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { +@_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 = JSPromise.async { - return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = ConfigStruct.computedSetting return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripJSObject") -@_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() - #else +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 +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_JSObjectContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSObjectContainer_extern(objectId) } -@_expose(wasm, "bjs_takeGreeter") -@_cdecl("bjs_takeGreeter") -public func _bjs_takeGreeter(_ g: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +#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 { + 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())) + } +} + +#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 { + fatalError("Only available on WebAssembly") +} +#endif +@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_FooContainer") +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#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())) + } +} + +#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) - takeGreeter(g: Greeter.bridgeJSLiftParameter(g), name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + 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_ArrayMembers_firstString") +@_cdecl("bjs_ArrayMembers_firstString") +public func _bjs_ArrayMembers_firstString() -> Void { #if arch(wasm32) - let ret = createCalculator() + let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) 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_roundTripVoid") +@_cdecl("bjs_roundTripVoid") +public func _bjs_roundTripVoid() -> Void { #if arch(wasm32) - let ret = useCalculator(calc: Calculator.bridgeJSLiftParameter(calc), x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) - return ret.bridgeJSLowerReturn() + roundTripVoid() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testGreeterToJSValue") -@_cdecl("bjs_testGreeterToJSValue") -public func _bjs_testGreeterToJSValue() -> Int32 { +@_expose(wasm, "bjs_roundTripInt") +@_cdecl("bjs_roundTripInt") +public func _bjs_roundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = testGreeterToJSValue() + let ret = roundTripInt(v: Int.bridgeJSLiftParameter(v)) 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_roundTripUInt") +@_cdecl("bjs_roundTripUInt") +public func _bjs_roundTripUInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = testCalculatorToJSValue() + let ret = roundTripUInt(v: UInt.bridgeJSLiftParameter(v)) 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_roundTripFloat") +@_cdecl("bjs_roundTripFloat") +public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { #if arch(wasm32) - let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) + let ret = roundTripFloat(v: Float.bridgeJSLiftParameter(v)) 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_roundTripDouble") +@_cdecl("bjs_roundTripDouble") +public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { #if arch(wasm32) - let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) + let ret = roundTripDouble(v: Double.bridgeJSLiftParameter(v)) 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_roundTripBool") +@_cdecl("bjs_roundTripBool") +public func _bjs_roundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = getDirection() + let ret = roundTripBool(v: Bool.bridgeJSLiftParameter(v)) 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_roundTripString") +@_cdecl("bjs_roundTripString") +public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) + let ret = roundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) 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_roundTripSwiftHeapObject") +@_cdecl("bjs_roundTripSwiftHeapObject") +public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = roundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) 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_roundTripUnsafeRawPointer") +@_cdecl("bjs_roundTripUnsafeRawPointer") +public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = getTheme() + let ret = roundTripUnsafeRawPointer(v: UnsafeRawPointer.bridgeJSLiftParameter(v)) 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_roundTripUnsafeMutableRawPointer") +@_cdecl("bjs_roundTripUnsafeMutableRawPointer") +public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) + let ret = roundTripUnsafeMutableRawPointer(v: UnsafeMutableRawPointer.bridgeJSLiftParameter(v)) 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_roundTripOpaquePointer") +@_cdecl("bjs_roundTripOpaquePointer") +public func _bjs_roundTripOpaquePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = getHttpStatus() + let ret = roundTripOpaquePointer(v: OpaquePointer.bridgeJSLiftParameter(v)) 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_roundTripUnsafePointer") +@_cdecl("bjs_roundTripUnsafePointer") +public func _bjs_roundTripUnsafePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = roundTripUnsafePointer(v: UnsafePointer.bridgeJSLiftParameter(v)) 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_roundTripUnsafeMutablePointer") +@_cdecl("bjs_roundTripUnsafeMutablePointer") +public func _bjs_roundTripUnsafeMutablePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) + let ret = roundTripUnsafeMutablePointer(v: UnsafeMutablePointer.bridgeJSLiftParameter(v)) 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_roundTripJSObject") +@_cdecl("bjs_roundTripJSObject") +public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = getTSDirection() + let ret = roundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) 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_roundTripDictionaryExport") +@_cdecl("bjs_roundTripDictionaryExport") +public func _bjs_roundTripDictionaryExport() -> Void { #if arch(wasm32) - let ret = setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = roundTripDictionaryExport(v: [String: Int].bridgeJSLiftParameter()) 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_roundTripOptionalDictionaryExport") +@_cdecl("bjs_roundTripOptionalDictionaryExport") +public func _bjs_roundTripOptionalDictionaryExport() -> Void { #if arch(wasm32) - let ret = getTSTheme() + let ret = roundTripOptionalDictionaryExport(v: Optional<[String: String]>.bridgeJSLiftParameter()) 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_roundTripJSValue") +@_cdecl("bjs_roundTripJSValue") +public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = createConverter() + let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) 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_roundTripOptionalJSValue") +@_cdecl("bjs_roundTripOptionalJSValue") +public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = useConverter(converter: Utils.Converter.bridgeJSLiftParameter(converter), value: Int.bridgeJSLiftParameter(value)) + let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) 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_roundTripOptionalJSValueArray") +@_cdecl("bjs_roundTripOptionalJSValueArray") +public func _bjs_roundTripOptionalJSValueArray() -> Void { #if arch(wasm32) - let ret = roundTripConverterArray(_: [Utils.Converter].bridgeJSStackPop()) + let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createHTTPServer") -@_cdecl("bjs_createHTTPServer") -public func _bjs_createHTTPServer() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_makeImportedFoo") +@_cdecl("bjs_makeImportedFoo") +public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { #if arch(wasm32) - let ret = createHTTPServer() - return ret.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: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #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_throwsSwiftError") +@_cdecl("bjs_throwsSwiftError") +public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { #if arch(wasm32) - let ret = createUUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) - return ret.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: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUUID") -@_cdecl("bjs_roundTripUUID") -public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_throwsWithIntResult") +@_cdecl("bjs_throwsWithIntResult") +public func _bjs_throwsWithIntResult() -> Int32 { #if arch(wasm32) - let ret = roundTripUUID(_: UUID.bridgeJSLiftParameter(uuid)) - 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: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripNetworkingAPIMethod") -@_cdecl("bjs_roundtripNetworkingAPIMethod") -public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { +@_expose(wasm, "bjs_throwsWithStringResult") +@_cdecl("bjs_throwsWithStringResult") +public func _bjs_throwsWithStringResult() -> Void { #if arch(wasm32) - let ret = roundtripNetworkingAPIMethod(_: Networking.API.Method.bridgeJSLiftParameter(method)) - return ret.bridgeJSLowerReturn() + 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 + } #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_throwsWithBoolResult") +@_cdecl("bjs_throwsWithBoolResult") +public func _bjs_throwsWithBoolResult() -> Int32 { #if arch(wasm32) - let ret = roundtripConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) - return ret.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: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripConfigurationPort") -@_cdecl("bjs_roundtripConfigurationPort") -public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { +@_expose(wasm, "bjs_throwsWithFloatResult") +@_cdecl("bjs_throwsWithFloatResult") +public func _bjs_throwsWithFloatResult() -> Float32 { #if arch(wasm32) - let ret = roundtripConfigurationPort(_: Configuration.Port.bridgeJSLiftParameter(port)) - return ret.bridgeJSLowerReturn() + 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 + } + #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: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0.0 + } #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_throwsWithSwiftHeapObjectResult") +@_cdecl("bjs_throwsWithSwiftHeapObjectResult") +public func _bjs_throwsWithSwiftHeapObjectResult() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = processConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) - return ret.bridgeJSLowerReturn() + 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 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripInternalSupportedMethod") -@_cdecl("bjs_roundtripInternalSupportedMethod") -public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { +@_expose(wasm, "bjs_throwsWithJSObjectResult") +@_cdecl("bjs_throwsWithJSObjectResult") +public func _bjs_throwsWithJSObjectResult() -> Int32 { #if arch(wasm32) - let ret = roundtripInternalSupportedMethod(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) - return ret.bridgeJSLowerReturn() + 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 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripAPIResult") -@_cdecl("bjs_roundtripAPIResult") -public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripVoid") +@_cdecl("bjs_asyncRoundTripVoid") +public func _bjs_asyncRoundTripVoid() -> Int32 { #if arch(wasm32) - let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) + let ret = JSPromise.async { + await asyncRoundTripVoid() + }.jsObject return 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_asyncRoundTripInt") +@_cdecl("bjs_asyncRoundTripInt") +public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = JSPromise.async { + return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)).jsValue + }.jsObject 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_asyncRoundTripFloat") +@_cdecl("bjs_asyncRoundTripFloat") +public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultFailure(_: Int.bridgeJSLiftParameter(value)) + let ret = JSPromise.async { + return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)).jsValue + }.jsObject 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_asyncRoundTripDouble") +@_cdecl("bjs_asyncRoundTripDouble") +public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultInfo() + let ret = JSPromise.async { + return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)).jsValue + }.jsObject 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_asyncRoundTripBool") +@_cdecl("bjs_asyncRoundTripBool") +public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultFlag(_: Bool.bridgeJSLiftParameter(value)) + let ret = JSPromise.async { + return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue + }.jsObject 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_asyncRoundTripString") +@_cdecl("bjs_asyncRoundTripString") +public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultRate(_: Float.bridgeJSLiftParameter(value)) + let ret = JSPromise.async { + return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue + }.jsObject 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_asyncRoundTripSwiftHeapObject") +@_cdecl("bjs_asyncRoundTripSwiftHeapObject") +public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = makeAPIResultPrecise(_: Double.bridgeJSLiftParameter(value)) + let ret = JSPromise.async { + return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue + }.jsObject 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_asyncRoundTripJSObject") +@_cdecl("bjs_asyncRoundTripJSObject") +public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) + let ret = JSPromise.async { + return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)).jsValue + }.jsObject return ret.bridgeJSLowerReturn() #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_takeGreeter") +@_cdecl("bjs_takeGreeter") +public func _bjs_takeGreeter(_ g: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = makeComplexResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() + takeGreeter(g: Greeter.bridgeJSLiftParameter(g), name: String.bridgeJSLiftParameter(nameBytes, nameLength)) #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_createCalculator") +@_cdecl("bjs_createCalculator") +public func _bjs_createCalculator() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = makeComplexResultError(_: String.bridgeJSLiftParameter(messageBytes, messageLength), _: Int.bridgeJSLiftParameter(code)) + let ret = createCalculator() return ret.bridgeJSLowerReturn() #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_useCalculator") +@_cdecl("bjs_useCalculator") +public func _bjs_useCalculator(_ calc: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = makeComplexResultLocation(_: Double.bridgeJSLiftParameter(lat), _: Double.bridgeJSLiftParameter(lng), _: String.bridgeJSLiftParameter(nameBytes, nameLength)) + 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_makeComplexResultStatus") -@_cdecl("bjs_makeComplexResultStatus") -public func _bjs_makeComplexResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_testGreeterToJSValue") +@_cdecl("bjs_testGreeterToJSValue") +public func _bjs_testGreeterToJSValue() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = testGreeterToJSValue() return ret.bridgeJSLowerReturn() #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_testCalculatorToJSValue") +@_cdecl("bjs_testCalculatorToJSValue") +public func _bjs_testCalculatorToJSValue() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultCoordinates(_: Double.bridgeJSLiftParameter(x), _: Double.bridgeJSLiftParameter(y), _: Double.bridgeJSLiftParameter(z)) + let ret = testCalculatorToJSValue() return ret.bridgeJSLowerReturn() #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_testSwiftClassAsJSValue") +@_cdecl("bjs_testSwiftClassAsJSValue") +public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> 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)) + let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultInfo") -@_cdecl("bjs_makeComplexResultInfo") -public func _bjs_makeComplexResultInfo() -> Void { +@_expose(wasm, "bjs_setDirection") +@_cdecl("bjs_setDirection") +public func _bjs_setDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = makeComplexResultInfo() + let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) return ret.bridgeJSLowerReturn() #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_getDirection") +@_cdecl("bjs_getDirection") +public func _bjs_getDirection() -> Int32 { #if arch(wasm32) - let ret = makeUtilitiesResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = getDirection() 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_processDirection") +@_cdecl("bjs_processDirection") +public func _bjs_processDirection(_ input: Int32) -> Int32 { #if arch(wasm32) - let ret = makeUtilitiesResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) 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_setTheme") +@_cdecl("bjs_setTheme") +public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) 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_getTheme") +@_cdecl("bjs_getTheme") +public func _bjs_getTheme() -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = getTheme() 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_setHttpStatus") +@_cdecl("bjs_setHttpStatus") +public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let ret = setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) 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_getHttpStatus") +@_cdecl("bjs_getHttpStatus") +public func _bjs_getHttpStatus() -> Int32 { #if arch(wasm32) - let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + let ret = getHttpStatus() 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_processTheme") +@_cdecl("bjs_processTheme") +public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) 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_setTSDirection") +@_cdecl("bjs_setTSDirection") +public func _bjs_setTSDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + let ret = setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) 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_getTSDirection") +@_cdecl("bjs_getTSDirection") +public func _bjs_getTSDirection() -> Int32 { #if arch(wasm32) - let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + let ret = getTSDirection() 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_setTSTheme") +@_cdecl("bjs_setTSTheme") +public func _bjs_setTSTheme(_ themeBytes: Int32, _ themeLength: 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 ret = setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) 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_getTSTheme") +@_cdecl("bjs_getTSTheme") +public func _bjs_getTSTheme() -> Void { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + let ret = getTSTheme() 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_createConverter") +@_cdecl("bjs_createConverter") +public func _bjs_createConverter() -> UnsafeMutableRawPointer { #if arch(wasm32) - resetObserverCounts() + let ret = createConverter() + 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_useConverter") +@_cdecl("bjs_useConverter") +public func _bjs_useConverter(_ converter: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = getObserverStats() + 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_testStringDefault") -@_cdecl("bjs_testStringDefault") -public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripConverterArray") +@_cdecl("bjs_roundTripConverterArray") +public func _bjs_roundTripConverterArray() -> Void { #if arch(wasm32) - let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) - return ret.bridgeJSLowerReturn() + let ret = roundTripConverterArray(_: [Utils.Converter].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testIntDefault") -@_cdecl("bjs_testIntDefault") -public func _bjs_testIntDefault(_ count: Int32) -> Int32 { +@_expose(wasm, "bjs_createHTTPServer") +@_cdecl("bjs_createHTTPServer") +public func _bjs_createHTTPServer() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testIntDefault(count: Int.bridgeJSLiftParameter(count)) + let ret = createHTTPServer() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testBoolDefault") -@_cdecl("bjs_testBoolDefault") -public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { +@_expose(wasm, "bjs_createUUID") +@_cdecl("bjs_createUUID") +public func _bjs_createUUID(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) + let ret = createUUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testOptionalDefault") -@_cdecl("bjs_testOptionalDefault") -public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripUUID") +@_cdecl("bjs_roundTripUUID") +public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let ret = roundTripUUID(_: UUID.bridgeJSLiftParameter(uuid)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testMultipleDefaults") -@_cdecl("bjs_testMultipleDefaults") -public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { +@_expose(wasm, "bjs_roundtripNetworkingAPIMethod") +@_cdecl("bjs_roundtripNetworkingAPIMethod") +public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) + let ret = roundtripNetworkingAPIMethod(_: Networking.API.Method.bridgeJSLiftParameter(method)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testSimpleEnumDefault") -@_cdecl("bjs_testSimpleEnumDefault") -public func _bjs_testSimpleEnumDefault(_ status: Int32) -> Int32 { +@_expose(wasm, "bjs_roundtripConfigurationLogLevel") +@_cdecl("bjs_roundtripConfigurationLogLevel") +public func _bjs_roundtripConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Void { #if arch(wasm32) - let ret = testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) + let ret = roundtripConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testDirectionDefault") -@_cdecl("bjs_testDirectionDefault") -public func _bjs_testDirectionDefault(_ direction: Int32) -> Int32 { +@_expose(wasm, "bjs_roundtripConfigurationPort") +@_cdecl("bjs_roundtripConfigurationPort") +public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { #if arch(wasm32) - let ret = testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) + let ret = roundtripConfigurationPort(_: Configuration.Port.bridgeJSLiftParameter(port)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testRawStringEnumDefault") -@_cdecl("bjs_testRawStringEnumDefault") -public func _bjs_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { +@_expose(wasm, "bjs_processConfigurationLogLevel") +@_cdecl("bjs_processConfigurationLogLevel") +public func _bjs_processConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Int32 { #if arch(wasm32) - let ret = testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = processConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testComplexInit") -@_cdecl("bjs_testComplexInit") -public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_roundtripInternalSupportedMethod") +@_cdecl("bjs_roundtripInternalSupportedMethod") +public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) + let ret = roundtripInternalSupportedMethod(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testEmptyInit") -@_cdecl("bjs_testEmptyInit") -public func _bjs_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundtripAPIResult") +@_cdecl("bjs_roundtripAPIResult") +public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) + let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayWithDefault") -@_cdecl("bjs_arrayWithDefault") -public func _bjs_arrayWithDefault() -> Int32 { +@_expose(wasm, "bjs_makeAPIResultSuccess") +@_cdecl("bjs_makeAPIResultSuccess") +public func _bjs_makeAPIResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = arrayWithDefault(_: [Int].bridgeJSStackPop()) + let ret = makeAPIResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayWithOptionalDefault") -@_cdecl("bjs_arrayWithOptionalDefault") -public func _bjs_arrayWithOptionalDefault() -> Int32 { +@_expose(wasm, "bjs_makeAPIResultFailure") +@_cdecl("bjs_makeAPIResultFailure") +public func _bjs_makeAPIResultFailure(_ value: Int32) -> Void { #if arch(wasm32) - let ret = arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) + let ret = makeAPIResultFailure(_: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMixedDefaults") -@_cdecl("bjs_arrayMixedDefaults") -public func _bjs_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { +@_expose(wasm, "bjs_makeAPIResultInfo") +@_cdecl("bjs_makeAPIResultInfo") +public func _bjs_makeAPIResultInfo() -> Void { #if arch(wasm32) - let ret = arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + let ret = makeAPIResultInfo() 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_makeAPIResultFlag") +@_cdecl("bjs_makeAPIResultFlag") +public func _bjs_makeAPIResultFlag(_ value: Int32) -> Void { #if arch(wasm32) - let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + let ret = makeAPIResultFlag(_: Bool.bridgeJSLiftParameter(value)) 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_makeAPIResultRate") +@_cdecl("bjs_makeAPIResultRate") +public func _bjs_makeAPIResultRate(_ value: Float32) -> Void { #if arch(wasm32) - let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = makeAPIResultRate(_: Float.bridgeJSLiftParameter(value)) + 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_makeAPIResultPrecise") +@_cdecl("bjs_makeAPIResultPrecise") +public func _bjs_makeAPIResultPrecise(_ value: Float64) -> Void { #if arch(wasm32) - let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = makeAPIResultPrecise(_: Double.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripIntArray") -@_cdecl("bjs_roundTripIntArray") -public func _bjs_roundTripIntArray() -> Void { +@_expose(wasm, "bjs_roundtripComplexResult") +@_cdecl("bjs_roundtripComplexResult") +public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripIntArray(_: [Int].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripStringArray") -@_cdecl("bjs_roundTripStringArray") -public func _bjs_roundTripStringArray() -> Void { +@_expose(wasm, "bjs_makeComplexResultSuccess") +@_cdecl("bjs_makeComplexResultSuccess") +public func _bjs_makeComplexResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripStringArray(_: [String].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeComplexResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDoubleArray") -@_cdecl("bjs_roundTripDoubleArray") -public func _bjs_roundTripDoubleArray() -> Void { +@_expose(wasm, "bjs_makeComplexResultError") +@_cdecl("bjs_makeComplexResultError") +public func _bjs_makeComplexResultError(_ messageBytes: Int32, _ messageLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = roundTripDoubleArray(_: [Double].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeComplexResultError(_: String.bridgeJSLiftParameter(messageBytes, messageLength), _: Int.bridgeJSLiftParameter(code)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripBoolArray") -@_cdecl("bjs_roundTripBoolArray") -public func _bjs_roundTripBoolArray() -> Void { +@_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 = roundTripBoolArray(_: [Bool].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripDirectionArray") -@_cdecl("bjs_roundTripDirectionArray") -public func _bjs_roundTripDirectionArray() -> Void { +@_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 = roundTripDirectionArray(_: [Direction].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripStatusArray") -@_cdecl("bjs_roundTripStatusArray") -public func _bjs_roundTripStatusArray() -> Void { +@_expose(wasm, "bjs_makeComplexResultCoordinates") +@_cdecl("bjs_makeComplexResultCoordinates") +public func _bjs_makeComplexResultCoordinates(_ x: Float64, _ y: Float64, _ z: Float64) -> Void { #if arch(wasm32) - let ret = roundTripStatusArray(_: [Status].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripThemeArray") -@_cdecl("bjs_roundTripThemeArray") -public func _bjs_roundTripThemeArray() -> Void { +@_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 = roundTripThemeArray(_: [Theme].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripHttpStatusArray") -@_cdecl("bjs_roundTripHttpStatusArray") -public func _bjs_roundTripHttpStatusArray() -> Void { +@_expose(wasm, "bjs_makeComplexResultInfo") +@_cdecl("bjs_makeComplexResultInfo") +public func _bjs_makeComplexResultInfo() -> Void { #if arch(wasm32) - let ret = roundTripHttpStatusArray(_: [HttpStatus].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeComplexResultInfo() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataPointArray") -@_cdecl("bjs_roundTripDataPointArray") -public func _bjs_roundTripDataPointArray() -> Void { +@_expose(wasm, "bjs_makeUtilitiesResultSuccess") +@_cdecl("bjs_makeUtilitiesResultSuccess") +public func _bjs_makeUtilitiesResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripDataPointArray(_: [DataPoint].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeUtilitiesResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripGreeterArray") -@_cdecl("bjs_roundTripGreeterArray") -public func _bjs_roundTripGreeterArray() -> Void { +@_expose(wasm, "bjs_makeUtilitiesResultFailure") +@_cdecl("bjs_makeUtilitiesResultFailure") +public func _bjs_makeUtilitiesResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = roundTripGreeterArray(_: [Greeter].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeUtilitiesResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalIntArray") -@_cdecl("bjs_roundTripOptionalIntArray") -public func _bjs_roundTripOptionalIntArray() -> 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 = roundTripOptionalIntArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripOptionalStringArray") -@_cdecl("bjs_roundTripOptionalStringArray") -public func _bjs_roundTripOptionalStringArray() -> Void { +@_expose(wasm, "bjs_makeAPINetworkingResultSuccess") +@_cdecl("bjs_makeAPINetworkingResultSuccess") +public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalStringArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDataPointArray") -@_cdecl("bjs_roundTripOptionalDataPointArray") -public func _bjs_roundTripOptionalDataPointArray() -> Void { +@_expose(wasm, "bjs_makeAPINetworkingResultFailure") +@_cdecl("bjs_makeAPINetworkingResultFailure") +public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalDataPointArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDirectionArray") -@_cdecl("bjs_roundTripOptionalDirectionArray") -public func _bjs_roundTripOptionalDirectionArray() -> Void { +@_expose(wasm, "bjs_roundtripUtilitiesResult") +@_cdecl("bjs_roundtripUtilitiesResult") +public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalDirectionArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStatusArray") -@_cdecl("bjs_roundTripOptionalStatusArray") -public func _bjs_roundTripOptionalStatusArray() -> Void { +@_expose(wasm, "bjs_roundtripAPINetworkingResult") +@_cdecl("bjs_roundtripAPINetworkingResult") +public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalStatusArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalIntArrayType") -@_cdecl("bjs_roundTripOptionalIntArrayType") -public func _bjs_roundTripOptionalIntArrayType() -> Void { +@_expose(wasm, "bjs_roundTripAllTypesResult") +@_cdecl("bjs_roundTripAllTypesResult") +public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalIntArrayType(_: Optional<[Int]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() + let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStringArrayType") -@_cdecl("bjs_roundTripOptionalStringArrayType") -public func _bjs_roundTripOptionalStringArrayType() -> Void { +@_expose(wasm, "bjs_roundTripTypedPayloadResult") +@_cdecl("bjs_roundTripTypedPayloadResult") +public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalStringArrayType(_: Optional<[String]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() + let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalGreeterArrayType") -@_cdecl("bjs_roundTripOptionalGreeterArrayType") -public func _bjs_roundTripOptionalGreeterArrayType() -> Void { +@_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 = roundTripOptionalGreeterArrayType(_: Optional<[Greeter]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() + 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_roundTripNestedIntArray") -@_cdecl("bjs_roundTripNestedIntArray") -public func _bjs_roundTripNestedIntArray() -> Void { +@_expose(wasm, "bjs_testPropertyHolder") +@_cdecl("bjs_testPropertyHolder") +public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripNestedIntArray(_: [[Int]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedStringArray") -@_cdecl("bjs_roundTripNestedStringArray") -public func _bjs_roundTripNestedStringArray() -> Void { +@_expose(wasm, "bjs_resetObserverCounts") +@_cdecl("bjs_resetObserverCounts") +public func _bjs_resetObserverCounts() -> Void { #if arch(wasm32) - let ret = roundTripNestedStringArray(_: [[String]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + resetObserverCounts() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDoubleArray") -@_cdecl("bjs_roundTripNestedDoubleArray") -public func _bjs_roundTripNestedDoubleArray() -> Void { +@_expose(wasm, "bjs_getObserverStats") +@_cdecl("bjs_getObserverStats") +public func _bjs_getObserverStats() -> Void { #if arch(wasm32) - let ret = roundTripNestedDoubleArray(_: [[Double]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = getObserverStats() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedBoolArray") -@_cdecl("bjs_roundTripNestedBoolArray") -public func _bjs_roundTripNestedBoolArray() -> Void { +@_expose(wasm, "bjs_testStringDefault") +@_cdecl("bjs_testStringDefault") +public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedBoolArray(_: [[Bool]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDataPointArray") -@_cdecl("bjs_roundTripNestedDataPointArray") -public func _bjs_roundTripNestedDataPointArray() -> Void { +@_expose(wasm, "bjs_testIntDefault") +@_cdecl("bjs_testIntDefault") +public func _bjs_testIntDefault(_ count: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripNestedDataPointArray(_: [[DataPoint]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testIntDefault(count: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDirectionArray") -@_cdecl("bjs_roundTripNestedDirectionArray") -public func _bjs_roundTripNestedDirectionArray() -> Void { +@_expose(wasm, "bjs_testBoolDefault") +@_cdecl("bjs_testBoolDefault") +public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripNestedDirectionArray(_: [[Direction]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedGreeterArray") -@_cdecl("bjs_roundTripNestedGreeterArray") -public func _bjs_roundTripNestedGreeterArray() -> Void { +@_expose(wasm, "bjs_testOptionalDefault") +@_cdecl("bjs_testOptionalDefault") +public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedGreeterArray(_: [[Greeter]].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeRawPointerArray") -@_cdecl("bjs_roundTripUnsafeRawPointerArray") -public func _bjs_roundTripUnsafeRawPointerArray() -> Void { +@_expose(wasm, "bjs_testMultipleDefaults") +@_cdecl("bjs_testMultipleDefaults") +public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointerArray") -@_cdecl("bjs_roundTripUnsafeMutableRawPointerArray") -public func _bjs_roundTripUnsafeMutableRawPointerArray() -> Void { +@_expose(wasm, "bjs_testSimpleEnumDefault") +@_cdecl("bjs_testSimpleEnumDefault") +public func _bjs_testSimpleEnumDefault(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOpaquePointerArray") -@_cdecl("bjs_roundTripOpaquePointerArray") -public func _bjs_roundTripOpaquePointerArray() -> Void { +@_expose(wasm, "bjs_testDirectionDefault") +@_cdecl("bjs_testDirectionDefault") +public func _bjs_testDirectionDefault(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafePointerArray") -@_cdecl("bjs_roundTripUnsafePointerArray") -public func _bjs_roundTripUnsafePointerArray() -> Void { +@_expose(wasm, "bjs_testRawStringEnumDefault") +@_cdecl("bjs_testRawStringEnumDefault") +public func _bjs_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUnsafePointerArray(_: [UnsafePointer].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeMutablePointerArray") -@_cdecl("bjs_roundTripUnsafeMutablePointerArray") -public func _bjs_roundTripUnsafeMutablePointerArray() -> Void { +@_expose(wasm, "bjs_testComplexInit") +@_cdecl("bjs_testComplexInit") +public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripUnsafeMutablePointerArray(_: [UnsafeMutablePointer].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_consumeDataProcessorArrayType") -@_cdecl("bjs_consumeDataProcessorArrayType") -public func _bjs_consumeDataProcessorArrayType() -> Int32 { +@_expose(wasm, "bjs_testEmptyInit") +@_cdecl("bjs_testEmptyInit") +public func _bjs_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = consumeDataProcessorArrayType(_: [AnyDataProcessor].bridgeJSStackPop()) + let ret = testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataProcessorArrayType") -@_cdecl("bjs_roundTripDataProcessorArrayType") -public func _bjs_roundTripDataProcessorArrayType() -> Void { +@_expose(wasm, "bjs_arrayWithDefault") +@_cdecl("bjs_arrayWithDefault") +public func _bjs_arrayWithDefault() -> Int32 { #if arch(wasm32) - let ret = roundTripDataProcessorArrayType(_: [AnyDataProcessor].bridgeJSStackPop()) - ret.map { $0 as! AnyDataProcessor }.bridgeJSStackPush() + let ret = arrayWithDefault(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripJSObjectArray") -@_cdecl("bjs_roundTripJSObjectArray") -public func _bjs_roundTripJSObjectArray() -> Void { +@_expose(wasm, "bjs_arrayWithOptionalDefault") +@_cdecl("bjs_arrayWithOptionalDefault") +public func _bjs_arrayWithOptionalDefault() -> Int32 { #if arch(wasm32) - let ret = roundTripJSObjectArray(_: [JSObject].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalJSObjectArray") -@_cdecl("bjs_roundTripOptionalJSObjectArray") -public func _bjs_roundTripOptionalJSObjectArray() -> Void { +@_expose(wasm, "bjs_arrayMixedDefaults") +@_cdecl("bjs_arrayMixedDefaults") +public func _bjs_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripFooArray") -@_cdecl("bjs_roundTripFooArray") -public func _bjs_roundTripFooArray() -> Void { +@_expose(wasm, "bjs_formatName") +@_cdecl("bjs_formatName") +public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { #if arch(wasm32) - let ret = roundTripFooArray(_: [Foo].bridgeJSStackPop()) - ret.bridgeJSStackPush() + 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_roundTripOptionalFooArray") -@_cdecl("bjs_roundTripOptionalFooArray") -public func _bjs_roundTripOptionalFooArray() -> Void { +@_expose(wasm, "bjs_makeFormatter") +@_cdecl("bjs_makeFormatter") +public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalFooArray(_: [Optional].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_multiArrayFirstNums") -@_cdecl("bjs_multiArrayFirstNums") -public func _bjs_multiArrayFirstNums() -> Void { +@_expose(wasm, "bjs_makeAdder") +@_cdecl("bjs_makeAdder") +public func _bjs_makeAdder(_ base: Int32) -> Int32 { #if arch(wasm32) - let _tmp_strs = [String].bridgeJSStackPop() - let _tmp_nums = [Int].bridgeJSStackPop() - let ret = multiArrayFirstNums(nums: _tmp_nums, strs: _tmp_strs) - ret.bridgeJSStackPush() + let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_multiArrayFirstStrs") -@_cdecl("bjs_multiArrayFirstStrs") -public func _bjs_multiArrayFirstStrs() -> Void { +@_expose(wasm, "bjs_roundTripOptionalIntArrayType") +@_cdecl("bjs_roundTripOptionalIntArrayType") +public func _bjs_roundTripOptionalIntArrayType() -> Void { #if arch(wasm32) - let _tmp_strs = [String].bridgeJSStackPop() - let _tmp_nums = [Int].bridgeJSStackPop() - let ret = multiArrayFirstStrs(nums: _tmp_nums, strs: _tmp_strs) + let ret = roundTripOptionalIntArrayType(_: Optional<[Int]>.bridgeJSLiftParameter()) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_multiOptionalArrayFirstA") -@_cdecl("bjs_multiOptionalArrayFirstA") -public func _bjs_multiOptionalArrayFirstA() -> Void { +@_expose(wasm, "bjs_roundTripOptionalStringArrayType") +@_cdecl("bjs_roundTripOptionalStringArrayType") +public func _bjs_roundTripOptionalStringArrayType() -> Void { #if arch(wasm32) - let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() - let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() - let ret = multiOptionalArrayFirstA(a: _tmp_a, b: _tmp_b) + let ret = roundTripOptionalStringArrayType(_: Optional<[String]>.bridgeJSLiftParameter()) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_multiOptionalArrayFirstB") -@_cdecl("bjs_multiOptionalArrayFirstB") -public func _bjs_multiOptionalArrayFirstB() -> Void { +@_expose(wasm, "bjs_roundTripOptionalGreeterArrayType") +@_cdecl("bjs_roundTripOptionalGreeterArrayType") +public func _bjs_roundTripOptionalGreeterArrayType() -> Void { #if arch(wasm32) - let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() - let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() - let ret = multiOptionalArrayFirstB(a: _tmp_a, b: _tmp_b) + let ret = roundTripOptionalGreeterArrayType(_: Optional<[Greeter]>.bridgeJSLiftParameter()) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -9315,6 +9371,78 @@ fileprivate func bjs_ArraySupportImports_jsRoundTripJSClassArray_static_extern() return bjs_ArraySupportImports_jsRoundTripJSClassArray_static_extern() } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static") +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static() -> Void { + return bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static_extern() +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_jsSumNumberArray_static") fileprivate func bjs_ArraySupportImports_jsSumNumberArray_static_extern() -> Float64 @@ -9339,6 +9467,18 @@ fileprivate func bjs_ArraySupportImports_jsCreateNumberArray_static_extern() -> return bjs_ArraySupportImports_jsCreateNumberArray_static_extern() } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArraySupportImports_runJsArraySupportTests_static") +fileprivate func bjs_ArraySupportImports_runJsArraySupportTests_static_extern() -> Void +#else +fileprivate func bjs_ArraySupportImports_runJsArraySupportTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArraySupportImports_runJsArraySupportTests_static() -> Void { + return bjs_ArraySupportImports_runJsArraySupportTests_static_extern() +} + func _$ArraySupportImports_jsIntArrayLength(_ items: [Int]) throws(JSException) -> Int { let _ = items.bridgeJSLowerParameter() let ret = bjs_ArraySupportImports_jsIntArrayLength_static() @@ -9411,6 +9551,60 @@ func _$ArraySupportImports_jsRoundTripJSClassArray(_ values: [ArrayElementObject return [ArrayElementObject].bridgeJSLiftReturn() } +func _$ArraySupportImports_jsRoundTripOptionalIntArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalIntArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + +func _$ArraySupportImports_jsRoundTripOptionalStringArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalStringArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + +func _$ArraySupportImports_jsRoundTripOptionalBoolArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalBoolArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + +func _$ArraySupportImports_jsRoundTripOptionalJSValueArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalJSValueArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + +func _$ArraySupportImports_jsRoundTripOptionalJSObjectArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalJSObjectArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + +func _$ArraySupportImports_jsRoundTripOptionalJSClassArray(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.bridgeJSLowerParameter() + bjs_ArraySupportImports_jsRoundTripOptionalJSClassArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn() +} + func _$ArraySupportImports_jsSumNumberArray(_ values: [Double]) throws(JSException) -> Double { let _ = values.bridgeJSLowerParameter() let ret = bjs_ArraySupportImports_jsSumNumberArray_static() @@ -9428,6 +9622,13 @@ func _$ArraySupportImports_jsCreateNumberArray() throws(JSException) -> [Double] return [Double].bridgeJSLiftReturn() } +func _$ArraySupportImports_runJsArraySupportTests() throws(JSException) -> Void { + bjs_ArraySupportImports_runJsArraySupportTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 4b33632b5..1a090993b 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -3702,1228 +3702,2135 @@ "enums" : [ { "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - ], - "name" : "west" - } ], "emitStyle" : "const", - "name" : "Direction", + "name" : "ArraySupportExports", "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripIntArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "loading" - }, - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "int" : { + } + } + } + } + } ], - "name" : "success" + "returnType" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripStringArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "error" - } - ], - "emitStyle" : "const", - "name" : "Status", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Status", - "tsFullPath" : "Status" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "string" : { + } + } + } + } + } ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ + "returnType" : { + "array" : { + "_0" : { + "string" : { - ], - "name" : "dark", - "rawValue" : "dark" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripDoubleArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripDoubleArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "const", - "name" : "Theme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Theme", - "tsFullPath" : "Theme" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "double" : { + } + } + } + } + } ], - "name" : "ok", - "rawValue" : "200" - }, - { - "associatedValues" : [ + "returnType" : { + "array" : { + "_0" : { + "double" : { - ], - "name" : "notFound", - "rawValue" : "404" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripBoolArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripBoolArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "serverError", - "rawValue" : "500" - }, - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "bool" : { + } + } + } + } + } ], - "name" : "unknown", - "rawValue" : "-1" - } - ], - "emitStyle" : "const", - "name" : "HttpStatus", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "HttpStatus", - "tsFullPath" : "HttpStatus" - }, - { - "cases" : [ - { - "associatedValues" : [ + "returnType" : { + "array" : { + "_0" : { + "bool" : { - ], - "name" : "rough", - "rawValue" : "0.1" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - - ], - "name" : "normal", - "rawValue" : "0.01" - }, - { - "associatedValues" : [ - - ], - "name" : "fine", - "rawValue" : "0.001" - } - ], - "emitStyle" : "const", - "name" : "Precision", - "rawType" : "Float", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Precision", - "tsFullPath" : "Precision" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "quarter", - "rawValue" : "0.25" - }, - { - "associatedValues" : [ - - ], - "name" : "half", - "rawValue" : "0.5" - }, - { - "associatedValues" : [ - - ], - "name" : "golden", - "rawValue" : "1.618" - } - ], - "emitStyle" : "const", - "name" : "Ratio", - "rawType" : "Double", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Ratio", - "tsFullPath" : "Ratio" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSDirection", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSDirection", - "tsFullPath" : "TSDirection" - }, - { - "cases" : [ - { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUnsafeRawPointerArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ - + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + } + } ], - "name" : "dark", - "rawValue" : "dark" + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSTheme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSTheme", - "tsFullPath" : "TSTheme" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "StringUtils", - "namespace" : [ - "Utils" - ], - "staticMethods" : [ - { - "abiName" : "bjs_Utils_StringUtils_static_uppercase", + "abiName" : "bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "uppercase", + "name" : "roundTripUnsafeMutableRawPointerArray", "namespace" : [ - "Utils", - "StringUtils" + "ArraySupportExports" ], "parameters" : [ { "label" : "_", - "name" : "text", + "name" : "v", "type" : { - "string" : { - + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } } }, "staticContext" : { "namespaceEnum" : { - "_0" : "Utils.StringUtils" + "_0" : "ArraySupportExports" } } }, { - "abiName" : "bjs_Utils_StringUtils_static_lowercase", + "abiName" : "bjs_ArraySupportExports_static_roundTripOpaquePointerArray", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "lowercase", + "name" : "roundTripOpaquePointerArray", "namespace" : [ - "Utils", - "StringUtils" + "ArraySupportExports" ], "parameters" : [ { "label" : "_", - "name" : "text", + "name" : "v", "type" : { - "string" : { - + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } } }, "staticContext" : { "namespaceEnum" : { - "_0" : "Utils.StringUtils" + "_0" : "ArraySupportExports" } } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils.StringUtils", - "tsFullPath" : "Utils.StringUtils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Networking", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking", - "tsFullPath" : "Networking" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "API", - "namespace" : [ - "Networking" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API", - "tsFullPath" : "Networking.API" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "get" }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripUnsafePointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUnsafePointerArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "post" - }, - { - "associatedValues" : [ - + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } + } + } ], - "name" : "put" + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUnsafeMutablePointerArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "delete" - } - ], - "emitStyle" : "const", - "name" : "Method", - "namespace" : [ - "Networking", - "API" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API.Method", - "tsFullPath" : "Networking.API.Method" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Configuration", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration", - "tsFullPath" : "Configuration" - }, - { - "cases" : [ - { - "associatedValues" : [ - + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + } + } ], - "name" : "debug", - "rawValue" : "debug" + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripJSValueArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripJSValueArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "info", - "rawValue" : "info" - }, - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + } + } ], - "name" : "warning", - "rawValue" : "warning" + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripJSObjectArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripJSObjectArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "error", - "rawValue" : "error" - } - ], - "emitStyle" : "const", - "name" : "LogLevel", - "namespace" : [ - "Configuration" - ], - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.LogLevel", - "tsFullPath" : "Configuration.LogLevel" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "jsObject" : { + } + } + } + } + } ], - "name" : "http", - "rawValue" : "80" + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_roundTripCaseEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripCaseEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripStringRawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripIntRawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripStructArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripStructArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripSwiftClassArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNamespacedSwiftClassArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripProtocolArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripProtocolArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "ArrayElementProtocol" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "ArrayElementProtocol" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripJSClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripJSClassArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalIntArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStringArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalJSObjectArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalCaseEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStringRawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalIntRawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalStructArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStructArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "https", - "rawValue" : "443" + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalSwiftClassArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "development", - "rawValue" : "3000" - } - ], - "emitStyle" : "const", - "name" : "Port", - "namespace" : [ - "Configuration" - ], - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.Port", - "tsFullPath" : "Configuration.Port" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Internal", - "namespace" : [ - "Networking", - "APIV2" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal", - "tsFullPath" : "Networking.APIV2.Internal" - }, - { - "cases" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalJSClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalJSClassArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "get" + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedIntArray", + "namespace" : [ + "ArraySupportExports" ], - "name" : "post" - } - ], - "emitStyle" : "const", - "name" : "SupportedMethod", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "staticMethods" : [ + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "int" : { - ], - "staticProperties" : [ + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "int" : { - ], - "swiftCallName" : "Internal.SupportedMethod", - "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" - }, - { - "cases" : [ + } + } + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedStringArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "string" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } + } + } } } } ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } } } } - ], - "name" : "failure" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedDoubleArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedDoubleArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "bool" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "double" : { + } + } + } + } } } } ], - "name" : "flag" - }, - { - "associatedValues" : [ - { - "type" : { - "float" : { + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "double" : { + } + } } } } - ], - "name" : "rate" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedBoolArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedBoolArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "double" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "bool" : { + } + } + } + } } } } ], - "name" : "precise" - }, - { - "associatedValues" : [ - - ], - "name" : "info" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "bool" : { + } + } } } } - ], - "name" : "success" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedStructArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedStructArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "string" : { - + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + } + } } } - }, - { - "type" : { - "int" : { - + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } } } } - ], - "name" : "error" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - { - "type" : { - "double" : { - - } - } - }, + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedCaseEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "double" : { - + "array" : { + "_0" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } } } - }, - { - "type" : { - "string" : { - + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } } - ], - "name" : "location" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, + "abiName" : "bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripNestedSwiftClassArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { - "int" : { - + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + } } } - }, - { - "type" : { - "string" : { - + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } } } - ], - "name" : "status" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_ArraySupportExports_static_multiArrayFirst", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "multiArrayFirst", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "a", "type" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { + "label" : "_", + "name" : "b", "type" : { - "double" : { + "array" : { + "_0" : { + "string" : { + } + } } } - }, - { - "type" : { - "double" : { + } + ], + "returnType" : { + "array" : { + "_0" : { + "int" : { } } } - ], - "name" : "coordinates" + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } }, { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, + "abiName" : "bjs_ArraySupportExports_static_multiArraySecond", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "multiArraySecond", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "a", "type" : { - "bool" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { + "label" : "_", + "name" : "b", "type" : { - "int" : { + "array" : { + "_0" : { + "string" : { + } + } } } - }, - { - "type" : { - "int" : { + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { } } - }, + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_multiOptionalArrayFirst", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "multiOptionalArrayFirst", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "a", "type" : { - "double" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" } } }, { + "label" : "_", + "name" : "b", "type" : { - "double" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } - }, - { - "type" : { - "string" : { + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } } - } - }, + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_multiOptionalArraySecond", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "multiOptionalArraySecond", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "a", "type" : { - "string" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" } } }, { + "label" : "_", + "name" : "b", "type" : { - "string" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } } ], - "name" : "comprehensive" - }, - { - "associatedValues" : [ + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { - ], - "name" : "info" + } + } + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } } - ], - "emitStyle" : "const", - "name" : "ComplexResult", - "staticMethods" : [ - ], "staticProperties" : [ ], - "swiftCallName" : "ComplexResult", - "tsFullPath" : "ComplexResult" + "swiftCallName" : "ArraySupportExports", + "tsFullPath" : "ArraySupportExports" }, { "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + ], + "name" : "west" + } ], "emitStyle" : "const", - "name" : "Utilities", + "name" : "Direction", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "Utilities", - "tsFullPath" : "Utilities" + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - } ], - "name" : "success" + "name" : "loading" }, { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - }, - { - "type" : { - "int" : { - - } - } - } ], - "name" : "failure" + "name" : "success" }, { "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - }, - { - "type" : { - "string" : { - } - } - } ], - "name" : "status" + "name" : "error" } ], "emitStyle" : "const", - "name" : "Result", - "namespace" : [ - "Utilities" - ], + "name" : "Status", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "Utilities.Result", - "tsFullPath" : "Utilities.Result" + "swiftCallName" : "Status", + "tsFullPath" : "Status" }, { "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light", + "rawValue" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark", + "rawValue" : "dark" + }, + { + "associatedValues" : [ + ], + "name" : "auto", + "rawValue" : "auto" + } ], "emitStyle" : "const", - "name" : "API", + "name" : "Theme", + "rawType" : "String", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "API", - "tsFullPath" : "API" + "swiftCallName" : "Theme", + "tsFullPath" : "Theme" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - } ], - "name" : "success" + "name" : "ok", + "rawValue" : "200" }, { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - }, - { - "type" : { - "int" : { + ], + "name" : "notFound", + "rawValue" : "404" + }, + { + "associatedValues" : [ - } - } - } ], - "name" : "failure" + "name" : "serverError", + "rawValue" : "500" + }, + { + "associatedValues" : [ + + ], + "name" : "unknown", + "rawValue" : "-1" } ], "emitStyle" : "const", - "name" : "NetworkingResult", - "namespace" : [ - "API" - ], + "name" : "HttpStatus", + "rawType" : "Int", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "API.NetworkingResult", - "tsFullPath" : "API.NetworkingResult" + "swiftCallName" : "HttpStatus", + "tsFullPath" : "HttpStatus" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "swiftStruct" : { - "_0" : "Address" - } - } - } - ], - "name" : "structPayload" - }, - { - "associatedValues" : [ - { - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } + ], - "name" : "classPayload" + "name" : "rough", + "rawValue" : "0.1" }, { "associatedValues" : [ - { - "type" : { - "jsObject" : { - } - } - } ], - "name" : "jsObjectPayload" + "name" : "normal", + "rawValue" : "0.01" }, { "associatedValues" : [ - { - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } + ], - "name" : "nestedEnum" - }, + "name" : "fine", + "rawValue" : "0.001" + } + ], + "emitStyle" : "const", + "name" : "Precision", + "rawType" : "Float", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Precision", + "tsFullPath" : "Precision" + }, + { + "cases" : [ { "associatedValues" : [ - { - "type" : { - "array" : { - "_0" : { - "int" : { - } - } - } - } - } ], - "name" : "arrayPayload" + "name" : "quarter", + "rawValue" : "0.25" }, { "associatedValues" : [ - { - "type" : { - "jsObject" : { - "_0" : "Foo" - } - } - } + ], - "name" : "jsClassPayload" + "name" : "half", + "rawValue" : "0.5" }, { "associatedValues" : [ ], - "name" : "empty" + "name" : "golden", + "rawValue" : "1.618" } ], "emitStyle" : "const", - "name" : "AllTypesResult", + "name" : "Ratio", + "rawType" : "Double", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "AllTypesResult", - "tsFullPath" : "AllTypesResult" + "swiftCallName" : "Ratio", + "tsFullPath" : "Ratio" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - ], - "name" : "precision" - }, - { - "associatedValues" : [ - { - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } + ], - "name" : "direction" + "name" : "north" }, { "associatedValues" : [ - { - "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - }, - "_1" : "null" - } - } - } + ], - "name" : "optPrecision" + "name" : "south" }, { "associatedValues" : [ - { - "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" - } - } - } + ], - "name" : "optDirection" + "name" : "east" }, { "associatedValues" : [ ], - "name" : "empty" + "name" : "west" } ], - "emitStyle" : "const", - "name" : "TypedPayloadResult", + "emitStyle" : "tsEnum", + "name" : "TSDirection", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "TypedPayloadResult", - "tsFullPath" : "TypedPayloadResult" + "swiftCallName" : "TSDirection", + "tsFullPath" : "TSDirection" }, { "cases" : [ @@ -4931,96 +5838,77 @@ "associatedValues" : [ ], - "name" : "scientific" + "name" : "light", + "rawValue" : "light" }, { "associatedValues" : [ ], - "name" : "basic" - } - ], - "emitStyle" : "const", - "name" : "StaticCalculator", - "staticMethods" : [ + "name" : "dark", + "rawValue" : "dark" + }, { - "abiName" : "bjs_StaticCalculator_static_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "int" : { + "associatedValues" : [ - } - } - } ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "StaticCalculator" - } - } + "name" : "auto", + "rawValue" : "auto" } + ], + "emitStyle" : "tsEnum", + "name" : "TSTheme", + "rawType" : "String", + "staticMethods" : [ + ], "staticProperties" : [ ], - "swiftCallName" : "StaticCalculator", - "tsFullPath" : "StaticCalculator" + "swiftCallName" : "TSTheme", + "tsFullPath" : "TSTheme" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "StaticUtils", + "name" : "Utils", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "StaticUtils", - "tsFullPath" : "StaticUtils" + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "Nested", + "name" : "StringUtils", "namespace" : [ - "StaticUtils" + "Utils" ], "staticMethods" : [ { - "abiName" : "bjs_StaticUtils_Nested_static_roundtrip", + "abiName" : "bjs_Utils_StringUtils_static_uppercase", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "roundtrip", + "name" : "uppercase", "namespace" : [ - "StaticUtils", - "Nested" + "Utils", + "StringUtils" ], "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "text", "type" : { "string" : { @@ -5035,7 +5923,41 @@ }, "staticContext" : { "namespaceEnum" : { - "_0" : "StaticUtils.Nested" + "_0" : "Utils.StringUtils" + } + } + }, + { + "abiName" : "bjs_Utils_StringUtils_static_lowercase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "lowercase", + "namespace" : [ + "Utils", + "StringUtils" + ], + "parameters" : [ + { + "label" : "_", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "Utils.StringUtils" } } } @@ -5043,96 +5965,144 @@ "staticProperties" : [ ], - "swiftCallName" : "StaticUtils.Nested", - "tsFullPath" : "StaticUtils.Nested" + "swiftCallName" : "Utils.StringUtils", + "tsFullPath" : "Utils.StringUtils" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "GraphOperations", + "name" : "Networking", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking", + "tsFullPath" : "Networking" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "API", "namespace" : [ - "Services", - "Graph" + "Networking" ], "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API", + "tsFullPath" : "Networking.API" + }, + { + "cases" : [ { - "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "createGraph", - "namespace" : [ - "Services", - "Graph", - "GraphOperations" + "associatedValues" : [ + ], - "parameters" : [ - { - "label" : "rootId", - "name" : "rootId", - "type" : { - "int" : { + "name" : "get" + }, + { + "associatedValues" : [ + + ], + "name" : "post" + }, + { + "associatedValues" : [ + + ], + "name" : "put" + }, + { + "associatedValues" : [ + + ], + "name" : "delete" + } + ], + "emitStyle" : "const", + "name" : "Method", + "namespace" : [ + "Networking", + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API.Method", + "tsFullPath" : "Networking.API.Method" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Configuration", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration", + "tsFullPath" : "Configuration" + }, + { + "cases" : [ + { + "associatedValues" : [ - } - } - } ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "namespaceEnum" : { - "_0" : "GraphOperations" - } - } + "name" : "debug", + "rawValue" : "debug" }, { - "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "nodeCount", - "namespace" : [ - "Services", - "Graph", - "GraphOperations" + "associatedValues" : [ + ], - "parameters" : [ - { - "label" : "graphId", - "name" : "graphId", - "type" : { - "int" : { + "name" : "info", + "rawValue" : "info" + }, + { + "associatedValues" : [ - } - } - } ], - "returnType" : { - "int" : { + "name" : "warning", + "rawValue" : "warning" + }, + { + "associatedValues" : [ - } - }, - "staticContext" : { - "namespaceEnum" : { - "_0" : "GraphOperations" - } - } + ], + "name" : "error", + "rawValue" : "error" } + ], + "emitStyle" : "const", + "name" : "LogLevel", + "namespace" : [ + "Configuration" + ], + "rawType" : "String", + "staticMethods" : [ + ], "staticProperties" : [ ], - "swiftCallName" : "GraphOperations", - "tsFullPath" : "Services.Graph.GraphOperations" + "swiftCallName" : "Configuration.LogLevel", + "tsFullPath" : "Configuration.LogLevel" }, { "cases" : [ @@ -5140,364 +6110,380 @@ "associatedValues" : [ ], - "name" : "option1" + "name" : "http", + "rawValue" : "80" }, { "associatedValues" : [ ], - "name" : "option2" + "name" : "https", + "rawValue" : "443" + }, + { + "associatedValues" : [ + + ], + "name" : "development", + "rawValue" : "3000" } ], "emitStyle" : "const", - "name" : "StaticPropertyEnum", + "name" : "Port", + "namespace" : [ + "Configuration" + ], + "rawType" : "Int", "staticMethods" : [ ], "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumProperty", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "string" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "enumConstant", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + ], + "swiftCallName" : "Configuration.Port", + "tsFullPath" : "Configuration.Port" + }, + { + "cases" : [ - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumBool", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "bool" : { + ], + "emitStyle" : "const", + "name" : "Internal", + "namespace" : [ + "Networking", + "APIV2" + ], + "staticMethods" : [ - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumVariable", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + ], + "staticProperties" : [ - } - } - }, + ], + "swiftCallName" : "Internal", + "tsFullPath" : "Networking.APIV2.Internal" + }, + { + "cases" : [ { - "isReadonly" : true, - "isStatic" : true, - "name" : "computedReadonly", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + "associatedValues" : [ - } - } + ], + "name" : "get" }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedReadWrite", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "string" : { + "associatedValues" : [ - } - } + ], + "name" : "post" } - ], - "swiftCallName" : "StaticPropertyEnum", - "tsFullPath" : "StaticPropertyEnum" - }, - { - "cases" : [ - ], "emitStyle" : "const", - "name" : "StaticPropertyNamespace", + "name" : "SupportedMethod", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], "staticMethods" : [ ], "staticProperties" : [ + + ], + "swiftCallName" : "Internal.SupportedMethod", + "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" + }, + { + "cases" : [ { - "isReadonly" : false, - "isStatic" : true, - "name" : "namespaceProperty", - "namespace" : [ - "StaticPropertyNamespace" + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace" + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } } - }, - "type" : { - "string" : { + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + } + } } - } + ], + "name" : "flag" }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "namespaceConstant", - "namespace" : [ - "StaticPropertyNamespace" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace" + "associatedValues" : [ + { + "type" : { + "float" : { + + } + } } - }, - "type" : { - "string" : { + ], + "name" : "rate" + }, + { + "associatedValues" : [ + { + "type" : { + "double" : { + } + } } - } - } - ], - "swiftCallName" : "StaticPropertyNamespace", - "tsFullPath" : "StaticPropertyNamespace" - }, - { - "cases" : [ + ], + "name" : "precise" + }, + { + "associatedValues" : [ + ], + "name" : "info" + } ], "emitStyle" : "const", - "name" : "NestedProperties", - "namespace" : [ - "StaticPropertyNamespace" - ], + "name" : "APIResult", "staticMethods" : [ ], "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedProperty", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "int" : { - } - } - }, + ], + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" + }, + { + "cases" : [ { - "isReadonly" : true, - "isStatic" : true, - "name" : "nestedConstant", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "string" : { + "associatedValues" : [ + { + "type" : { + "string" : { + } + } } - } + ], + "name" : "success" }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedDouble", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "double" : { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + } + } } - } - } - ], - "swiftCallName" : "StaticPropertyNamespace.NestedProperties", - "tsFullPath" : "StaticPropertyNamespace.NestedProperties" - }, - { - "cases" : [ + ], + "name" : "error" + }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "Address" - } - }, - "_1" : "null" + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "string" : { + } } } ], - "name" : "optStruct" + "name" : "location" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "string" : { + } } } ], - "name" : "optClass" + "name" : "status" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "jsObject" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { - } - }, - "_1" : "null" } } } ], - "name" : "optJSObject" + "name" : "coordinates" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "bool" : { + + } + } + }, + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "string" : { + } } - } - ], - "name" : "optNestedEnum" - }, - { - "associatedValues" : [ + }, { "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + "string" : { - } - } - } - }, - "_1" : "null" } } - } - ], - "name" : "optArray" - }, - { - "associatedValues" : [ + }, { "type" : { - "nullable" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - }, - "_1" : "null" + "string" : { + } } } ], - "name" : "optJsClass" + "name" : "comprehensive" }, { "associatedValues" : [ ], - "name" : "empty" + "name" : "info" } ], "emitStyle" : "const", - "name" : "OptionalAllTypesResult", + "name" : "ComplexResult", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "OptionalAllTypesResult", - "tsFullPath" : "OptionalAllTypesResult" + "swiftCallName" : "ComplexResult", + "tsFullPath" : "ComplexResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utilities", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utilities", + "tsFullPath" : "Utilities" }, { "cases" : [ @@ -5505,13 +6491,8 @@ "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } @@ -5522,25 +6503,15 @@ "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "int" : { + "string" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "bool" : { + "int" : { - } - }, - "_1" : "null" } } } @@ -5551,37 +6522,22 @@ "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "bool" : { + "bool" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "int" : { + "int" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } @@ -5590,1793 +6546,1704 @@ } ], "emitStyle" : "const", - "name" : "APIOptionalResult", + "name" : "Result", + "namespace" : [ + "Utilities" + ], "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "APIOptionalResult", - "tsFullPath" : "APIOptionalResult" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundTripVoid", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripVoid", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_roundTripUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUInt", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "uint" : { - - } - } - } - ], - "returnType" : { - "uint" : { - - } - } - }, - { - "abiName" : "bjs_roundTripFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripFloat", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "float" : { - - } - } - } - ], - "returnType" : { - "float" : { - - } - } + "swiftCallName" : "Utilities.Result", + "tsFullPath" : "Utilities.Result" }, { - "abiName" : "bjs_roundTripDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDouble", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "double" : { + "cases" : [ - } - } - } ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_roundTripBool", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripBool", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "bool" : { + "emitStyle" : "const", + "name" : "API", + "staticMethods" : [ - } - } - } ], - "returnType" : { - "bool" : { + "staticProperties" : [ - } - } + ], + "swiftCallName" : "API", + "tsFullPath" : "API" }, { - "abiName" : "bjs_roundTripString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripString", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "string" : { + "associatedValues" : [ + { + "type" : { + "string" : { + } + } } - } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" } ], - "returnType" : { - "string" : { + "emitStyle" : "const", + "name" : "NetworkingResult", + "namespace" : [ + "API" + ], + "staticMethods" : [ - } - } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "API.NetworkingResult", + "tsFullPath" : "API.NetworkingResult" }, { - "abiName" : "bjs_roundTripSwiftHeapObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSwiftHeapObject", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "associatedValues" : [ + { + "type" : { + "swiftStruct" : { + "_0" : "Address" + } + } } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeRawPointer", - "parameters" : [ + ], + "name" : "structPayload" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" + "associatedValues" : [ + { + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeMutableRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeMutableRawPointer", - "parameters" : [ + ], + "name" : "classPayload" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" + "associatedValues" : [ + { + "type" : { + "jsObject" : { + + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripOpaquePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOpaquePointer", - "parameters" : [ + ], + "name" : "jsObjectPayload" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" + "associatedValues" : [ + { + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafePointer", - "parameters" : [ + ], + "name" : "nestedEnum" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" + "associatedValues" : [ + { + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeMutablePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeMutablePointer", - "parameters" : [ + ], + "name" : "arrayPayload" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" + "associatedValues" : [ + { + "type" : { + "jsObject" : { + "_0" : "Foo" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "abiName" : "bjs_roundTripJSObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripJSObject", - "parameters" : [ + ], + "name" : "jsClassPayload" + }, { - "label" : "v", - "name" : "v", - "type" : { - "jsObject" : { + "associatedValues" : [ - } - } + ], + "name" : "empty" } ], - "returnType" : { - "jsObject" : { + "emitStyle" : "const", + "name" : "AllTypesResult", + "staticMethods" : [ - } - } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AllTypesResult", + "tsFullPath" : "AllTypesResult" }, { - "abiName" : "bjs_roundTripDictionaryExport", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDictionaryExport", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "dictionary" : { - "_0" : { - "int" : { - + "associatedValues" : [ + { + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" } } } - } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "int" : { - + ], + "name" : "precision" + }, + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalDictionaryExport", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalDictionaryExport", - "parameters" : [ + ], + "name" : "direction" + }, { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "dictionary" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { "_0" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" } - } + }, + "_1" : "null" } - }, - "_1" : "null" + } } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { - + ], + "name" : "optPrecision" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" } } } - }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_roundTripJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripJSValue", - "parameters" : [ + ], + "name" : "optDirection" + }, { - "label" : "v", - "name" : "v", - "type" : { - "jsValue" : { + "associatedValues" : [ - } - } + ], + "name" : "empty" } ], - "returnType" : { - "jsValue" : { + "emitStyle" : "const", + "name" : "TypedPayloadResult", + "staticMethods" : [ - } - } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TypedPayloadResult", + "tsFullPath" : "TypedPayloadResult" }, { - "abiName" : "bjs_roundTripOptionalJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalJSValue", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "jsValue" : { + "associatedValues" : [ + + ], + "name" : "scientific" + }, + { + "associatedValues" : [ + + ], + "name" : "basic" + } + ], + "emitStyle" : "const", + "name" : "StaticCalculator", + "staticMethods" : [ + { + "abiName" : "bjs_StaticCalculator_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "int" : { } - }, - "_1" : "null" + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" } } } ], - "returnType" : { - "nullable" : { - "_0" : { - "jsValue" : { + "staticProperties" : [ - } - }, - "_1" : "null" - } - } + ], + "swiftCallName" : "StaticCalculator", + "tsFullPath" : "StaticCalculator" }, { - "abiName" : "bjs_roundTripJSValueArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripJSValueArray", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "array" : { - "_0" : { - "jsValue" : { + "cases" : [ - } - } - } - } - } ], - "returnType" : { - "array" : { - "_0" : { - "jsValue" : { + "emitStyle" : "const", + "name" : "StaticUtils", + "staticMethods" : [ - } - } - } - } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "StaticUtils", + "tsFullPath" : "StaticUtils" }, { - "abiName" : "bjs_roundTripOptionalJSValueArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalJSValueArray", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "cases" : [ - } - } - } - }, - "_1" : "null" - } - } - } ], - "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "emitStyle" : "const", + "name" : "Nested", + "namespace" : [ + "StaticUtils" + ], + "staticMethods" : [ + { + "abiName" : "bjs_StaticUtils_Nested_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "namespace" : [ + "StaticUtils", + "Nested" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { } } } - }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_makeImportedFoo", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "makeImportedFoo", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { + ], + "returnType" : { "string" : { } - } - } - ], - "returnType" : { - "jsObject" : { - "_0" : "Foo" - } - } - }, - { - "abiName" : "bjs_throwsSwiftError", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsSwiftError", - "parameters" : [ - { - "label" : "shouldThrow", - "name" : "shouldThrow", - "type" : { - "bool" : { - + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticUtils.Nested" } } } ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_throwsWithIntResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithIntResult", - "parameters" : [ + "staticProperties" : [ ], - "returnType" : { - "int" : { - - } - } + "swiftCallName" : "StaticUtils.Nested", + "tsFullPath" : "StaticUtils.Nested" }, { - "abiName" : "bjs_throwsWithStringResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithStringResult", - "parameters" : [ + "cases" : [ ], - "returnType" : { - "string" : { + "emitStyle" : "const", + "name" : "GraphOperations", + "namespace" : [ + "Services", + "Graph" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createGraph", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "rootId", + "name" : "rootId", + "type" : { + "int" : { - } - } - }, - { - "abiName" : "bjs_throwsWithBoolResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithBoolResult", - "parameters" : [ + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "nodeCount", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { - ], - "returnType" : { - "bool" : { + } + } + } + ], + "returnType" : { + "int" : { + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } } - } - }, - { - "abiName" : "bjs_throwsWithFloatResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithFloatResult", - "parameters" : [ - ], - "returnType" : { - "float" : { + "staticProperties" : [ - } - } + ], + "swiftCallName" : "GraphOperations", + "tsFullPath" : "Services.Graph.GraphOperations" }, { - "abiName" : "bjs_throwsWithDoubleResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithDoubleResult", - "parameters" : [ + "cases" : [ + { + "associatedValues" : [ - ], - "returnType" : { - "double" : { + ], + "name" : "option1" + }, + { + "associatedValues" : [ + ], + "name" : "option2" } - } - }, - { - "abiName" : "bjs_throwsWithSwiftHeapObjectResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithSwiftHeapObjectResult", - "parameters" : [ - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "abiName" : "bjs_throwsWithJSObjectResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithJSObjectResult", - "parameters" : [ + "emitStyle" : "const", + "name" : "StaticPropertyEnum", + "staticMethods" : [ ], - "returnType" : { - "jsObject" : { + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumProperty", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "string" : { - } - } - }, - { - "abiName" : "bjs_asyncRoundTripVoid", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripVoid", - "parameters" : [ + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "enumConstant", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "int" : { - ], - "returnType" : { - "void" : { + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumBool", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "bool" : { - } - } - }, - { - "abiName" : "bjs_asyncRoundTripInt", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripInt", - "parameters" : [ + } + } + }, { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "enumVariable", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, "type" : { "int" : { } } - } - ], - "returnType" : { - "int" : { + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "computedReadonly", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "int" : { - } - } - }, - { - "abiName" : "bjs_asyncRoundTripFloat", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripFloat", - "parameters" : [ + } + } + }, { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "computedReadWrite", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, "type" : { - "float" : { + "string" : { } } } ], - "returnType" : { - "float" : { - - } - } + "swiftCallName" : "StaticPropertyEnum", + "tsFullPath" : "StaticPropertyEnum" }, { - "abiName" : "bjs_asyncRoundTripDouble", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripDouble", - "parameters" : [ + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "StaticPropertyNamespace", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "namespaceProperty", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace" + } + }, + "type" : { + "string" : { + + } + } + }, { - "label" : "v", - "name" : "v", + "isReadonly" : true, + "isStatic" : true, + "name" : "namespaceConstant", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace" + } + }, "type" : { - "double" : { + "string" : { } } } ], - "returnType" : { - "double" : { - - } - } + "swiftCallName" : "StaticPropertyNamespace", + "tsFullPath" : "StaticPropertyNamespace" }, { - "abiName" : "bjs_asyncRoundTripBool", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripBool", - "parameters" : [ + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "NestedProperties", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedProperty", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { - "bool" : { + "int" : { } } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripString", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripString", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", + "isReadonly" : true, + "isStatic" : true, + "name" : "nestedConstant", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { "string" : { } } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripSwiftHeapObject", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripSwiftHeapObject", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedDouble", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "double" : { + } } } ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "swiftCallName" : "StaticPropertyNamespace.NestedProperties", + "tsFullPath" : "StaticPropertyNamespace.NestedProperties" }, { - "abiName" : "bjs_asyncRoundTripJSObject", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripJSObject", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "jsObject" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Address" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optStruct" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optClass" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "jsObject" : { + ], + "name" : "optJSObject" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optNestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { - } - } - }, - { - "abiName" : "bjs_takeGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeGreeter", - "parameters" : [ + } + } + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optArray" + }, { - "label" : "g", - "name" : "g", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } } - } + ], + "name" : "optJsClass" }, { - "label" : "name", - "name" : "name", - "type" : { - "string" : { + "associatedValues" : [ - } - } + ], + "name" : "empty" } ], - "returnType" : { - "void" : { + "emitStyle" : "const", + "name" : "OptionalAllTypesResult", + "staticMethods" : [ - } - } - }, - { - "abiName" : "bjs_createCalculator", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createCalculator", - "parameters" : [ + ], + "staticProperties" : [ ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Calculator" - } - } + "swiftCallName" : "OptionalAllTypesResult", + "tsFullPath" : "OptionalAllTypesResult" }, { - "abiName" : "bjs_useCalculator", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "useCalculator", - "parameters" : [ + "cases" : [ { - "label" : "calc", - "name" : "calc", - "type" : { - "swiftHeapObject" : { - "_0" : "Calculator" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } } - } + ], + "name" : "success" }, { - "label" : "x", - "name" : "x", - "type" : { - "int" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + } + }, + "_1" : "null" + } + } } - } + ], + "name" : "failure" }, { - "label" : "y", - "name" : "y", - "type" : { - "int" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" + } + } } - } + ], + "name" : "status" } ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_testGreeterToJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testGreeterToJSValue", - "parameters" : [ + "emitStyle" : "const", + "name" : "APIOptionalResult", + "staticMethods" : [ ], - "returnType" : { - "jsObject" : { + "staticProperties" : [ - } - } - }, + ], + "swiftCallName" : "APIOptionalResult", + "tsFullPath" : "APIOptionalResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ { - "abiName" : "bjs_testCalculatorToJSValue", + "abiName" : "bjs_roundTripVoid", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testCalculatorToJSValue", + "name" : "roundTripVoid", "parameters" : [ ], "returnType" : { - "jsObject" : { + "void" : { } } }, { - "abiName" : "bjs_testSwiftClassAsJSValue", + "abiName" : "bjs_roundTripInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testSwiftClassAsJSValue", + "name" : "roundTripInt", "parameters" : [ { - "label" : "greeter", - "name" : "greeter", + "label" : "v", + "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "int" : { + } } } ], "returnType" : { - "jsObject" : { + "int" : { } } }, { - "abiName" : "bjs_setDirection", + "abiName" : "bjs_roundTripUInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setDirection", + "name" : "roundTripUInt", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "uint" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" - } - } - }, - { - "abiName" : "bjs_getDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getDirection", - "parameters" : [ + "uint" : { - ], - "returnType" : { - "caseEnum" : { - "_0" : "Direction" } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_roundTripFloat", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "roundTripFloat", "parameters" : [ { - "label" : "_", - "name" : "input", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "float" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "float" : { + } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_roundTripDouble", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "roundTripDouble", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "double" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "double" : { + } } }, { - "abiName" : "bjs_getTheme", + "abiName" : "bjs_roundTripBool", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTheme", + "name" : "roundTripBool", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "bool" : { + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "bool" : { + } } }, { - "abiName" : "bjs_setHttpStatus", + "abiName" : "bjs_roundTripString", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setHttpStatus", + "name" : "roundTripString", "parameters" : [ { - "label" : "_", - "name" : "status", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "string" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "string" : { + } } }, { - "abiName" : "bjs_getHttpStatus", + "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getHttpStatus", + "name" : "roundTripSwiftHeapObject", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_processTheme", + "abiName" : "bjs_roundTripUnsafeRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processTheme", + "name" : "roundTripUnsafeRawPointer", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } }, { - "abiName" : "bjs_setTSDirection", + "abiName" : "bjs_roundTripUnsafeMutableRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSDirection", + "name" : "roundTripUnsafeMutableRawPointer", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "TSDirection" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } }, { - "abiName" : "bjs_getTSDirection", + "abiName" : "bjs_roundTripOpaquePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSDirection", + "name" : "roundTripOpaquePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } } } }, { - "abiName" : "bjs_setTSTheme", + "abiName" : "bjs_roundTripUnsafePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSTheme", + "name" : "roundTripUnsafePointer", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_getTSTheme", + "abiName" : "bjs_roundTripUnsafeMutablePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSTheme", + "name" : "roundTripUnsafeMutablePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_createConverter", + "abiName" : "bjs_roundTripJSObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createConverter", + "name" : "roundTripJSObject", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "jsObject" : { + } } }, { - "abiName" : "bjs_useConverter", + "abiName" : "bjs_roundTripDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "useConverter", + "name" : "roundTripDictionaryExport", "parameters" : [ { - "label" : "converter", - "name" : "converter", - "type" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" - } - } - }, - { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "int" : { + "dictionary" : { + "_0" : { + "int" : { + } + } } } } ], "returnType" : { - "string" : { + "dictionary" : { + "_0" : { + "int" : { + } + } } } }, { - "abiName" : "bjs_roundTripConverterArray", + "abiName" : "bjs_roundTripOptionalDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripConverterArray", + "name" : "roundTripOptionalDictionaryExport", "parameters" : [ { - "label" : "_", - "name" : "converters", + "label" : "v", + "name" : "v", "type" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "dictionary" : { + "_0" : { + "string" : { + + } + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "dictionary" : { + "_0" : { + "string" : { + + } + } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_createHTTPServer", + "abiName" : "bjs_roundTripJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createHTTPServer", + "name" : "roundTripJSValue", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsValue" : { + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Networking.API.HTTPServer" + "jsValue" : { + } } }, { - "abiName" : "bjs_createUUID", + "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createUUID", + "name" : "roundTripOptionalJSValue", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripUUID", + "abiName" : "bjs_roundTripOptionalJSValueArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUUID", + "name" : "roundTripOptionalJSValueArray", "parameters" : [ { - "label" : "_", - "name" : "uuid", + "label" : "v", + "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "UUID" + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundtripNetworkingAPIMethod", + "abiName" : "bjs_makeImportedFoo", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripNetworkingAPIMethod", + "name" : "makeImportedFoo", "parameters" : [ { - "label" : "_", - "name" : "method", + "label" : "value", + "name" : "value", "type" : { - "caseEnum" : { - "_0" : "Networking.API.Method" + "string" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Networking.API.Method" + "jsObject" : { + "_0" : "Foo" } } }, { - "abiName" : "bjs_roundtripConfigurationLogLevel", + "abiName" : "bjs_throwsSwiftError", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripConfigurationLogLevel", + "name" : "throwsSwiftError", "parameters" : [ { - "label" : "_", - "name" : "level", + "label" : "shouldThrow", + "name" : "shouldThrow", "type" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" + "bool" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" + "void" : { + } } }, { - "abiName" : "bjs_roundtripConfigurationPort", + "abiName" : "bjs_throwsWithIntResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripConfigurationPort", + "name" : "throwsWithIntResult", "parameters" : [ - { - "label" : "_", - "name" : "port", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" + "int" : { + } } }, { - "abiName" : "bjs_processConfigurationLogLevel", + "abiName" : "bjs_throwsWithStringResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "processConfigurationLogLevel", + "name" : "throwsWithStringResult", "parameters" : [ - { - "label" : "_", - "name" : "level", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" + "string" : { + } } }, { - "abiName" : "bjs_roundtripInternalSupportedMethod", + "abiName" : "bjs_throwsWithBoolResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripInternalSupportedMethod", + "name" : "throwsWithBoolResult", "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" + "bool" : { + } } }, { - "abiName" : "bjs_roundtripAPIResult", + "abiName" : "bjs_throwsWithFloatResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripAPIResult", + "name" : "throwsWithFloatResult", "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "float" : { + } } }, { - "abiName" : "bjs_makeAPIResultSuccess", + "abiName" : "bjs_throwsWithDoubleResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "makeAPIResultSuccess", + "name" : "throwsWithDoubleResult", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "double" : { + } } }, { - "abiName" : "bjs_makeAPIResultFailure", + "abiName" : "bjs_throwsWithSwiftHeapObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "makeAPIResultFailure", + "name" : "throwsWithSwiftHeapObjectResult", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "int" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_makeAPIResultInfo", + "abiName" : "bjs_throwsWithJSObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "makeAPIResultInfo", + "name" : "throwsWithJSObjectResult", "parameters" : [ ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripVoid", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + } } }, { - "abiName" : "bjs_makeAPIResultFlag", + "abiName" : "bjs_asyncRoundTripInt", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultFlag", + "name" : "asyncRoundTripInt", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "bool" : { + "int" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "int" : { + } } }, { - "abiName" : "bjs_makeAPIResultRate", + "abiName" : "bjs_asyncRoundTripFloat", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultRate", + "name" : "asyncRoundTripFloat", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { "float" : { @@ -7385,23 +8252,23 @@ } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "float" : { + } } }, { - "abiName" : "bjs_makeAPIResultPrecise", + "abiName" : "bjs_asyncRoundTripDouble", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultPrecise", + "name" : "asyncRoundTripDouble", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { "double" : { @@ -7410,48 +8277,48 @@ } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "double" : { + } } }, { - "abiName" : "bjs_roundtripComplexResult", + "abiName" : "bjs_asyncRoundTripBool", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripComplexResult", + "name" : "asyncRoundTripBool", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "v", + "name" : "v", "type" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "bool" : { + } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "bool" : { + } } }, { - "abiName" : "bjs_makeComplexResultSuccess", + "abiName" : "bjs_asyncRoundTripString", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultSuccess", + "name" : "asyncRoundTripString", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { "string" : { @@ -7460,118 +8327,82 @@ } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "string" : { + } } }, { - "abiName" : "bjs_makeComplexResultError", + "abiName" : "bjs_asyncRoundTripSwiftHeapObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultError", + "name" : "asyncRoundTripSwiftHeapObject", "parameters" : [ { - "label" : "_", - "name" : "message", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "label" : "v", + "name" : "v", "type" : { - "int" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_makeComplexResultLocation", + "abiName" : "bjs_asyncRoundTripJSObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultLocation", + "name" : "asyncRoundTripJSObject", "parameters" : [ { - "label" : "_", - "name" : "lat", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "lng", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "name", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "jsObject" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeComplexResultStatus", + "abiName" : "bjs_takeGreeter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultStatus", + "name" : "takeGreeter", "parameters" : [ { - "label" : "_", - "name" : "active", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "label" : "g", + "name" : "g", "type" : { - "int" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "label" : "_", - "name" : "message", + "label" : "name", + "name" : "name", "type" : { "string" : { @@ -7580,577 +8411,441 @@ } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "void" : { + } } }, { - "abiName" : "bjs_makeComplexResultCoordinates", + "abiName" : "bjs_createCalculator", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultCoordinates", + "name" : "createCalculator", "parameters" : [ - { - "label" : "_", - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "y", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "z", - "type" : { - "double" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "abiName" : "bjs_makeComplexResultComprehensive", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeComplexResultComprehensive", - "parameters" : [ - { - "label" : "_", - "name" : "flag1", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "flag2", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "count1", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "count2", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "value1", - "type" : { - "double" : { - - } - } - }, + "abiName" : "bjs_useCalculator", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "useCalculator", + "parameters" : [ { - "label" : "_", - "name" : "value2", + "label" : "calc", + "name" : "calc", "type" : { - "double" : { - + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "label" : "_", - "name" : "text1", + "label" : "x", + "name" : "x", "type" : { - "string" : { + "int" : { } } }, { - "label" : "_", - "name" : "text2", + "label" : "y", + "name" : "y", "type" : { - "string" : { + "int" : { } } - }, - { - "label" : "_", - "name" : "text3", - "type" : { - "string" : { + } + ], + "returnType" : { + "int" : { - } - } } + } + }, + { + "abiName" : "bjs_testGreeterToJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testGreeterToJSValue", + "parameters" : [ + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeComplexResultInfo", + "abiName" : "bjs_testCalculatorToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultInfo", + "name" : "testCalculatorToJSValue", "parameters" : [ ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeUtilitiesResultSuccess", + "abiName" : "bjs_testSwiftClassAsJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultSuccess", + "name" : "testSwiftClassAsJSValue", "parameters" : [ { - "label" : "_", - "name" : "message", + "label" : "greeter", + "name" : "greeter", "type" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeUtilitiesResultFailure", + "abiName" : "bjs_setDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultFailure", + "name" : "setDirection", "parameters" : [ { "label" : "_", - "name" : "error", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "name" : "direction", "type" : { - "int" : { - + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_makeUtilitiesResultStatus", + "abiName" : "bjs_getDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultStatus", + "name" : "getDirection", "parameters" : [ - { - "label" : "_", - "name" : "active", - "type" : { - "bool" : { - } - } - }, - { - "label" : "_", - "name" : "code", - "type" : { - "int" : { - - } - } - }, + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "abiName" : "bjs_processDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDirection", + "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "input", "type" : { - "string" : { - + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_makeAPINetworkingResultSuccess", + "abiName" : "bjs_setTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultSuccess", + "name" : "setTheme", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "theme", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_makeAPINetworkingResultFailure", + "abiName" : "bjs_getTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultFailure", + "name" : "getTheme", "parameters" : [ - { - "label" : "_", - "name" : "error", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", - "type" : { - "int" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundtripUtilitiesResult", + "abiName" : "bjs_setHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripUtilitiesResult", + "name" : "setHttpStatus", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "status", "type" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_roundtripAPINetworkingResult", + "abiName" : "bjs_getHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripAPINetworkingResult", + "name" : "getHttpStatus", "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" - } - } - } + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_roundTripAllTypesResult", + "abiName" : "bjs_processTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripAllTypesResult", + "name" : "processTheme", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "theme", "type" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_roundTripTypedPayloadResult", + "abiName" : "bjs_setTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripTypedPayloadResult", + "name" : "setTSDirection", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "direction", "type" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" + "caseEnum" : { + "_0" : "TSDirection" } } } ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" + "returnType" : { + "caseEnum" : { + "_0" : "TSDirection" } } }, { - "abiName" : "bjs_createPropertyHolder", + "abiName" : "bjs_getTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createPropertyHolder", + "name" : "getTSDirection", "parameters" : [ - { - "label" : "intValue", - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "label" : "floatValue", - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "label" : "doubleValue", - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "label" : "boolValue", - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "stringValue", - "name" : "stringValue", - "type" : { - "string" : { - } - } - }, - { - "label" : "jsObject", - "name" : "jsObject", - "type" : { - "jsObject" : { - - } - } - } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" + "caseEnum" : { + "_0" : "TSDirection" } } }, { - "abiName" : "bjs_testPropertyHolder", + "abiName" : "bjs_setTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testPropertyHolder", + "name" : "setTSTheme", "parameters" : [ { - "label" : "holder", - "name" : "holder", + "label" : "_", + "name" : "theme", "type" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } } ], "returnType" : { - "string" : { - + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, { - "abiName" : "bjs_resetObserverCounts", + "abiName" : "bjs_getTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "resetObserverCounts", + "name" : "getTSTheme", "parameters" : [ ], "returnType" : { - "void" : { - + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, { - "abiName" : "bjs_getObserverStats", + "abiName" : "bjs_createConverter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getObserverStats", + "name" : "createConverter", "parameters" : [ ], "returnType" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Utils.Converter" } } }, { - "abiName" : "bjs_testStringDefault", + "abiName" : "bjs_useConverter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testStringDefault", + "name" : "useConverter", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Hello World" + "label" : "converter", + "name" : "converter", + "type" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" } - }, - "label" : "message", - "name" : "message", + } + }, + { + "label" : "value", + "name" : "value", "type" : { - "string" : { + "int" : { } } @@ -8163,246 +8858,199 @@ } }, { - "abiName" : "bjs_testIntDefault", + "abiName" : "bjs_roundTripConverterArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testIntDefault", + "name" : "roundTripConverterArray", "parameters" : [ { - "defaultValue" : { - "int" : { - "_0" : 42 - } - }, - "label" : "count", - "name" : "count", + "label" : "_", + "name" : "converters", "type" : { - "int" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } } ], "returnType" : { - "int" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } }, { - "abiName" : "bjs_testBoolDefault", + "abiName" : "bjs_createHTTPServer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testBoolDefault", + "name" : "createHTTPServer", "parameters" : [ - { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "flag", - "name" : "flag", - "type" : { - "bool" : { - } - } - } ], "returnType" : { - "bool" : { - + "swiftHeapObject" : { + "_0" : "Networking.API.HTTPServer" } } }, { - "abiName" : "bjs_testOptionalDefault", + "abiName" : "bjs_createUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testOptionalDefault", + "name" : "createUUID", "parameters" : [ { - "defaultValue" : { - "null" : { - - } - }, - "label" : "name", - "name" : "name", + "label" : "value", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "swiftHeapObject" : { + "_0" : "UUID" } } }, { - "abiName" : "bjs_testMultipleDefaults", + "abiName" : "bjs_roundTripUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testMultipleDefaults", + "name" : "roundTripUUID", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Default Title" - } - }, - "label" : "title", - "name" : "title", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "int" : { - "_0" : -10 - } - }, - "label" : "count", - "name" : "count", + "label" : "_", + "name" : "uuid", "type" : { - "int" : { - + "swiftHeapObject" : { + "_0" : "UUID" } } - }, - { - "defaultValue" : { - "bool" : { - "_0" : false - } - }, - "label" : "enabled", - "name" : "enabled", + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "UUID" + } + } + }, + { + "abiName" : "bjs_roundtripNetworkingAPIMethod", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripNetworkingAPIMethod", + "parameters" : [ + { + "label" : "_", + "name" : "method", "type" : { - "bool" : { - + "caseEnum" : { + "_0" : "Networking.API.Method" } } } ], "returnType" : { - "string" : { - + "caseEnum" : { + "_0" : "Networking.API.Method" } } }, { - "abiName" : "bjs_testSimpleEnumDefault", + "abiName" : "bjs_roundtripConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testSimpleEnumDefault", + "name" : "roundtripConfigurationLogLevel", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "success" - } - }, - "label" : "status", - "name" : "status", + "label" : "_", + "name" : "level", "type" : { - "caseEnum" : { - "_0" : "Status" + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } }, { - "abiName" : "bjs_testDirectionDefault", + "abiName" : "bjs_roundtripConfigurationPort", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testDirectionDefault", + "name" : "roundtripConfigurationPort", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Direction", - "_1" : "north" - } - }, - "label" : "direction", - "name" : "direction", + "label" : "_", + "name" : "port", "type" : { - "caseEnum" : { - "_0" : "Direction" + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_testRawStringEnumDefault", + "abiName" : "bjs_processConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testRawStringEnumDefault", + "name" : "processConfigurationLogLevel", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Theme", - "_1" : "light" - } - }, - "label" : "theme", - "name" : "theme", + "label" : "_", + "name" : "level", "type" : { "rawValueEnum" : { - "_0" : "Theme", + "_0" : "Configuration.LogLevel", "_1" : "String" } } @@ -8410,1687 +9058,1308 @@ ], "returnType" : { "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_testComplexInit", + "abiName" : "bjs_roundtripInternalSupportedMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testComplexInit", + "name" : "roundtripInternalSupportedMethod", "parameters" : [ { - "defaultValue" : { - "objectWithArguments" : { - "_0" : "Greeter", - "_1" : [ - { - "string" : { - "_0" : "DefaultGreeter" - } - } - ] - } - }, - "label" : "greeter", - "name" : "greeter", + "label" : "_", + "name" : "method", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "caseEnum" : { + "_0" : "Internal.SupportedMethod" } } } ], "returnType" : { - "string" : { - + "caseEnum" : { + "_0" : "Internal.SupportedMethod" } } }, { - "abiName" : "bjs_testEmptyInit", + "abiName" : "bjs_roundtripAPIResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testEmptyInit", + "name" : "roundtripAPIResult", "parameters" : [ { - "defaultValue" : { - "object" : { - "_0" : "StaticPropertyHolder" - } - }, - "label" : "_", - "name" : "object", + "label" : "result", + "name" : "result", "type" : { - "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" + "associatedValueEnum" : { + "_0" : "APIResult" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_arrayWithDefault", + "abiName" : "bjs_makeAPIResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayWithDefault", + "name" : "makeAPIResultSuccess", "parameters" : [ { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 1 - } - }, - { - "int" : { - "_0" : 2 - } - }, - { - "int" : { - "_0" : 3 - } - } - ] - } - }, "label" : "_", - "name" : "values", + "name" : "value", "type" : { - "array" : { - "_0" : { - "int" : { + "string" : { - } - } } } } ], "returnType" : { - "int" : { - + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_arrayWithOptionalDefault", + "abiName" : "bjs_makeAPIResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayWithOptionalDefault", + "name" : "makeAPIResultFailure", "parameters" : [ { - "defaultValue" : { - "null" : { - - } - }, "label" : "_", - "name" : "values", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + "int" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "int" : { - + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_arrayMixedDefaults", + "abiName" : "bjs_makeAPIResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayMixedDefaults", + "name" : "makeAPIResultInfo", "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Sum" - } - }, - "label" : "prefix", - "name" : "prefix", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 10 - } - }, - { - "int" : { - "_0" : 20 - } - } - ] - } - }, - "label" : "values", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "defaultValue" : { - "string" : { - "_0" : "!" - } - }, - "label" : "suffix", - "name" : "suffix", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_formatName", + "abiName" : "bjs_makeAPIResultFlag", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "formatName", + "name" : "makeAPIResultFlag", "parameters" : [ { "label" : "_", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "label" : "transform", - "name" : "transform", + "name" : "value", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { + "bool" : { - } - } - }, - "useJSTypedClosure" : false } } } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeFormatter", + "abiName" : "bjs_makeAPIResultRate", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeFormatter", + "name" : "makeAPIResultRate", "parameters" : [ { - "label" : "prefix", - "name" : "prefix", + "label" : "_", + "name" : "value", "type" : { - "string" : { + "float" : { } } } ], "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - "useJSTypedClosure" : false + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeAdder", + "abiName" : "bjs_makeAPIResultPrecise", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAdder", + "name" : "makeAPIResultPrecise", "parameters" : [ { - "label" : "base", - "name" : "base", + "label" : "_", + "name" : "value", "type" : { - "int" : { + "double" : { } } } ], "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "int" : { - - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - "useJSTypedClosure" : false + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripIntArray", + "abiName" : "bjs_roundtripComplexResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripIntArray", + "name" : "roundtripComplexResult", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "result", "type" : { - "array" : { - "_0" : { - "int" : { - - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } } ], "returnType" : { - "array" : { - "_0" : { - "int" : { - - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripStringArray", + "abiName" : "bjs_makeComplexResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripStringArray", + "name" : "makeComplexResultSuccess", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "value", "type" : { - "array" : { - "_0" : { - "string" : { + "string" : { - } - } } } } ], "returnType" : { - "array" : { - "_0" : { - "string" : { - - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripDoubleArray", + "abiName" : "bjs_makeComplexResultError", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDoubleArray", + "name" : "makeComplexResultError", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "message", "type" : { - "array" : { - "_0" : { - "double" : { + "string" : { - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "double" : { + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { } } } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } } }, { - "abiName" : "bjs_roundTripBoolArray", + "abiName" : "bjs_makeComplexResultLocation", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripBoolArray", + "name" : "makeComplexResultLocation", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "lat", "type" : { - "array" : { - "_0" : { - "bool" : { + "double" : { - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "bool" : { + }, + { + "label" : "_", + "name" : "lng", + "type" : { + "double" : { } } - } - } - }, - { - "abiName" : "bjs_roundTripDirectionArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDirectionArray", - "parameters" : [ + }, { "label" : "_", - "name" : "values", + "name" : "name", "type" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "string" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripStatusArray", + "abiName" : "bjs_makeComplexResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripStatusArray", + "name" : "makeComplexResultStatus", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "active", "type" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - } + "bool" : { + } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { + } } } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } } }, { - "abiName" : "bjs_roundTripThemeArray", + "abiName" : "bjs_makeComplexResultCoordinates", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripThemeArray", + "name" : "makeComplexResultCoordinates", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "x", "type" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "z", + "type" : { + "double" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripHttpStatusArray", + "abiName" : "bjs_makeComplexResultComprehensive", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripHttpStatusArray", + "name" : "makeComplexResultComprehensive", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "flag1", "type" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "flag2", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "count1", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "count2", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "value1", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "value2", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "text1", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "text2", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "text3", + "type" : { + "string" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripDataPointArray", + "abiName" : "bjs_makeComplexResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataPointArray", + "name" : "makeComplexResultInfo", "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } - } - } + ], "returnType" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripGreeterArray", + "abiName" : "bjs_makeUtilitiesResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripGreeterArray", + "name" : "makeUtilitiesResultSuccess", "parameters" : [ { "label" : "_", - "name" : "greeters", + "name" : "message", "type" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "string" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_roundTripOptionalIntArray", + "abiName" : "bjs_makeUtilitiesResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalIntArray", + "name" : "makeUtilitiesResultFailure", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "error", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "int" : { + "string" : { - } - }, - "_1" : "null" - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "int" : { + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { - } - }, - "_1" : "null" } } } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "Utilities.Result" + } } }, { - "abiName" : "bjs_roundTripOptionalStringArray", + "abiName" : "bjs_makeUtilitiesResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStringArray", + "name" : "makeUtilitiesResultStatus", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "active", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "string" : { + "bool" : { - } - }, - "_1" : "null" - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "string" : { + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { - } - }, - "_1" : "null" } } } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "Utilities.Result" + } } }, { - "abiName" : "bjs_roundTripOptionalDataPointArray", + "abiName" : "bjs_makeAPINetworkingResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDataPointArray", + "name" : "makeAPINetworkingResultSuccess", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "message", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - }, - "_1" : "null" - } - } + "string" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - }, - "_1" : "null" - } - } + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_roundTripOptionalDirectionArray", + "abiName" : "bjs_makeAPINetworkingResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDirectionArray", + "name" : "makeAPINetworkingResultFailure", "parameters" : [ { "label" : "_", - "name" : "directions", + "name" : "error", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" - } - } + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" - } - } + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_roundTripOptionalStatusArray", + "abiName" : "bjs_roundtripUtilitiesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStatusArray", + "name" : "roundtripUtilitiesResult", "parameters" : [ { "label" : "_", - "name" : "statuses", + "name" : "result", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - }, - "_1" : "null" - } - } + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } } ], "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - }, - "_1" : "null" - } - } + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_roundTripOptionalIntArrayType", + "abiName" : "bjs_roundtripAPINetworkingResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalIntArrayType", + "name" : "roundtripAPINetworkingResult", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_roundTripOptionalStringArrayType", + "abiName" : "bjs_roundTripAllTypesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStringArrayType", + "name" : "roundTripAllTypesResult", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } }, { - "abiName" : "bjs_roundTripOptionalGreeterArrayType", + "abiName" : "bjs_roundTripTypedPayloadResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalGreeterArrayType", + "name" : "roundTripTypedPayloadResult", "parameters" : [ { "label" : "_", - "name" : "greeters", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } }, { - "abiName" : "bjs_roundTripNestedIntArray", + "abiName" : "bjs_createPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedIntArray", + "name" : "createPropertyHolder", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "intValue", + "name" : "intValue", "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + "int" : { - } - } - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + }, + { + "label" : "floatValue", + "name" : "floatValue", + "type" : { + "float" : { - } - } } } - } - } - }, - { - "abiName" : "bjs_roundTripNestedStringArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripNestedStringArray", - "parameters" : [ + }, { - "label" : "_", - "name" : "values", + "label" : "doubleValue", + "name" : "doubleValue", "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "string" : { + "double" : { + + } + } + }, + { + "label" : "boolValue", + "name" : "boolValue", + "type" : { + "bool" : { - } - } - } - } } } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "string" : { + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { - } - } } } - } - } - }, - { - "abiName" : "bjs_roundTripNestedDoubleArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripNestedDoubleArray", - "parameters" : [ + }, { - "label" : "_", - "name" : "values", + "label" : "jsObject", + "name" : "jsObject", "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "double" : { + "jsObject" : { - } - } - } - } } } } ], "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "double" : { - - } - } - } - } + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } }, { - "abiName" : "bjs_roundTripNestedBoolArray", + "abiName" : "bjs_testPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedBoolArray", + "name" : "testPropertyHolder", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "holder", + "name" : "holder", "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "bool" : { - - } - } - } - } + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } } ], "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "bool" : { + "string" : { - } - } - } - } } } }, { - "abiName" : "bjs_roundTripNestedDataPointArray", + "abiName" : "bjs_resetObserverCounts", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedDataPointArray", + "name" : "resetObserverCounts", "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } - } - } - } - } + ], "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } - } + "void" : { + } } }, { - "abiName" : "bjs_roundTripNestedDirectionArray", + "abiName" : "bjs_getObserverStats", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedDirectionArray", + "name" : "getObserverStats", "parameters" : [ - { - "label" : "_", - "name" : "directions", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } - } - } + ], "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripNestedGreeterArray", + "abiName" : "bjs_testStringDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedGreeterArray", + "name" : "testStringDefault", "parameters" : [ { - "label" : "_", - "name" : "greeters", + "defaultValue" : { + "string" : { + "_0" : "Hello World" + } + }, + "label" : "message", + "name" : "message", "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } + "string" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripUnsafeRawPointerArray", + "abiName" : "bjs_testIntDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeRawPointerArray", + "name" : "testIntDefault", "parameters" : [ { - "label" : "_", - "name" : "values", + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } + "int" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } + "int" : { + } } }, { - "abiName" : "bjs_roundTripUnsafeMutableRawPointerArray", + "abiName" : "bjs_testBoolDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutableRawPointerArray", + "name" : "testBoolDefault", "parameters" : [ { - "label" : "_", - "name" : "values", + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "flag", + "name" : "flag", "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } + "bool" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } + "bool" : { + } } }, { - "abiName" : "bjs_roundTripOpaquePointerArray", + "abiName" : "bjs_testOptionalDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOpaquePointerArray", + "name" : "testOptionalDefault", "parameters" : [ { - "label" : "_", - "name" : "values", + "defaultValue" : { + "null" : { + + } + }, + "label" : "name", + "name" : "name", "type" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "string" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "string" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripUnsafePointerArray", + "abiName" : "bjs_testMultipleDefaults", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafePointerArray", + "name" : "testMultipleDefaults", "parameters" : [ { - "label" : "_", - "name" : "values", + "defaultValue" : { + "string" : { + "_0" : "Default Title" + } + }, + "label" : "title", + "name" : "title", "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } + "string" : { + + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : -10 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : false + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + } } } ], "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripUnsafeMutablePointerArray", + "abiName" : "bjs_testSimpleEnumDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutablePointerArray", + "name" : "testSimpleEnumDefault", "parameters" : [ { - "label" : "_", - "name" : "values", + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "success" + } + }, + "label" : "status", + "name" : "status", "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } + "caseEnum" : { + "_0" : "Status" } } } ], "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_consumeDataProcessorArrayType", + "abiName" : "bjs_testDirectionDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "consumeDataProcessorArrayType", + "name" : "testDirectionDefault", "parameters" : [ { - "label" : "_", - "name" : "processors", + "defaultValue" : { + "enumCase" : { + "_0" : "Direction", + "_1" : "north" + } + }, + "label" : "direction", + "name" : "direction", "type" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" - } - } + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "int" : { - + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_roundTripDataProcessorArrayType", + "abiName" : "bjs_testRawStringEnumDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataProcessorArrayType", + "name" : "testRawStringEnumDefault", "parameters" : [ { - "label" : "_", - "name" : "processors", + "defaultValue" : { + "enumCase" : { + "_0" : "Theme", + "_1" : "light" + } + }, + "label" : "theme", + "name" : "theme", "type" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" - } - } + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" - } - } + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundTripJSObjectArray", + "abiName" : "bjs_testComplexInit", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSObjectArray", + "name" : "testComplexInit", "parameters" : [ { - "label" : "_", - "name" : "objects", - "type" : { - "array" : { - "_0" : { - "jsObject" : { - + "defaultValue" : { + "objectWithArguments" : { + "_0" : "Greeter", + "_1" : [ + { + "string" : { + "_0" : "DefaultGreeter" + } } - } + ] + } + }, + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "array" : { - "_0" : { - "jsObject" : { + "string" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalJSObjectArray", + "abiName" : "bjs_testEmptyInit", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSObjectArray", + "name" : "testEmptyInit", "parameters" : [ { + "defaultValue" : { + "object" : { + "_0" : "StaticPropertyHolder" + } + }, "label" : "_", - "name" : "objects", + "name" : "object", "type" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "jsObject" : { - - } - }, - "_1" : "null" - } - } + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" } } } ], "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "jsObject" : { - - } - }, - "_1" : "null" - } - } + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" } } }, { - "abiName" : "bjs_roundTripFooArray", + "abiName" : "bjs_arrayWithDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripFooArray", + "name" : "arrayWithDefault", "parameters" : [ { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 1 + } + }, + { + "int" : { + "_0" : 2 + } + }, + { + "int" : { + "_0" : 3 + } + } + ] + } + }, "label" : "_", - "name" : "foos", + "name" : "values", "type" : { "array" : { "_0" : { - "jsObject" : { - "_0" : "Foo" + "int" : { + } } } @@ -10098,70 +10367,92 @@ } ], "returnType" : { - "array" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - } + "int" : { + } } }, { - "abiName" : "bjs_roundTripOptionalFooArray", + "abiName" : "bjs_arrayWithOptionalDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalFooArray", + "name" : "arrayWithOptionalDefault", "parameters" : [ { + "defaultValue" : { + "null" : { + + } + }, "label" : "_", - "name" : "foos", + "name" : "values", "type" : { - "array" : { + "nullable" : { "_0" : { - "nullable" : { + "array" : { "_0" : { - "jsObject" : { - "_0" : "Foo" + "int" : { + } - }, - "_1" : "null" + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { - "_0" : { - "nullable" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - }, - "_1" : "null" - } - } + "int" : { + } } }, { - "abiName" : "bjs_multiArrayFirstNums", + "abiName" : "bjs_arrayMixedDefaults", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "multiArrayFirstNums", + "name" : "arrayMixedDefaults", "parameters" : [ { - "label" : "nums", - "name" : "nums", + "defaultValue" : { + "string" : { + "_0" : "Sum" + } + }, + "label" : "prefix", + "name" : "prefix", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 10 + } + }, + { + "int" : { + "_0" : 20 + } + } + ] + } + }, + "label" : "values", + "name" : "values", "type" : { "array" : { "_0" : { @@ -10173,111 +10464,182 @@ } }, { - "label" : "strs", - "name" : "strs", + "defaultValue" : { + "string" : { + "_0" : "!" + } + }, + "label" : "suffix", + "name" : "suffix", "type" : { - "array" : { - "_0" : { - "string" : { + "string" : { - } - } } } } ], "returnType" : { - "array" : { - "_0" : { - "int" : { + "string" : { - } - } } } }, { - "abiName" : "bjs_multiArrayFirstStrs", + "abiName" : "bjs_formatName", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "multiArrayFirstStrs", + "name" : "formatName", "parameters" : [ { - "label" : "nums", - "name" : "nums", + "label" : "_", + "name" : "name", "type" : { - "array" : { - "_0" : { - "int" : { + "string" : { - } - } } } }, { - "label" : "strs", - "name" : "strs", + "label" : "transform", + "name" : "transform", "type" : { - "array" : { + "closure" : { "_0" : { - "string" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + } } - } + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "array" : { - "_0" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeFormatter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeFormatter", + "parameters" : [ + { + "label" : "prefix", + "name" : "prefix", + "type" : { "string" : { } } } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } } }, { - "abiName" : "bjs_multiOptionalArrayFirstA", + "abiName" : "bjs_makeAdder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "multiOptionalArrayFirstA", + "name" : "makeAdder", "parameters" : [ { - "label" : "a", - "name" : "a", + "label" : "base", + "name" : "base", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + "int" : { - } - } - } - }, - "_1" : "null" } } - }, + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundTripOptionalIntArrayType", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalIntArrayType", + "parameters" : [ { - "label" : "b", - "name" : "b", + "label" : "_", + "name" : "values", "type" : { "nullable" : { "_0" : { "array" : { "_0" : { - "string" : { + "int" : { } } @@ -10304,23 +10666,23 @@ } }, { - "abiName" : "bjs_multiOptionalArrayFirstB", + "abiName" : "bjs_roundTripOptionalStringArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "multiOptionalArrayFirstB", + "name" : "roundTripOptionalStringArrayType", "parameters" : [ { - "label" : "a", - "name" : "a", + "label" : "_", + "name" : "values", "type" : { "nullable" : { "_0" : { "array" : { "_0" : { - "int" : { + "string" : { } } @@ -10329,17 +10691,42 @@ "_1" : "null" } } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalGreeterArrayType", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalGreeterArrayType", + "parameters" : [ { - "label" : "b", - "name" : "b", + "label" : "_", + "name" : "greeters", "type" : { "nullable" : { "_0" : { "array" : { "_0" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } } @@ -10354,8 +10741,8 @@ "_0" : { "array" : { "_0" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } } @@ -11994,6 +12381,23 @@ } ], "protocols" : [ + { + "methods" : [ + + ], + "name" : "ArrayElementProtocol", + "properties" : [ + { + "isReadonly" : false, + "name" : "value", + "type" : { + "int" : { + + } + } + } + ] + }, { "methods" : [ { @@ -14048,6 +14452,222 @@ } } }, + { + "name" : "jsRoundTripOptionalIntArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "name" : "jsRoundTripOptionalStringArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "name" : "jsRoundTripOptionalBoolArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "name" : "jsRoundTripOptionalJSValueArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "name" : "jsRoundTripOptionalJSObjectArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "name" : "jsRoundTripOptionalJSClassArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "ArrayElementObject" + } + }, + "_1" : "null" + } + } + } + } + }, { "name" : "jsSumNumberArray", "parameters" : [ @@ -14084,6 +14704,17 @@ } } } + }, + { + "name" : "runJsArraySupportTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } } ] } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs index 5c3b20e63..b877e9cf2 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs @@ -1,5 +1,7 @@ // @ts-check +import assert from 'node:assert'; + export class ArrayElementObject { constructor(id) { this.id = id; @@ -29,9 +31,6 @@ export function getImports(importsContext) { jsRoundTripJSValueArray: (values) => { return values; }, - jsRoundTripOptionalJSValueArray: (values) => { - return values ?? null; - }, jsSumNumberArray: (values) => { return values.reduce((a, b) => a + b, 0); }, @@ -44,5 +43,166 @@ export function getImports(importsContext) { jsRoundTripJSClassArray: (values) => { return values; }, + jsRoundTripOptionalIntArray: (values) => { + return values; + }, + jsRoundTripOptionalStringArray: (values) => { + return values; + }, + jsRoundTripOptionalBoolArray: (values) => { + return values; + }, + jsRoundTripOptionalJSValueArray: (values) => { + return values; + }, + jsRoundTripOptionalJSObjectArray: (values) => { + return values; + }, + jsRoundTripOptionalJSClassArray: (values) => { + return values; + }, + runJsArraySupportTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsArraySupportTests(exports); + }, }; +} + +/** + * Array value bridging coverage for BridgeJS runtime tests. + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports + */ +export function runJsArraySupportTests(rootExports) { + const exports = rootExports.ArraySupportExports; + const { Direction, Status, Theme, HttpStatus, Greeter, Utils } = rootExports; + + // Primitive arrays + assert.deepEqual(exports.roundTripIntArray([1, 2, 3, -10, 2147483647]), [1, 2, 3, -10, 2147483647]); + assert.deepEqual(exports.roundTripIntArray([]), []); + assert.deepEqual(exports.roundTripStringArray(["Hello", "World", ""]), ["Hello", "World", ""]); + const doubles = exports.roundTripDoubleArray([1.5, 0.0, -1.5, Infinity, NaN]); + assert.equal(doubles[0], 1.5); + assert(Number.isNaN(doubles[4])); + assert.deepEqual(exports.roundTripBoolArray([true, false, true]), [true, false, true]); + + // UnsafePointer-family arrays + const pointerValues = [1, 4, 1024, 65536, 2147483647]; + assert.deepEqual(exports.roundTripUnsafeRawPointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafeMutableRawPointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripOpaquePointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafePointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafeMutablePointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafeRawPointerArray([]), []); + + // JSValue arrays + const jsValueArray = [true, 42, "ok", { nested: 1 }, null, undefined, Symbol("s"), BigInt(3)]; + assert.deepEqual(exports.roundTripJSValueArray(jsValueArray), jsValueArray); + + // JSObject arrays + const jsObj1 = { a: 1, b: "hello" }; + const jsObj2 = { x: [1, 2, 3], y: { nested: true } }; + const jsObjResult = exports.roundTripJSObjectArray([jsObj1, jsObj2]); + assert.equal(jsObjResult.length, 2); + assert.equal(jsObjResult[0], jsObj1); + assert.equal(jsObjResult[1], jsObj2); + assert.deepEqual(exports.roundTripJSObjectArray([]), []); + + // Enum arrays + assert.deepEqual(exports.roundTripCaseEnumArray([Direction.North, Direction.South]), [Direction.North, Direction.South]); + assert.deepEqual(exports.roundTripIntRawValueEnumArray([HttpStatus.Ok, HttpStatus.NotFound]), [HttpStatus.Ok, HttpStatus.NotFound]); + assert.deepEqual(exports.roundTripStringRawValueEnumArray([Theme.Light, Theme.Dark]), [Theme.Light, Theme.Dark]); + + // Struct arrays + const points = [ + { x: 1.0, y: 2.0, label: "A", optCount: 10, optFlag: true }, + { x: 3.0, y: 4.0, label: "B", optCount: null, optFlag: null } + ]; + const pointResult = exports.roundTripStructArray(points); + assert.equal(pointResult[0].optCount, 10); + assert.equal(pointResult[1].optCount, null); + + // Class arrays + const g1 = new Greeter("Alice"); + const g2 = new Greeter("Bob"); + const gResult = exports.roundTripSwiftClassArray([g1, g2]); + assert.equal(gResult[0].name, "Alice"); + assert.equal(gResult[1].greet(), "Hello, Bob!"); + g1.release(); g2.release(); + gResult.forEach(g => g.release()); + + // Namespaced Swift class arrays + const c1 = rootExports.createConverter(); + const c2 = rootExports.createConverter(); + const converterArray = exports.roundTripNamespacedSwiftClassArray([c1, c2]); + assert.equal(converterArray.length, 2); + assert.equal(converterArray[0].toString(10), "10"); + assert.equal(converterArray[1].toString(20), "20"); + c1.release(); + c2.release(); + converterArray.forEach((c) => c.release()); + + // Protocol arrays + /** @type {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').ArrayElementProtocol[]} */ + const protocolArray = [{ value: 1 }]; + const result = exports.roundTripProtocolArray(protocolArray); + assert.equal(result.length, 1); + assert.equal(result[0], protocolArray[0]); + assert.equal(result[0].value, 1); + + // @JSClass struct arrays + const foo1 = new ArrayElementObject("first"); + const foo2 = new ArrayElementObject("second"); + const jsClassResult = exports.roundTripJSClassArray([foo1, foo2]); + assert.equal(jsClassResult.length, 2); + assert.equal(jsClassResult[0].id, foo1.id); + assert.equal(jsClassResult[1].id, foo2.id); + + // Arrays of optional elements + assert.deepEqual(exports.roundTripOptionalIntArray([1, null, 3]), [1, null, 3]); + assert.deepEqual(exports.roundTripOptionalStringArray(["a", null, "b"]), ["a", null, "b"]); + const optJsResult = exports.roundTripOptionalJSObjectArray([jsObj1, null, jsObj2]); + assert.equal(optJsResult.length, 3); + assert.equal(optJsResult[0], jsObj1); + assert.equal(optJsResult[1], null); + assert.equal(optJsResult[2], jsObj2); + const optPoint = { x: 1.0, y: 2.0, label: "", optCount: null, optFlag: null }; + const optPoints = exports.roundTripOptionalStructArray([optPoint, null]); + assert.deepEqual(optPoints[0], optPoint); + assert.equal(optPoints[1], null); + assert.deepEqual(exports.roundTripOptionalCaseEnumArray([Direction.North, null]), [Direction.North, null]); + assert.deepEqual(exports.roundTripOptionalIntRawValueEnumArray([HttpStatus.Ok, null]), [HttpStatus.Ok, null]); + assert.deepEqual(exports.roundTripOptionalJSClassArray([]), []); + const optJsClassResult = exports.roundTripOptionalJSClassArray([foo1, null, foo2]); + assert.equal(optJsClassResult.length, 3); + assert.equal(optJsClassResult[0]?.id, foo1.id); + assert.equal(optJsClassResult[1], null); + assert.equal(optJsClassResult[2]?.id, foo2.id); + + // Nested arrays + assert.deepEqual(exports.roundTripNestedIntArray([[1, 2], [3]]), [[1, 2], [3]]); + assert.deepEqual(exports.roundTripNestedIntArray([[1, 2], [], [3]]), [[1, 2], [], [3]]); + assert.deepEqual(exports.roundTripNestedStringArray([["a", "b"], ["c"]]), [["a", "b"], ["c"]]); + assert.deepEqual(exports.roundTripNestedDoubleArray([[1.5], [2.5]]), [[1.5], [2.5]]); + assert.deepEqual(exports.roundTripNestedBoolArray([[true], [false]]), [[true], [false]]); + const nestedPoint = { x: 1.0, y: 2.0, label: "A", optCount: null, optFlag: null }; + assert.deepEqual(exports.roundTripNestedStructArray([[nestedPoint]])[0][0], nestedPoint); + assert.deepEqual(exports.roundTripNestedCaseEnumArray([[Direction.North], [Direction.South]]), [[Direction.North], [Direction.South]]); + const ng1 = new Greeter("Nested1"); + const ng2 = new Greeter("Nested2"); + const nestedGreeters = exports.roundTripNestedSwiftClassArray([[ng1], [ng2]]); + assert.equal(nestedGreeters[0][0].name, "Nested1"); + assert.equal(nestedGreeters[1][0].greet(), "Hello, Nested2!"); + ng1.release(); ng2.release(); + nestedGreeters.forEach(row => row.forEach(g => g.release())); + + // Multiple array parameters + assert.deepEqual(exports.multiArrayFirst([1, 2, 3], ["a", "b"]), [1, 2, 3]); + assert.deepEqual(exports.multiArraySecond([1, 2, 3], ["a", "b"]), ["a", "b"]); + assert.deepEqual(exports.multiOptionalArrayFirst([10, 20], ["x"]), [10, 20]); + assert.deepEqual(exports.multiOptionalArraySecond([10, 20], ["x"]), ["x"]); + assert.equal(exports.multiOptionalArrayFirst(null, ["y"]), null); + assert.deepEqual(exports.multiOptionalArraySecond(null, ["y"]), ["y"]); + assert.deepEqual(exports.multiOptionalArrayFirst([5], null), [5]); + assert.equal(exports.multiOptionalArraySecond([5], null), null); } \ No newline at end of file diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 4242d8bdb..953c9b93a 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -251,7 +251,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.arrayMembersSum(arrayStruct, [10, 20]), 30); assert.equal(exports.arrayMembersFirst(arrayStruct, ["x", "y"]), "x"); const jsValueArray = [true, 42, "ok", { nested: 1 }, null, undefined]; - assert.deepEqual(exports.roundTripJSValueArray(jsValueArray), jsValueArray); assert.deepEqual(exports.roundTripOptionalJSValueArray(jsValueArray), jsValueArray); assert.equal(exports.roundTripOptionalJSValueArray(null), null); @@ -616,16 +615,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.useConverter(createdConverter, 55), "55"); createdConverter.release(); - const c1 = exports.createConverter(); - const c2 = exports.createConverter(); - const converterArray = exports.roundTripConverterArray([c1, c2]); - assert.equal(converterArray.length, 2); - assert.equal(converterArray[0].toString(10), "10"); - assert.equal(converterArray[1].toString(20), "20"); - c1.release(); - c2.release(); - converterArray.forEach((c) => c.release()); - const uuid = exports.createUUID("11111111-2222-3333-4444-555555555555"); assert.equal(uuid.uuidString(), "11111111-2222-3333-4444-555555555555"); const roundTrippedUUID = exports.roundTripUUID(uuid); @@ -1224,49 +1213,6 @@ function setupTestGlobals(global) { function testArraySupport(exports) { const { Direction, Status, Theme, HttpStatus, Greeter } = exports; - // Primitive arrays - assert.deepEqual(exports.roundTripIntArray([1, 2, 3, -10, 2147483647]), [1, 2, 3, -10, 2147483647]); - assert.deepEqual(exports.roundTripIntArray([]), []); - assert.deepEqual(exports.roundTripStringArray(["Hello", "World", ""]), ["Hello", "World", ""]); - const doubles = exports.roundTripDoubleArray([1.5, 0.0, -1.5, Infinity, NaN]); - assert.equal(doubles[0], 1.5); - assert(Number.isNaN(doubles[4])); - assert.deepEqual(exports.roundTripBoolArray([true, false, true]), [true, false, true]); - - // Enum arrays - assert.deepEqual(exports.roundTripDirectionArray([Direction.North, Direction.South]), [Direction.North, Direction.South]); - assert.deepEqual(exports.roundTripStatusArray([Status.Loading, Status.Success]), [Status.Loading, Status.Success]); - assert.deepEqual(exports.roundTripThemeArray([Theme.Light, Theme.Dark]), [Theme.Light, Theme.Dark]); - assert.deepEqual(exports.roundTripHttpStatusArray([HttpStatus.Ok, HttpStatus.NotFound]), [HttpStatus.Ok, HttpStatus.NotFound]); - - // Struct arrays - const points = [ - { x: 1.0, y: 2.0, label: "A", optCount: 10, optFlag: true }, - { x: 3.0, y: 4.0, label: "B", optCount: null, optFlag: null } - ]; - const pointResult = exports.roundTripDataPointArray(points); - assert.equal(pointResult[0].optCount, 10); - assert.equal(pointResult[1].optCount, null); - - // Class arrays - const g1 = new Greeter("Alice"); - const g2 = new Greeter("Bob"); - const gResult = exports.roundTripGreeterArray([g1, g2]); - assert.equal(gResult[0].name, "Alice"); - assert.equal(gResult[1].greet(), "Hello, Bob!"); - g1.release(); g2.release(); - gResult.forEach(g => g.release()); - - // Arrays of optional elements - assert.deepEqual(exports.roundTripOptionalIntArray([1, null, 3]), [1, null, 3]); - assert.deepEqual(exports.roundTripOptionalStringArray(["a", null, "b"]), ["a", null, "b"]); - const optPoint = { x: 1.0, y: 2.0, label: "", optCount: null, optFlag: null }; - const optPoints = exports.roundTripOptionalDataPointArray([optPoint, null]); - assert.deepEqual(optPoints[0], optPoint); - assert.equal(optPoints[1], null); - assert.deepEqual(exports.roundTripOptionalDirectionArray([Direction.North, null]), [Direction.North, null]); - assert.deepEqual(exports.roundTripOptionalStatusArray([Status.Success, null]), [Status.Success, null]); - // Optional arrays assert.deepEqual(exports.roundTripOptionalIntArrayType([1, 2, 3]), [1, 2, 3]); assert.equal(exports.roundTripOptionalIntArrayType(null), null); @@ -1278,33 +1224,6 @@ function testArraySupport(exports) { assert.equal(exports.roundTripOptionalGreeterArrayType(null), null); og1.release(); optGreeterResult.forEach(g => g.release()); - - // Nested arrays - assert.deepEqual(exports.roundTripNestedIntArray([[1, 2], [3]]), [[1, 2], [3]]); - assert.deepEqual(exports.roundTripNestedIntArray([[1, 2], [], [3]]), [[1, 2], [], [3]]); - assert.deepEqual(exports.roundTripNestedStringArray([["a", "b"], ["c"]]), [["a", "b"], ["c"]]); - assert.deepEqual(exports.roundTripNestedDoubleArray([[1.5], [2.5]]), [[1.5], [2.5]]); - assert.deepEqual(exports.roundTripNestedBoolArray([[true], [false]]), [[true], [false]]); - const nestedPoint = { x: 1.0, y: 2.0, label: "A", optCount: null, optFlag: null }; - assert.deepEqual(exports.roundTripNestedDataPointArray([[nestedPoint]])[0][0], nestedPoint); - assert.deepEqual(exports.roundTripNestedDirectionArray([[Direction.North], [Direction.South]]), [[Direction.North], [Direction.South]]); - const ng1 = new Greeter("Nested1"); - const ng2 = new Greeter("Nested2"); - const nestedGreeters = exports.roundTripNestedGreeterArray([[ng1], [ng2]]); - assert.equal(nestedGreeters[0][0].name, "Nested1"); - assert.equal(nestedGreeters[1][0].greet(), "Hello, Nested2!"); - ng1.release(); ng2.release(); - nestedGreeters.forEach(row => row.forEach(g => g.release())); - - // UnsafePointer-family arrays - const pointerValues = [1, 4, 1024, 65536, 2147483647]; - assert.deepEqual(exports.roundTripUnsafeRawPointerArray(pointerValues), pointerValues); - assert.deepEqual(exports.roundTripUnsafeMutableRawPointerArray(pointerValues), pointerValues); - assert.deepEqual(exports.roundTripOpaquePointerArray(pointerValues), pointerValues); - assert.deepEqual(exports.roundTripUnsafePointerArray(pointerValues), pointerValues); - assert.deepEqual(exports.roundTripUnsafeMutablePointerArray(pointerValues), pointerValues); - assert.deepEqual(exports.roundTripUnsafeRawPointerArray([]), []); - // Default values assert.equal(exports.arrayWithDefault(), 6); assert.equal(exports.arrayWithDefault([10, 20]), 30); @@ -1317,73 +1236,6 @@ function testArraySupport(exports) { assert.equal(exports.arrayMixedDefaults("Val", [100], "?"), "Val: 100?"); assert.equal(exports.arrayMixedDefaults(undefined, [5, 5]), "Sum: 10!"); assert.equal(exports.arrayMixedDefaults(undefined, undefined, "?"), "Sum: 30?"); - - const helper1 = new exports.Greeter("Helper1"); - const jsProcessor1 = { - count: 1, name: "Processor1", optionalTag: null, optionalCount: null, - direction: null, optionalTheme: null, httpStatus: null, apiResult: null, - helper: helper1, optionalHelper: null, - increment(by) { this.count += by; }, - getValue() { return this.count; }, - setLabelElements(a, b) { }, getLabel() { return ""; }, - isEven() { return this.count % 2 === 0; }, - processGreeter(g) { return ""; }, createGreeter() { return new exports.Greeter("P1"); }, - processOptionalGreeter(g) { return ""; }, createOptionalGreeter() { return null; }, - handleAPIResult(r) { }, getAPIResult() { return null; } - }; - - const consumeResult = exports.consumeDataProcessorArrayType([jsProcessor1]); - assert.equal(consumeResult, 1); - - const processors = [jsProcessor1]; - const result = exports.roundTripDataProcessorArrayType(processors); - - assert.equal(result.length, 1); - assert.equal(result[0], jsProcessor1); - assert.equal(result[0].count, 1); - - helper1.release(); - - // JSObject arrays - const jsObj1 = { a: 1, b: "hello" }; - const jsObj2 = { x: [1, 2, 3], y: { nested: true } }; - const jsObjResult = exports.roundTripJSObjectArray([jsObj1, jsObj2]); - assert.equal(jsObjResult.length, 2); - assert.equal(jsObjResult[0], jsObj1); - assert.equal(jsObjResult[1], jsObj2); - assert.deepEqual(exports.roundTripJSObjectArray([]), []); - - const optJsResult = exports.roundTripOptionalJSObjectArray([jsObj1, null, jsObj2]); - assert.equal(optJsResult.length, 3); - assert.equal(optJsResult[0], jsObj1); - assert.equal(optJsResult[1], null); - assert.equal(optJsResult[2], jsObj2); - - // @JSClass struct arrays - const foo1 = new ImportedFoo("first"); - const foo2 = new ImportedFoo("second"); - const fooResult = exports.roundTripFooArray([foo1, foo2]); - assert.equal(fooResult.length, 2); - assert.equal(fooResult[0].value, "first"); - assert.equal(fooResult[1].value, "second"); - assert.deepEqual(exports.roundTripFooArray([]), []); - - const optFooResult = exports.roundTripOptionalFooArray([foo1, null, foo2]); - assert.equal(optFooResult.length, 3); - assert.equal(optFooResult[0].value, "first"); - assert.equal(optFooResult[1], null); - assert.equal(optFooResult[2].value, "second"); - - // Multiple stack-based parameters (regression test for LIFO ordering) - assert.deepEqual(exports.multiArrayFirstNums([1, 2, 3], ["a", "b"]), [1, 2, 3]); - assert.deepEqual(exports.multiArrayFirstStrs([1, 2, 3], ["a", "b"]), ["a", "b"]); - - assert.deepEqual(exports.multiOptionalArrayFirstA([10, 20], ["x"]), [10, 20]); - assert.deepEqual(exports.multiOptionalArrayFirstB([10, 20], ["x"]), ["x"]); - assert.equal(exports.multiOptionalArrayFirstA(null, ["y"]), null); - assert.deepEqual(exports.multiOptionalArrayFirstB(null, ["y"]), ["y"]); - assert.deepEqual(exports.multiOptionalArrayFirstA([5], null), [5]); - assert.equal(exports.multiOptionalArrayFirstB([5], null), null); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ From f08fec78e28a93f50958a45598a5f1989c3404cf Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Fri, 27 Feb 2026 13:01:18 +0900 Subject: [PATCH 005/140] [NFC] BridgeJS: Move out default argument tests into a separate suite (#679) BridgeJS: Move out default argument tests into a separate suite --- .../DefaultArgumentTests.swift | 131 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 95 - .../Generated/BridgeJS.swift | 637 +- .../Generated/JavaScript/BridgeJS.json | 6113 +++++++++-------- .../JavaScript/DefaultArgumentTests.mjs | 97 + Tests/prelude.mjs | 91 +- 6 files changed, 3782 insertions(+), 3382 deletions(-) create mode 100644 Tests/BridgeJSRuntimeTests/DefaultArgumentTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs diff --git a/Tests/BridgeJSRuntimeTests/DefaultArgumentTests.swift b/Tests/BridgeJSRuntimeTests/DefaultArgumentTests.swift new file mode 100644 index 000000000..061dc5709 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/DefaultArgumentTests.swift @@ -0,0 +1,131 @@ +import XCTest +import JavaScriptKit + +@JSClass struct DefaultArgumentImports { + @JSFunction static func runJsDefaultArgumentTests() throws(JSException) +} + +final class DefaultArgumentTests: XCTestCase { + func testRunJsDefaultArgumentTests() throws { + try DefaultArgumentImports.runJsDefaultArgumentTests() + } +} + +// MARK: - Default Parameters + +@JS enum DefaultArgumentExports { + @JS static func testStringDefault(message: String = "Hello World") -> String { + return message + } + + @JS static func testIntDefault(count: Int = 42) -> Int { + return count + } + + @JS static func testBoolDefault(flag: Bool = true) -> Bool { + return flag + } + + @JS static func testOptionalDefault(name: String? = nil) -> String? { + return name + } + + @JS static func testMultipleDefaults( + title: String = "Default Title", + count: Int = -10, + enabled: Bool = false + ) -> String { + return "\(title): \(count) (\(enabled))" + } + + @JS static func testSimpleEnumDefault(status: Status = .success) -> Status { + return status + } + + @JS static func testDirectionDefault(direction: Direction = .north) -> Direction { + return direction + } + + @JS static func testRawStringEnumDefault(theme: Theme = .light) -> Theme { + return theme + } + + @JS static func testComplexInit(greeter: Greeter = Greeter(name: "DefaultGreeter")) -> String { + return greeter.greet() + } + + @JS static func testEmptyInit(_ object: StaticPropertyHolder = StaticPropertyHolder()) -> StaticPropertyHolder { + return object + } + + @JS static func createConstructorDefaults( + name: String = "Default", + count: Int = 42, + enabled: Bool = true, + status: Status = .success, + tag: String? = nil + ) -> DefaultArgumentConstructorDefaults { + return DefaultArgumentConstructorDefaults( + name: name, + count: count, + enabled: enabled, + status: status, + tag: tag + ) + } + + @JS static func describeConstructorDefaults( + _ value: DefaultArgumentConstructorDefaults + ) -> String { + return value.describe() + } + + @JS static func arrayWithDefault(_ values: [Int] = [1, 2, 3]) -> Int { + return values.reduce(0, +) + } + + @JS static func arrayWithOptionalDefault(_ values: [Int]? = nil) -> Int { + return values?.reduce(0, +) ?? -1 + } + + @JS static func arrayMixedDefaults( + prefix: String = "Sum", + values: [Int] = [10, 20], + suffix: String = "!" + ) -> String { + return "\(prefix): \(values.reduce(0, +))\(suffix)" + } +} + +@JS class DefaultArgumentConstructorDefaults { + @JS var name: String + @JS var count: Int + @JS var enabled: Bool + @JS var status: Status + @JS var tag: String? + + @JS init( + name: String = "Default", + count: Int = 42, + enabled: Bool = true, + status: Status = .success, + tag: String? = nil + ) { + self.name = name + self.count = count + self.enabled = enabled + self.status = status + self.tag = tag + } + + @JS func describe() -> String { + let tagStr = tag ?? "nil" + let statusStr: String + switch status { + case .loading: statusStr = "loading" + case .success: statusStr = "success" + case .error: statusStr = "error" + } + return "\(name):\(count):\(enabled):\(statusStr):\(tagStr)" + } +} diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index ead7e0841..cfc1b47b5 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -769,101 +769,6 @@ enum GraphOperations { } } -// MARK: - Default Parameters - -@JS func testStringDefault(message: String = "Hello World") -> String { - return message -} - -@JS func testIntDefault(count: Int = 42) -> Int { - return count -} - -@JS func testBoolDefault(flag: Bool = true) -> Bool { - return flag -} - -@JS func testOptionalDefault(name: String? = nil) -> String? { - return name -} - -@JS func testMultipleDefaults( - title: String = "Default Title", - count: Int = -10, - enabled: Bool = false -) -> String { - return "\(title): \(count) (\(enabled))" -} - -@JS func testSimpleEnumDefault(status: Status = .success) -> Status { - return status -} - -@JS func testDirectionDefault(direction: Direction = .north) -> Direction { - return direction -} - -@JS func testRawStringEnumDefault(theme: Theme = .light) -> Theme { - return theme -} - -@JS func testComplexInit(greeter: Greeter = Greeter(name: "DefaultGreeter")) -> String { - return greeter.greet() -} - -@JS func testEmptyInit(_ object: StaticPropertyHolder = StaticPropertyHolder()) -> StaticPropertyHolder { - return object -} - -@JS class ConstructorDefaults { - @JS var name: String - @JS var count: Int - @JS var enabled: Bool - @JS var status: Status - @JS var tag: String? - - @JS init( - name: String = "Default", - count: Int = 42, - enabled: Bool = true, - status: Status = .success, - tag: String? = nil - ) { - self.name = name - self.count = count - self.enabled = enabled - self.status = status - self.tag = tag - } - - @JS func describe() -> String { - let tagStr = tag ?? "nil" - let statusStr: String - switch status { - case .loading: statusStr = "loading" - case .success: statusStr = "success" - case .error: statusStr = "error" - } - return "\(name):\(count):\(enabled):\(statusStr):\(tagStr)" - } -} - -@JS func arrayWithDefault(_ values: [Int] = [1, 2, 3]) -> Int { - return values.reduce(0, +) -} - -@JS func arrayWithOptionalDefault(_ values: [Int]? = nil) -> Int { - return values?.reduce(0, +) ?? -1 -} - -@JS func arrayMixedDefaults( - prefix: String = "Sum", - values: [Int] = [10, 20], - suffix: String = "!" -) -> String { - return "\(prefix): \(values.reduce(0, +))\(suffix)" -} - // MARK: - Static Properties @JS class StaticPropertyHolder { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 96731a282..34637a322 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -2687,6 +2687,171 @@ public func _bjs_ArraySupportExports_static_multiOptionalArraySecond() -> Void { #endif } +@_expose(wasm, "bjs_DefaultArgumentExports_static_testStringDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") +public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testIntDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testIntDefault") +public func _bjs_DefaultArgumentExports_static_testIntDefault(_ count: Int32) -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.testIntDefault(count: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testBoolDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testBoolDefault") +public func _bjs_DefaultArgumentExports_static_testBoolDefault(_ flag: Int32) -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testOptionalDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testOptionalDefault") +public func _bjs_DefaultArgumentExports_static_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testMultipleDefaults") +@_cdecl("bjs_DefaultArgumentExports_static_testMultipleDefaults") +public func _bjs_DefaultArgumentExports_static_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testSimpleEnumDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testSimpleEnumDefault") +public func _bjs_DefaultArgumentExports_static_testSimpleEnumDefault(_ status: Int32) -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testDirectionDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testDirectionDefault") +public func _bjs_DefaultArgumentExports_static_testDirectionDefault(_ direction: Int32) -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testRawStringEnumDefault") +@_cdecl("bjs_DefaultArgumentExports_static_testRawStringEnumDefault") +public func _bjs_DefaultArgumentExports_static_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + 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 @@ -5873,149 +6038,6 @@ public func _bjs_getObserverStats() -> Void { #endif } -@_expose(wasm, "bjs_testStringDefault") -@_cdecl("bjs_testStringDefault") -public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { - #if arch(wasm32) - let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testIntDefault") -@_cdecl("bjs_testIntDefault") -public func _bjs_testIntDefault(_ count: Int32) -> Int32 { - #if arch(wasm32) - let ret = testIntDefault(count: Int.bridgeJSLiftParameter(count)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testBoolDefault") -@_cdecl("bjs_testBoolDefault") -public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { - #if arch(wasm32) - let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testOptionalDefault") -@_cdecl("bjs_testOptionalDefault") -public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testMultipleDefaults") -@_cdecl("bjs_testMultipleDefaults") -public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { - #if arch(wasm32) - let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testSimpleEnumDefault") -@_cdecl("bjs_testSimpleEnumDefault") -public func _bjs_testSimpleEnumDefault(_ status: Int32) -> Int32 { - #if arch(wasm32) - let ret = testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testDirectionDefault") -@_cdecl("bjs_testDirectionDefault") -public func _bjs_testDirectionDefault(_ direction: Int32) -> Int32 { - #if arch(wasm32) - let ret = testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testRawStringEnumDefault") -@_cdecl("bjs_testRawStringEnumDefault") -public func _bjs_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { - #if arch(wasm32) - let ret = testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testComplexInit") -@_cdecl("bjs_testComplexInit") -public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testEmptyInit") -@_cdecl("bjs_testEmptyInit") -public func _bjs_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_arrayWithDefault") -@_cdecl("bjs_arrayWithDefault") -public func _bjs_arrayWithDefault() -> Int32 { - #if arch(wasm32) - let ret = arrayWithDefault(_: [Int].bridgeJSStackPop()) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_arrayWithOptionalDefault") -@_cdecl("bjs_arrayWithOptionalDefault") -public func _bjs_arrayWithOptionalDefault() -> Int32 { - #if arch(wasm32) - let ret = arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_arrayMixedDefaults") -@_cdecl("bjs_arrayMixedDefaults") -public func _bjs_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { - #if arch(wasm32) - let ret = arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) - 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 { @@ -6711,6 +6733,161 @@ fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutable return _bjs_ClosureSupportExports_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 { + #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)) + 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 { + #if arch(wasm32) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).describe() + 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 { + #if arch(wasm32) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #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 { + #if arch(wasm32) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 +} + +@_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 = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled + return ret.bridgeJSLowerReturn() + #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 { + #if arch(wasm32) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) + #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 { + #if arch(wasm32) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status + 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 { + #if arch(wasm32) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) + #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 { + #if arch(wasm32) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag + 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 { + #if arch(wasm32) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_deinit") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_deinit") +public func _bjs_DefaultArgumentConstructorDefaults_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension DefaultArgumentConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_DefaultArgumentConstructorDefaults_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 +#else +fileprivate func _bjs_DefaultArgumentConstructorDefaults_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) +} + @_expose(wasm, "bjs_Greeter_init") @_cdecl("bjs_Greeter_init") public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { @@ -7615,161 +7792,6 @@ fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) return _bjs_MathUtils_wrap_extern(pointer) } -@_expose(wasm, "bjs_ConstructorDefaults_init") -@_cdecl("bjs_ConstructorDefaults_init") -public func _bjs_ConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = ConstructorDefaults(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_ConstructorDefaults_describe") -@_cdecl("bjs_ConstructorDefaults_describe") -public func _bjs_ConstructorDefaults_describe(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).describe() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_name_get") -@_cdecl("bjs_ConstructorDefaults_name_get") -public func _bjs_ConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).name - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_name_set") -@_cdecl("bjs_ConstructorDefaults_name_set") -public func _bjs_ConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_count_get") -@_cdecl("bjs_ConstructorDefaults_count_get") -public func _bjs_ConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).count - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_count_set") -@_cdecl("bjs_ConstructorDefaults_count_set") -public func _bjs_ConstructorDefaults_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_enabled_get") -@_cdecl("bjs_ConstructorDefaults_enabled_get") -public func _bjs_ConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).enabled - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_enabled_set") -@_cdecl("bjs_ConstructorDefaults_enabled_set") -public func _bjs_ConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_status_get") -@_cdecl("bjs_ConstructorDefaults_status_get") -public func _bjs_ConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).status - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_status_set") -@_cdecl("bjs_ConstructorDefaults_status_set") -public func _bjs_ConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_tag_get") -@_cdecl("bjs_ConstructorDefaults_tag_get") -public func _bjs_ConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).tag - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_tag_set") -@_cdecl("bjs_ConstructorDefaults_tag_set") -public func _bjs_ConstructorDefaults_tag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_ConstructorDefaults_deinit") -@_cdecl("bjs_ConstructorDefaults_deinit") -public func _bjs_ConstructorDefaults_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension ConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_ConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ConstructorDefaults_wrap") -fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_ConstructorDefaults_wrap_extern(pointer) -} - @_expose(wasm, "bjs_StaticPropertyHolder_init") @_cdecl("bjs_StaticPropertyHolder_init") public func _bjs_StaticPropertyHolder_init() -> UnsafeMutableRawPointer { @@ -10005,6 +10027,25 @@ func _$ClosureSupportImports_runJsClosureSupportTests() throws(JSException) -> V } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static") +fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() -> Void +#else +fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static() -> Void { + return bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() +} + +func _$DefaultArgumentImports_runJsDefaultArgumentTests() throws(JSException) -> Void { + bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionary") fileprivate func bjs_jsRoundTripDictionary_extern() -> Void diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 1a090993b..74ecd9d50 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -298,6 +298,172 @@ ], "swiftCallName" : "ClosureSupportExports" }, + { + "constructor" : { + "abiName" : "bjs_DefaultArgumentConstructorDefaults_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Default" + } + }, + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + + } + } + }, + { + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "success" + } + }, + "label" : "status", + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "defaultValue" : { + "null" : { + + } + }, + "label" : "tag", + "name" : "tag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_DefaultArgumentConstructorDefaults_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "DefaultArgumentConstructorDefaults", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "enabled", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "tag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "DefaultArgumentConstructorDefaults" + }, { "constructor" : { "abiName" : "bjs_Greeter_init", @@ -1260,213 +1426,47 @@ }, { "constructor" : { - "abiName" : "bjs_ConstructorDefaults_init", + "abiName" : "bjs_StaticPropertyHolder_init", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Default" - } - }, - "label" : "name", - "name" : "name", - "type" : { - "string" : { - } - } - }, - { - "defaultValue" : { - "int" : { - "_0" : 42 - } - }, - "label" : "count", - "name" : "count", - "type" : { - "int" : { + ] + }, + "methods" : [ - } + ], + "name" : "StaticPropertyHolder", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "staticConstant", + "staticContext" : { + "className" : { + "_0" : "StaticPropertyHolder" } }, - { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "enabled", - "name" : "enabled", - "type" : { - "bool" : { + "type" : { + "string" : { - } } - }, - { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "success" - } - }, - "label" : "status", - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "staticVariable", + "staticContext" : { + "className" : { + "_0" : "StaticPropertyHolder" } }, - { - "defaultValue" : { - "null" : { - - } - }, - "label" : "tag", - "name" : "tag", - "type" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_ConstructorDefaults_describe", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "describe", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "ConstructorDefaults", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "count", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "enabled", - "type" : { - "bool" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "tag", - "type" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" - } - } - } - ], - "swiftCallName" : "ConstructorDefaults" - }, - { - "constructor" : { - "abiName" : "bjs_StaticPropertyHolder_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "StaticPropertyHolder", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "staticConstant", - "staticContext" : { - "className" : { - "_0" : "StaticPropertyHolder" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "staticVariable", - "staticContext" : { - "className" : { - "_0" : "StaticPropertyHolder" - } - }, - "type" : { - "int" : { + "type" : { + "int" : { } } @@ -5575,780 +5575,742 @@ }, { "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } ], "emitStyle" : "const", - "name" : "Direction", + "name" : "DefaultArgumentExports", "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testStringDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testStringDefault", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "loading" - }, - { - "associatedValues" : [ + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Hello World" + } + }, + "label" : "message", + "name" : "message", + "type" : { + "string" : { + } + } + } ], - "name" : "success" + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testIntDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testIntDefault", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "error" - } - ], - "emitStyle" : "const", - "name" : "Status", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Status", - "tsFullPath" : "Status" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ + { + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + } + } + } ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ + "returnType" : { + "int" : { - ], - "name" : "dark", - "rawValue" : "dark" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "const", - "name" : "Theme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Theme", - "tsFullPath" : "Theme" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "ok", - "rawValue" : "200" - }, - { - "associatedValues" : [ - - ], - "name" : "notFound", - "rawValue" : "404" - }, - { - "associatedValues" : [ - - ], - "name" : "serverError", - "rawValue" : "500" - }, - { - "associatedValues" : [ - - ], - "name" : "unknown", - "rawValue" : "-1" - } - ], - "emitStyle" : "const", - "name" : "HttpStatus", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "HttpStatus", - "tsFullPath" : "HttpStatus" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "rough", - "rawValue" : "0.1" - }, - { - "associatedValues" : [ - - ], - "name" : "normal", - "rawValue" : "0.01" - }, - { - "associatedValues" : [ - - ], - "name" : "fine", - "rawValue" : "0.001" - } - ], - "emitStyle" : "const", - "name" : "Precision", - "rawType" : "Float", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Precision", - "tsFullPath" : "Precision" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "quarter", - "rawValue" : "0.25" - }, - { - "associatedValues" : [ - - ], - "name" : "half", - "rawValue" : "0.5" - }, - { - "associatedValues" : [ - - ], - "name" : "golden", - "rawValue" : "1.618" - } - ], - "emitStyle" : "const", - "name" : "Ratio", - "rawType" : "Double", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Ratio", - "tsFullPath" : "Ratio" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSDirection", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSDirection", - "tsFullPath" : "TSDirection" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ - - ], - "name" : "dark", - "rawValue" : "dark" - }, - { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSTheme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSTheme", - "tsFullPath" : "TSTheme" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "StringUtils", - "namespace" : [ - "Utils" - ], - "staticMethods" : [ - { - "abiName" : "bjs_Utils_StringUtils_static_uppercase", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "uppercase", - "namespace" : [ - "Utils", - "StringUtils" + "abiName" : "bjs_DefaultArgumentExports_static_testBoolDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testBoolDefault", + "namespace" : [ + "DefaultArgumentExports" ], "parameters" : [ { - "label" : "_", - "name" : "text", + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "flag", + "name" : "flag", "type" : { - "string" : { + "bool" : { } } } ], "returnType" : { - "string" : { + "bool" : { } }, "staticContext" : { "namespaceEnum" : { - "_0" : "Utils.StringUtils" + "_0" : "DefaultArgumentExports" } } }, { - "abiName" : "bjs_Utils_StringUtils_static_lowercase", + "abiName" : "bjs_DefaultArgumentExports_static_testOptionalDefault", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "lowercase", + "name" : "testOptionalDefault", "namespace" : [ - "Utils", - "StringUtils" + "DefaultArgumentExports" ], "parameters" : [ { - "label" : "_", - "name" : "text", - "type" : { - "string" : { + "defaultValue" : { + "null" : { + + } + }, + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" } }, "staticContext" : { "namespaceEnum" : { - "_0" : "Utils.StringUtils" + "_0" : "DefaultArgumentExports" } } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils.StringUtils", - "tsFullPath" : "Utils.StringUtils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Networking", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking", - "tsFullPath" : "Networking" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "API", - "namespace" : [ - "Networking" - ], - "staticMethods" : [ + }, + { + "abiName" : "bjs_DefaultArgumentExports_static_testMultipleDefaults", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testMultipleDefaults", + "namespace" : [ + "DefaultArgumentExports" + ], + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Default Title" + } + }, + "label" : "title", + "name" : "title", + "type" : { + "string" : { - ], - "staticProperties" : [ + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : -10 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { - ], - "swiftCallName" : "Networking.API", - "tsFullPath" : "Networking.API" - }, - { - "cases" : [ - { - "associatedValues" : [ + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : false + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + } + } + } ], - "name" : "get" - }, - { - "associatedValues" : [ + "returnType" : { + "string" : { - ], - "name" : "post" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testSimpleEnumDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testSimpleEnumDefault", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "put" + "parameters" : [ + { + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "success" + } + }, + "label" : "status", + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testDirectionDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testDirectionDefault", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "delete" - } - ], - "emitStyle" : "const", - "name" : "Method", - "namespace" : [ - "Networking", - "API" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API.Method", - "tsFullPath" : "Networking.API.Method" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Configuration", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration", - "tsFullPath" : "Configuration" - }, - { - "cases" : [ - { - "associatedValues" : [ - + "parameters" : [ + { + "defaultValue" : { + "enumCase" : { + "_0" : "Direction", + "_1" : "north" + } + }, + "label" : "direction", + "name" : "direction", + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } ], - "name" : "debug", - "rawValue" : "debug" + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testRawStringEnumDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testRawStringEnumDefault", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "info", - "rawValue" : "info" + "parameters" : [ + { + "defaultValue" : { + "enumCase" : { + "_0" : "Theme", + "_1" : "light" + } + }, + "label" : "theme", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - - ], - "name" : "warning", - "rawValue" : "warning" - }, - { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testComplexInit", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testComplexInit", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "error", - "rawValue" : "error" - } - ], - "emitStyle" : "const", - "name" : "LogLevel", - "namespace" : [ - "Configuration" - ], - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.LogLevel", - "tsFullPath" : "Configuration.LogLevel" - }, - { - "cases" : [ - { - "associatedValues" : [ - + "parameters" : [ + { + "defaultValue" : { + "objectWithArguments" : { + "_0" : "Greeter", + "_1" : [ + { + "string" : { + "_0" : "DefaultGreeter" + } + } + ] + } + }, + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], - "name" : "http", - "rawValue" : "80" - }, - { - "associatedValues" : [ + "returnType" : { + "string" : { - ], - "name" : "https", - "rawValue" : "443" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_testEmptyInit", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "testEmptyInit", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "development", - "rawValue" : "3000" - } - ], - "emitStyle" : "const", - "name" : "Port", - "namespace" : [ - "Configuration" - ], - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.Port", - "tsFullPath" : "Configuration.Port" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Internal", - "namespace" : [ - "Networking", - "APIV2" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal", - "tsFullPath" : "Networking.APIV2.Internal" - }, - { - "cases" : [ - { - "associatedValues" : [ - + "parameters" : [ + { + "defaultValue" : { + "object" : { + "_0" : "StaticPropertyHolder" + } + }, + "label" : "_", + "name" : "object", + "type" : { + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" + } + } + } ], - "name" : "get" + "returnType" : { + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_createConstructorDefaults", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createConstructorDefaults", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "post" - } - ], - "emitStyle" : "const", - "name" : "SupportedMethod", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal.SupportedMethod", - "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ { + "defaultValue" : { + "string" : { + "_0" : "Default" + } + }, + "label" : "name", + "name" : "name", "type" : { "string" : { } } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ + }, { + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", "type" : { "int" : { } } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ + }, { + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "enabled", + "name" : "enabled", "type" : { "bool" : { } } - } - ], - "name" : "flag" - }, - { - "associatedValues" : [ + }, { + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "success" + } + }, + "label" : "status", + "name" : "status", "type" : { - "float" : { - + "caseEnum" : { + "_0" : "Status" } } - } - ], - "name" : "rate" - }, - { - "associatedValues" : [ + }, { + "defaultValue" : { + "null" : { + + } + }, + "label" : "tag", + "name" : "tag", "type" : { - "double" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" } } } ], - "name" : "precise" + "returnType" : { + "swiftHeapObject" : { + "_0" : "DefaultArgumentConstructorDefaults" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_DefaultArgumentExports_static_describeConstructorDefaults", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "describeConstructorDefaults", + "namespace" : [ + "DefaultArgumentExports" ], - "name" : "info" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ { + "label" : "_", + "name" : "value", "type" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "DefaultArgumentConstructorDefaults" } } } ], - "name" : "success" + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_DefaultArgumentExports_static_arrayWithDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "arrayWithDefault", + "namespace" : [ + "DefaultArgumentExports" + ], + "parameters" : [ { - "type" : { - "string" : { - + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 1 + } + }, + { + "int" : { + "_0" : 2 + } + }, + { + "int" : { + "_0" : 3 + } + } + ] } - } - }, - { + }, + "label" : "_", + "name" : "values", "type" : { - "int" : { + "array" : { + "_0" : { + "int" : { + } + } } } } ], - "name" : "error" + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ - { - "type" : { - "double" : { - - } - } - }, + "abiName" : "bjs_DefaultArgumentExports_static_arrayWithOptionalDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "arrayWithOptionalDefault", + "namespace" : [ + "DefaultArgumentExports" + ], + "parameters" : [ { - "type" : { - "double" : { + "defaultValue" : { + "null" : { } - } - }, - { + }, + "label" : "_", + "name" : "values", "type" : { - "string" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" } } } ], - "name" : "location" + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_DefaultArgumentExports_static_arrayMixedDefaults", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "arrayMixedDefaults", + "namespace" : [ + "DefaultArgumentExports" + ], + "parameters" : [ { + "defaultValue" : { + "string" : { + "_0" : "Sum" + } + }, + "label" : "prefix", + "name" : "prefix", "type" : { - "bool" : { + "string" : { } } }, { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 10 + } + }, + { + "int" : { + "_0" : 20 + } + } + ] + } + }, + "label" : "values", + "name" : "values", "type" : { - "int" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { + "defaultValue" : { + "string" : { + "_0" : "!" + } + }, + "label" : "suffix", + "name" : "suffix", "type" : { "string" : { @@ -6356,544 +6318,360 @@ } } ], - "name" : "status" - }, + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "DefaultArgumentExports" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "DefaultArgumentExports", + "tsFullPath" : "DefaultArgumentExports" + }, + { + "cases" : [ { "associatedValues" : [ - { - "type" : { - "double" : { - } - } - }, - { - "type" : { - "double" : { + ], + "name" : "north" + }, + { + "associatedValues" : [ - } - } - }, - { - "type" : { - "double" : { + ], + "name" : "south" + }, + { + "associatedValues" : [ - } - } - } ], - "name" : "coordinates" + "name" : "east" }, { "associatedValues" : [ - { - "type" : { - "bool" : { - } - } - }, - { - "type" : { - "bool" : { + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "Direction", + "staticMethods" : [ - } - } - }, - { - "type" : { - "int" : { + ], + "staticProperties" : [ - } - } - }, - { - "type" : { - "int" : { + ], + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" + }, + { + "cases" : [ + { + "associatedValues" : [ - } - } - }, - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "string" : { + ], + "name" : "loading" + }, + { + "associatedValues" : [ - } - } - } ], - "name" : "comprehensive" + "name" : "success" }, { "associatedValues" : [ ], - "name" : "info" + "name" : "error" } ], "emitStyle" : "const", - "name" : "ComplexResult", + "name" : "Status", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "ComplexResult", - "tsFullPath" : "ComplexResult" + "swiftCallName" : "Status", + "tsFullPath" : "Status" }, { "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light", + "rawValue" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark", + "rawValue" : "dark" + }, + { + "associatedValues" : [ + ], + "name" : "auto", + "rawValue" : "auto" + } ], "emitStyle" : "const", - "name" : "Utilities", + "name" : "Theme", + "rawType" : "String", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "Utilities", - "tsFullPath" : "Utilities" + "swiftCallName" : "Theme", + "tsFullPath" : "Theme" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - } ], - "name" : "success" + "name" : "ok", + "rawValue" : "200" }, { "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "int" : { - } - } - } ], - "name" : "failure" + "name" : "notFound", + "rawValue" : "404" }, { "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "int" : { - } - } - }, - { - "type" : { - "string" : { + ], + "name" : "serverError", + "rawValue" : "500" + }, + { + "associatedValues" : [ - } - } - } ], - "name" : "status" + "name" : "unknown", + "rawValue" : "-1" } ], "emitStyle" : "const", - "name" : "Result", - "namespace" : [ - "Utilities" - ], + "name" : "HttpStatus", + "rawType" : "Int", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "Utilities.Result", - "tsFullPath" : "Utilities.Result" + "swiftCallName" : "HttpStatus", + "tsFullPath" : "HttpStatus" }, { "cases" : [ + { + "associatedValues" : [ + ], + "name" : "rough", + "rawValue" : "0.1" + }, + { + "associatedValues" : [ + + ], + "name" : "normal", + "rawValue" : "0.01" + }, + { + "associatedValues" : [ + + ], + "name" : "fine", + "rawValue" : "0.001" + } ], "emitStyle" : "const", - "name" : "API", + "name" : "Precision", + "rawType" : "Float", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "API", - "tsFullPath" : "API" + "swiftCallName" : "Precision", + "tsFullPath" : "Precision" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - } ], - "name" : "success" + "name" : "quarter", + "rawValue" : "0.25" }, { "associatedValues" : [ - { - "type" : { - "string" : { - } - } - }, - { - "type" : { - "int" : { + ], + "name" : "half", + "rawValue" : "0.5" + }, + { + "associatedValues" : [ - } - } - } ], - "name" : "failure" + "name" : "golden", + "rawValue" : "1.618" } ], "emitStyle" : "const", - "name" : "NetworkingResult", - "namespace" : [ - "API" - ], + "name" : "Ratio", + "rawType" : "Double", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "API.NetworkingResult", - "tsFullPath" : "API.NetworkingResult" + "swiftCallName" : "Ratio", + "tsFullPath" : "Ratio" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "swiftStruct" : { - "_0" : "Address" - } - } - } - ], - "name" : "structPayload" - }, - { - "associatedValues" : [ - { - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } + ], - "name" : "classPayload" + "name" : "north" }, { "associatedValues" : [ - { - "type" : { - "jsObject" : { - } - } - } ], - "name" : "jsObjectPayload" + "name" : "south" }, { "associatedValues" : [ - { - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } + ], - "name" : "nestedEnum" - }, - { - "associatedValues" : [ - { - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "name" : "arrayPayload" - }, - { - "associatedValues" : [ - { - "type" : { - "jsObject" : { - "_0" : "Foo" - } - } - } - ], - "name" : "jsClassPayload" + "name" : "east" }, { "associatedValues" : [ ], - "name" : "empty" + "name" : "west" } ], - "emitStyle" : "const", - "name" : "AllTypesResult", + "emitStyle" : "tsEnum", + "name" : "TSDirection", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "AllTypesResult", - "tsFullPath" : "AllTypesResult" + "swiftCallName" : "TSDirection", + "tsFullPath" : "TSDirection" }, { "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - ], - "name" : "precision" - }, - { - "associatedValues" : [ - { - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - ], - "name" : "direction" - }, - { - "associatedValues" : [ - { - "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - }, - "_1" : "null" - } - } - } - ], - "name" : "optPrecision" - }, - { - "associatedValues" : [ - { - "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" - } - } - } - ], - "name" : "optDirection" - }, { "associatedValues" : [ ], - "name" : "empty" - } - ], - "emitStyle" : "const", - "name" : "TypedPayloadResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TypedPayloadResult", - "tsFullPath" : "TypedPayloadResult" - }, - { - "cases" : [ + "name" : "light", + "rawValue" : "light" + }, { "associatedValues" : [ ], - "name" : "scientific" + "name" : "dark", + "rawValue" : "dark" }, { "associatedValues" : [ ], - "name" : "basic" + "name" : "auto", + "rawValue" : "auto" } ], - "emitStyle" : "const", - "name" : "StaticCalculator", + "emitStyle" : "tsEnum", + "name" : "TSTheme", + "rawType" : "String", "staticMethods" : [ - { - "abiName" : "bjs_StaticCalculator_static_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - } - }, - "staticContext" : { - "enumName" : { - "_0" : "StaticCalculator" - } - } - } ], "staticProperties" : [ ], - "swiftCallName" : "StaticCalculator", - "tsFullPath" : "StaticCalculator" + "swiftCallName" : "TSTheme", + "tsFullPath" : "TSTheme" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "StaticUtils", + "name" : "Utils", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "StaticUtils", - "tsFullPath" : "StaticUtils" + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "Nested", + "name" : "StringUtils", "namespace" : [ - "StaticUtils" + "Utils" ], "staticMethods" : [ { - "abiName" : "bjs_StaticUtils_Nested_static_roundtrip", + "abiName" : "bjs_Utils_StringUtils_static_uppercase", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "roundtrip", + "name" : "uppercase", "namespace" : [ - "StaticUtils", - "Nested" + "Utils", + "StringUtils" ], "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "text", "type" : { "string" : { @@ -6908,95 +6686,41 @@ }, "staticContext" : { "namespaceEnum" : { - "_0" : "StaticUtils.Nested" - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "StaticUtils.Nested", - "tsFullPath" : "StaticUtils.Nested" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "GraphOperations", - "namespace" : [ - "Services", - "Graph" - ], - "staticMethods" : [ - { - "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "createGraph", - "namespace" : [ - "Services", - "Graph", - "GraphOperations" - ], - "parameters" : [ - { - "label" : "rootId", - "name" : "rootId", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "namespaceEnum" : { - "_0" : "GraphOperations" + "_0" : "Utils.StringUtils" } } }, { - "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "abiName" : "bjs_Utils_StringUtils_static_lowercase", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "nodeCount", + "name" : "lowercase", "namespace" : [ - "Services", - "Graph", - "GraphOperations" + "Utils", + "StringUtils" ], "parameters" : [ { - "label" : "graphId", - "name" : "graphId", + "label" : "_", + "name" : "text", "type" : { - "int" : { + "string" : { } } } ], "returnType" : { - "int" : { + "string" : { } }, "staticContext" : { "namespaceEnum" : { - "_0" : "GraphOperations" + "_0" : "Utils.StringUtils" } } } @@ -7004,373 +6728,313 @@ "staticProperties" : [ ], - "swiftCallName" : "GraphOperations", - "tsFullPath" : "Services.Graph.GraphOperations" + "swiftCallName" : "Utils.StringUtils", + "tsFullPath" : "Utils.StringUtils" }, { "cases" : [ - { - "associatedValues" : [ - ], - "name" : "option1" - }, - { - "associatedValues" : [ - - ], - "name" : "option2" - } ], "emitStyle" : "const", - "name" : "StaticPropertyEnum", + "name" : "Networking", "staticMethods" : [ ], "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumProperty", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "string" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "enumConstant", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + ], + "swiftCallName" : "Networking", + "tsFullPath" : "Networking" + }, + { + "cases" : [ - } - } - }, + ], + "emitStyle" : "const", + "name" : "API", + "namespace" : [ + "Networking" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API", + "tsFullPath" : "Networking.API" + }, + { + "cases" : [ { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumBool", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "bool" : { + "associatedValues" : [ - } - } + ], + "name" : "get" }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumVariable", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + "associatedValues" : [ - } - } + ], + "name" : "post" }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "computedReadonly", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "int" : { + "associatedValues" : [ - } - } + ], + "name" : "put" }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedReadWrite", - "staticContext" : { - "enumName" : { - "_0" : "StaticPropertyEnum" - } - }, - "type" : { - "string" : { + "associatedValues" : [ - } - } + ], + "name" : "delete" } ], - "swiftCallName" : "StaticPropertyEnum", - "tsFullPath" : "StaticPropertyEnum" + "emitStyle" : "const", + "name" : "Method", + "namespace" : [ + "Networking", + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API.Method", + "tsFullPath" : "Networking.API.Method" }, { "cases" : [ ], "emitStyle" : "const", - "name" : "StaticPropertyNamespace", + "name" : "Configuration", "staticMethods" : [ ], "staticProperties" : [ + + ], + "swiftCallName" : "Configuration", + "tsFullPath" : "Configuration" + }, + { + "cases" : [ { - "isReadonly" : false, - "isStatic" : true, - "name" : "namespaceProperty", - "namespace" : [ - "StaticPropertyNamespace" + "associatedValues" : [ + ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace" - } - }, - "type" : { - "string" : { + "name" : "debug", + "rawValue" : "debug" + }, + { + "associatedValues" : [ - } - } + ], + "name" : "info", + "rawValue" : "info" }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "namespaceConstant", - "namespace" : [ - "StaticPropertyNamespace" + "associatedValues" : [ + ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace" - } - }, - "type" : { - "string" : { + "name" : "warning", + "rawValue" : "warning" + }, + { + "associatedValues" : [ - } - } + ], + "name" : "error", + "rawValue" : "error" } - ], - "swiftCallName" : "StaticPropertyNamespace", - "tsFullPath" : "StaticPropertyNamespace" - }, - { - "cases" : [ - ], "emitStyle" : "const", - "name" : "NestedProperties", + "name" : "LogLevel", "namespace" : [ - "StaticPropertyNamespace" + "Configuration" ], + "rawType" : "String", "staticMethods" : [ ], "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.LogLevel", + "tsFullPath" : "Configuration.LogLevel" + }, + { + "cases" : [ { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedProperty", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "int" : { + "associatedValues" : [ - } - } + ], + "name" : "http", + "rawValue" : "80" }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "nestedConstant", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "string" : { + "associatedValues" : [ - } - } + ], + "name" : "https", + "rawValue" : "443" }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedDouble", - "namespace" : [ - "StaticPropertyNamespace", - "NestedProperties" - ], - "staticContext" : { - "namespaceEnum" : { - "_0" : "StaticPropertyNamespace.NestedProperties" - } - }, - "type" : { - "double" : { + "associatedValues" : [ - } - } + ], + "name" : "development", + "rawValue" : "3000" } ], - "swiftCallName" : "StaticPropertyNamespace.NestedProperties", - "tsFullPath" : "StaticPropertyNamespace.NestedProperties" + "emitStyle" : "const", + "name" : "Port", + "namespace" : [ + "Configuration" + ], + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.Port", + "tsFullPath" : "Configuration.Port" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Internal", + "namespace" : [ + "Networking", + "APIV2" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal", + "tsFullPath" : "Networking.APIV2.Internal" }, { "cases" : [ { "associatedValues" : [ - { - "type" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "Address" - } - }, - "_1" : "null" - } - } - } + ], - "name" : "optStruct" + "name" : "get" }, + { + "associatedValues" : [ + + ], + "name" : "post" + } + ], + "emitStyle" : "const", + "name" : "SupportedMethod", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal.SupportedMethod", + "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" + }, + { + "cases" : [ { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } } ], - "name" : "optClass" + "name" : "success" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "jsObject" : { + "int" : { - } - }, - "_1" : "null" } } } ], - "name" : "optJSObject" + "name" : "failure" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "bool" : { + } } } ], - "name" : "optNestedEnum" + "name" : "flag" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { + "float" : { - } - } - } - }, - "_1" : "null" } } } ], - "name" : "optArray" + "name" : "rate" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - }, - "_1" : "null" + "double" : { + } } } ], - "name" : "optJsClass" + "name" : "precise" }, { "associatedValues" : [ ], - "name" : "empty" + "name" : "info" } ], "emitStyle" : "const", - "name" : "OptionalAllTypesResult", + "name" : "APIResult", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "OptionalAllTypesResult", - "tsFullPath" : "OptionalAllTypesResult" + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" }, { "cases" : [ @@ -7378,13 +7042,8 @@ "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } @@ -7395,644 +7054,1345 @@ "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "int" : { + "string" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "bool" : { + "int" : { - } - }, - "_1" : "null" } } } ], - "name" : "failure" + "name" : "error" }, { "associatedValues" : [ { "type" : { - "nullable" : { - "_0" : { - "bool" : { + "double" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "int" : { + "double" : { - } - }, - "_1" : "null" } } }, { "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } ], - "name" : "status" - } - ], - "emitStyle" : "const", - "name" : "APIOptionalResult", - "staticMethods" : [ + "name" : "location" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { - ], - "staticProperties" : [ + } + } + }, + { + "type" : { + "int" : { - ], - "swiftCallName" : "APIOptionalResult", - "tsFullPath" : "APIOptionalResult" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundTripVoid", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripVoid", - "parameters" : [ + } + } + }, + { + "type" : { + "string" : { - ], - "returnType" : { - "void" : { + } + } + } + ], + "name" : "status" + }, + { + "associatedValues" : [ + { + "type" : { + "double" : { - } - } + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + } + ], + "name" : "coordinates" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "comprehensive" + }, + { + "associatedValues" : [ + + ], + "name" : "info" + } + ], + "emitStyle" : "const", + "name" : "ComplexResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ComplexResult", + "tsFullPath" : "ComplexResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utilities", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utilities", + "tsFullPath" : "Utilities" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "status" + } + ], + "emitStyle" : "const", + "name" : "Result", + "namespace" : [ + "Utilities" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utilities.Result", + "tsFullPath" : "Utilities.Result" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "API", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "API", + "tsFullPath" : "API" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + } + ], + "emitStyle" : "const", + "name" : "NetworkingResult", + "namespace" : [ + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "API.NetworkingResult", + "tsFullPath" : "API.NetworkingResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "swiftStruct" : { + "_0" : "Address" + } + } + } + ], + "name" : "structPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "name" : "classPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "jsObject" : { + + } + } + } + ], + "name" : "jsObjectPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "name" : "nestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "name" : "arrayPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "jsObject" : { + "_0" : "Foo" + } + } + } + ], + "name" : "jsClassPayload" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "AllTypesResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AllTypesResult", + "tsFullPath" : "AllTypesResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + } + ], + "name" : "precision" + }, + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + ], + "name" : "direction" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optPrecision" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optDirection" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "TypedPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TypedPayloadResult", + "tsFullPath" : "TypedPayloadResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "scientific" + }, + { + "associatedValues" : [ + + ], + "name" : "basic" + } + ], + "emitStyle" : "const", + "name" : "StaticCalculator", + "staticMethods" : [ + { + "abiName" : "bjs_StaticCalculator_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "StaticCalculator", + "tsFullPath" : "StaticCalculator" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "StaticUtils", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "StaticUtils", + "tsFullPath" : "StaticUtils" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Nested", + "namespace" : [ + "StaticUtils" + ], + "staticMethods" : [ + { + "abiName" : "bjs_StaticUtils_Nested_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "namespace" : [ + "StaticUtils", + "Nested" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticUtils.Nested" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "StaticUtils.Nested", + "tsFullPath" : "StaticUtils.Nested" }, { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "GraphOperations", + "namespace" : [ + "Services", + "Graph" + ], + "staticMethods" : [ { - "label" : "v", - "name" : "v", - "type" : { + "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createGraph", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "rootId", + "name" : "rootId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "nodeCount", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { "int" : { } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } } } ], - "returnType" : { - "int" : { + "staticProperties" : [ - } - } + ], + "swiftCallName" : "GraphOperations", + "tsFullPath" : "Services.Graph.GraphOperations" }, { - "abiName" : "bjs_roundTripUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUInt", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", + "associatedValues" : [ + + ], + "name" : "option1" + }, + { + "associatedValues" : [ + + ], + "name" : "option2" + } + ], + "emitStyle" : "const", + "name" : "StaticPropertyEnum", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumProperty", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, "type" : { - "uint" : { + "string" : { } } - } - ], - "returnType" : { - "uint" : { + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "enumConstant", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumBool", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumVariable", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "computedReadonly", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "computedReadWrite", + "staticContext" : { + "enumName" : { + "_0" : "StaticPropertyEnum" + } + }, + "type" : { + "string" : { + } + } } - } + ], + "swiftCallName" : "StaticPropertyEnum", + "tsFullPath" : "StaticPropertyEnum" }, { - "abiName" : "bjs_roundTripFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripFloat", - "parameters" : [ + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "StaticPropertyNamespace", + "staticMethods" : [ + + ], + "staticProperties" : [ { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "namespaceProperty", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace" + } + }, "type" : { - "float" : { + "string" : { } } - } - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_roundTripDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDouble", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", + "isReadonly" : true, + "isStatic" : true, + "name" : "namespaceConstant", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace" + } + }, "type" : { - "double" : { + "string" : { } } } ], - "returnType" : { - "double" : { - - } - } + "swiftCallName" : "StaticPropertyNamespace", + "tsFullPath" : "StaticPropertyNamespace" }, { - "abiName" : "bjs_roundTripBool", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripBool", - "parameters" : [ + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "NestedProperties", + "namespace" : [ + "StaticPropertyNamespace" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedProperty", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { - "bool" : { + "int" : { } } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_roundTripString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripString", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", + "isReadonly" : true, + "isStatic" : true, + "name" : "nestedConstant", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { "string" : { } } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_roundTripSwiftHeapObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSwiftHeapObject", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedDouble", + "namespace" : [ + "StaticPropertyNamespace", + "NestedProperties" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "StaticPropertyNamespace.NestedProperties" + } + }, "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "double" : { + } } } ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "swiftCallName" : "StaticPropertyNamespace.NestedProperties", + "tsFullPath" : "StaticPropertyNamespace.NestedProperties" }, { - "abiName" : "bjs_roundTripUnsafeRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeRawPointer", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Address" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optStruct" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optClass" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optJSObject" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optNestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "_1" : "null" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeMutableRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeMutableRawPointer", - "parameters" : [ + ], + "name" : "optArray" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } } } - } + ], + "name" : "optJsClass" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" } ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } + "emitStyle" : "const", + "name" : "OptionalAllTypesResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "OptionalAllTypesResult", + "tsFullPath" : "OptionalAllTypesResult" }, { - "abiName" : "bjs_roundTripOpaquePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOpaquePointer", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafePointer", - "parameters" : [ + ], + "name" : "success" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeMutablePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeMutablePointer", - "parameters" : [ + ], + "name" : "failure" + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } } } - } + ], + "name" : "status" } ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - }, + "emitStyle" : "const", + "name" : "APIOptionalResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIOptionalResult", + "tsFullPath" : "APIOptionalResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ { - "abiName" : "bjs_roundTripJSObject", + "abiName" : "bjs_roundTripVoid", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSObject", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "jsObject" : { - - } - } - } + "name" : "roundTripVoid", + "parameters" : [ + ], "returnType" : { - "jsObject" : { + "void" : { } } }, { - "abiName" : "bjs_roundTripDictionaryExport", + "abiName" : "bjs_roundTripInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDictionaryExport", + "name" : "roundTripInt", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "dictionary" : { - "_0" : { - "int" : { + "int" : { - } - } } } } ], "returnType" : { - "dictionary" : { - "_0" : { - "int" : { + "int" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalDictionaryExport", + "abiName" : "bjs_roundTripUInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDictionaryExport", + "name" : "roundTripUInt", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { + "uint" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { + "uint" : { - } - } - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_roundTripJSValue", + "abiName" : "bjs_roundTripFloat", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSValue", + "name" : "roundTripFloat", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "jsValue" : { + "float" : { } } } ], "returnType" : { - "jsValue" : { + "float" : { } } }, { - "abiName" : "bjs_roundTripOptionalJSValue", + "abiName" : "bjs_roundTripDouble", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValue", + "name" : "roundTripDouble", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "jsValue" : { + "double" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "jsValue" : { + "double" : { - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_roundTripOptionalJSValueArray", + "abiName" : "bjs_roundTripBool", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValueArray", + "name" : "roundTripBool", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "bool" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "bool" : { - } - } - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_makeImportedFoo", + "abiName" : "bjs_roundTripString", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "makeImportedFoo", + "name" : "roundTripString", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { "string" : { @@ -8041,493 +8401,551 @@ } ], "returnType" : { - "jsObject" : { - "_0" : "Foo" + "string" : { + } } }, { - "abiName" : "bjs_throwsSwiftError", + "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsSwiftError", + "name" : "roundTripSwiftHeapObject", "parameters" : [ { - "label" : "shouldThrow", - "name" : "shouldThrow", + "label" : "v", + "name" : "v", "type" : { - "bool" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "void" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_throwsWithIntResult", + "abiName" : "bjs_roundTripUnsafeRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithIntResult", + "name" : "roundTripUnsafeRawPointer", "parameters" : [ - - ], - "returnType" : { - "int" : { - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } } - } - }, - { - "abiName" : "bjs_throwsWithStringResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithStringResult", - "parameters" : [ - ], "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" : [ - - ], - "returnType" : { - "bool" : { - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } } - } - }, - { - "abiName" : "bjs_throwsWithFloatResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithFloatResult", - "parameters" : [ - ], "returnType" : { - "float" : { - + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } }, { - "abiName" : "bjs_throwsWithDoubleResult", + "abiName" : "bjs_roundTripOpaquePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithDoubleResult", + "name" : "roundTripOpaquePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } ], "returnType" : { - "double" : { - + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } } } }, { - "abiName" : "bjs_throwsWithSwiftHeapObjectResult", + "abiName" : "bjs_roundTripUnsafePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithSwiftHeapObjectResult", + "name" : "roundTripUnsafePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_throwsWithJSObjectResult", + "abiName" : "bjs_roundTripUnsafeMutablePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithJSObjectResult", + "name" : "roundTripUnsafeMutablePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } ], "returnType" : { - "jsObject" : { - + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_asyncRoundTripVoid", + "abiName" : "bjs_roundTripJSObject", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripVoid", + "name" : "roundTripJSObject", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + } + } + } ], "returnType" : { - "void" : { + "jsObject" : { } } }, { - "abiName" : "bjs_asyncRoundTripInt", + "abiName" : "bjs_roundTripDictionaryExport", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripInt", + "name" : "roundTripDictionaryExport", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "int" : { + "dictionary" : { + "_0" : { + "int" : { + } + } } } } ], "returnType" : { - "int" : { + "dictionary" : { + "_0" : { + "int" : { + } + } } } }, { - "abiName" : "bjs_asyncRoundTripFloat", + "abiName" : "bjs_roundTripOptionalDictionaryExport", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripFloat", + "name" : "roundTripOptionalDictionaryExport", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "float" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "float" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripDouble", + "abiName" : "bjs_roundTripJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDouble", + "name" : "roundTripJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "double" : { + "jsValue" : { } } } ], "returnType" : { - "double" : { + "jsValue" : { } } }, { - "abiName" : "bjs_asyncRoundTripBool", + "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripBool", + "name" : "roundTripOptionalJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "bool" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } } ], "returnType" : { - "bool" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripString", + "abiName" : "bjs_roundTripOptionalJSValueArray", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripString", + "name" : "roundTripOptionalJSValueArray", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "string" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripSwiftHeapObject", + "abiName" : "bjs_makeImportedFoo", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripSwiftHeapObject", + "name" : "makeImportedFoo", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "value", + "name" : "value", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "string" : { + } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsObject" : { + "_0" : "Foo" } } }, { - "abiName" : "bjs_asyncRoundTripJSObject", + "abiName" : "bjs_throwsSwiftError", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripJSObject", + "name" : "throwsSwiftError", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "shouldThrow", + "name" : "shouldThrow", "type" : { - "jsObject" : { + "bool" : { } } } ], "returnType" : { - "jsObject" : { + "void" : { } } }, { - "abiName" : "bjs_takeGreeter", + "abiName" : "bjs_throwsWithIntResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "takeGreeter", + "name" : "throwsWithIntResult", "parameters" : [ - { - "label" : "g", - "name" : "g", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "void" : { + "int" : { } } }, { - "abiName" : "bjs_createCalculator", + "abiName" : "bjs_throwsWithStringResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "createCalculator", + "name" : "throwsWithStringResult", "parameters" : [ ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Calculator" + "string" : { + } } }, { - "abiName" : "bjs_useCalculator", + "abiName" : "bjs_throwsWithBoolResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "useCalculator", + "name" : "throwsWithBoolResult", "parameters" : [ - { - "label" : "calc", - "name" : "calc", - "type" : { - "swiftHeapObject" : { - "_0" : "Calculator" - } - } - }, - { - "label" : "x", - "name" : "x", - "type" : { - "int" : { - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "int" : { + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_throwsWithFloatResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsWithFloatResult", + "parameters" : [ - } - } - } ], "returnType" : { - "int" : { + "float" : { } } }, { - "abiName" : "bjs_testGreeterToJSValue", + "abiName" : "bjs_throwsWithDoubleResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "testGreeterToJSValue", + "name" : "throwsWithDoubleResult", "parameters" : [ ], "returnType" : { - "jsObject" : { + "double" : { } } }, { - "abiName" : "bjs_testCalculatorToJSValue", + "abiName" : "bjs_throwsWithSwiftHeapObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "testCalculatorToJSValue", + "name" : "throwsWithSwiftHeapObjectResult", "parameters" : [ ], "returnType" : { - "jsObject" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_testSwiftClassAsJSValue", + "abiName" : "bjs_throwsWithJSObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "testSwiftClassAsJSValue", + "name" : "throwsWithJSObjectResult", "parameters" : [ - { - "label" : "greeter", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } + ], "returnType" : { "jsObject" : { @@ -8536,521 +8954,522 @@ } }, { - "abiName" : "bjs_setDirection", + "abiName" : "bjs_asyncRoundTripVoid", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setDirection", + "name" : "asyncRoundTripVoid", "parameters" : [ - { - "label" : "_", - "name" : "direction", - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "void" : { + } } }, { - "abiName" : "bjs_getDirection", + "abiName" : "bjs_asyncRoundTripInt", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getDirection", + "name" : "asyncRoundTripInt", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "int" : { + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "int" : { + } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_asyncRoundTripFloat", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "asyncRoundTripFloat", "parameters" : [ { - "label" : "_", - "name" : "input", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "float" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "float" : { + } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_asyncRoundTripDouble", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "asyncRoundTripDouble", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "double" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "double" : { + } } }, { - "abiName" : "bjs_getTheme", + "abiName" : "bjs_asyncRoundTripBool", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getTheme", + "name" : "asyncRoundTripBool", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "bool" : { + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "bool" : { + } } }, { - "abiName" : "bjs_setHttpStatus", + "abiName" : "bjs_asyncRoundTripString", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setHttpStatus", + "name" : "asyncRoundTripString", "parameters" : [ { - "label" : "_", - "name" : "status", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "string" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "string" : { + } } }, { - "abiName" : "bjs_getHttpStatus", + "abiName" : "bjs_asyncRoundTripSwiftHeapObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getHttpStatus", + "name" : "asyncRoundTripSwiftHeapObject", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_processTheme", + "abiName" : "bjs_asyncRoundTripJSObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "processTheme", + "name" : "asyncRoundTripJSObject", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "jsObject" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "jsObject" : { + } } }, { - "abiName" : "bjs_setTSDirection", + "abiName" : "bjs_takeGreeter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSDirection", + "name" : "takeGreeter", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "g", + "name" : "g", "type" : { - "caseEnum" : { - "_0" : "TSDirection" + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "void" : { + } } }, { - "abiName" : "bjs_getTSDirection", + "abiName" : "bjs_createCalculator", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSDirection", + "name" : "createCalculator", "parameters" : [ ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "abiName" : "bjs_setTSTheme", + "abiName" : "bjs_useCalculator", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSTheme", + "name" : "useCalculator", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "calc", + "name" : "calc", + "type" : { + "swiftHeapObject" : { + "_0" : "Calculator" + } + } + }, + { + "label" : "x", + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "label" : "y", + "name" : "y", "type" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "int" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "int" : { + } } }, { - "abiName" : "bjs_getTSTheme", + "abiName" : "bjs_testGreeterToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSTheme", + "name" : "testGreeterToJSValue", "parameters" : [ ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "jsObject" : { + } } }, { - "abiName" : "bjs_createConverter", + "abiName" : "bjs_testCalculatorToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createConverter", + "name" : "testCalculatorToJSValue", "parameters" : [ ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "jsObject" : { + } } }, { - "abiName" : "bjs_useConverter", + "abiName" : "bjs_testSwiftClassAsJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "useConverter", + "name" : "testSwiftClassAsJSValue", "parameters" : [ { - "label" : "converter", - "name" : "converter", + "label" : "greeter", + "name" : "greeter", "type" : { "swiftHeapObject" : { - "_0" : "Utils.Converter" - } - } - }, - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - + "_0" : "Greeter" } } } ], "returnType" : { - "string" : { + "jsObject" : { } } }, { - "abiName" : "bjs_roundTripConverterArray", + "abiName" : "bjs_setDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripConverterArray", + "name" : "setDirection", "parameters" : [ { "label" : "_", - "name" : "converters", + "name" : "direction", "type" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" - } - } + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" - } - } + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_createHTTPServer", + "abiName" : "bjs_getDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createHTTPServer", + "name" : "getDirection", "parameters" : [ ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Networking.API.HTTPServer" + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_createUUID", + "abiName" : "bjs_processDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createUUID", + "name" : "processDirection", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "input", "type" : { - "string" : { - + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_roundTripUUID", + "abiName" : "bjs_setTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUUID", + "name" : "setTheme", "parameters" : [ { "label" : "_", - "name" : "uuid", + "name" : "theme", "type" : { - "swiftHeapObject" : { - "_0" : "UUID" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundtripNetworkingAPIMethod", + "abiName" : "bjs_getTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripNetworkingAPIMethod", + "name" : "getTheme", "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Networking.API.Method" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundtripConfigurationLogLevel", + "abiName" : "bjs_setHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripConfigurationLogLevel", + "name" : "setHttpStatus", "parameters" : [ { "label" : "_", - "name" : "level", + "name" : "status", "type" : { "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" + "_0" : "HttpStatus", + "_1" : "Int" } } } ], "returnType" : { "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_roundtripConfigurationPort", + "abiName" : "bjs_getHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripConfigurationPort", + "name" : "getHttpStatus", "parameters" : [ - { - "label" : "_", - "name" : "port", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" - } - } - } + ], "returnType" : { "rawValueEnum" : { - "_0" : "Configuration.Port", + "_0" : "HttpStatus", "_1" : "Int" } } }, { - "abiName" : "bjs_processConfigurationLogLevel", + "abiName" : "bjs_processTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processConfigurationLogLevel", + "name" : "processTheme", "parameters" : [ { "label" : "_", - "name" : "level", + "name" : "theme", "type" : { "rawValueEnum" : { - "_0" : "Configuration.LogLevel", + "_0" : "Theme", "_1" : "String" } } @@ -9058,502 +9477,444 @@ ], "returnType" : { "rawValueEnum" : { - "_0" : "Configuration.Port", + "_0" : "HttpStatus", "_1" : "Int" } } }, { - "abiName" : "bjs_roundtripInternalSupportedMethod", + "abiName" : "bjs_setTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripInternalSupportedMethod", + "name" : "setTSDirection", "parameters" : [ { "label" : "_", - "name" : "method", + "name" : "direction", "type" : { "caseEnum" : { - "_0" : "Internal.SupportedMethod" + "_0" : "TSDirection" } } } ], "returnType" : { "caseEnum" : { - "_0" : "Internal.SupportedMethod" + "_0" : "TSDirection" } } }, { - "abiName" : "bjs_roundtripAPIResult", + "abiName" : "bjs_getTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripAPIResult", + "name" : "getTSDirection", "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "caseEnum" : { + "_0" : "TSDirection" } } }, { - "abiName" : "bjs_makeAPIResultSuccess", + "abiName" : "bjs_setTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultSuccess", + "name" : "setTSTheme", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "theme", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, { - "abiName" : "bjs_makeAPIResultFailure", + "abiName" : "bjs_getTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultFailure", + "name" : "getTSTheme", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "int" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, { - "abiName" : "bjs_makeAPIResultInfo", + "abiName" : "bjs_createConverter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultInfo", + "name" : "createConverter", "parameters" : [ ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "swiftHeapObject" : { + "_0" : "Utils.Converter" } } }, { - "abiName" : "bjs_makeAPIResultFlag", + "abiName" : "bjs_useConverter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultFlag", + "name" : "useConverter", "parameters" : [ { - "label" : "_", + "label" : "converter", + "name" : "converter", + "type" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } + }, + { + "label" : "value", "name" : "value", "type" : { - "bool" : { + "int" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "string" : { + } } }, { - "abiName" : "bjs_makeAPIResultRate", + "abiName" : "bjs_roundTripConverterArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultRate", + "name" : "roundTripConverterArray", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "converters", "type" : { - "float" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } }, { - "abiName" : "bjs_makeAPIResultPrecise", + "abiName" : "bjs_createHTTPServer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultPrecise", + "name" : "createHTTPServer", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "double" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "swiftHeapObject" : { + "_0" : "Networking.API.HTTPServer" } } }, { - "abiName" : "bjs_roundtripComplexResult", + "abiName" : "bjs_createUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripComplexResult", + "name" : "createUUID", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "value", + "name" : "value", "type" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "string" : { + } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "UUID" } } }, { - "abiName" : "bjs_makeComplexResultSuccess", + "abiName" : "bjs_roundTripUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultSuccess", + "name" : "roundTripUUID", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "uuid", "type" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "UUID" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "UUID" } } }, { - "abiName" : "bjs_makeComplexResultError", + "abiName" : "bjs_roundtripNetworkingAPIMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultError", + "name" : "roundtripNetworkingAPIMethod", "parameters" : [ { "label" : "_", - "name" : "message", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "name" : "method", "type" : { - "int" : { - + "caseEnum" : { + "_0" : "Networking.API.Method" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "caseEnum" : { + "_0" : "Networking.API.Method" } } }, { - "abiName" : "bjs_makeComplexResultLocation", + "abiName" : "bjs_roundtripConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultLocation", + "name" : "roundtripConfigurationLogLevel", "parameters" : [ { "label" : "_", - "name" : "lat", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "lng", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "name", + "name" : "level", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } }, { - "abiName" : "bjs_makeComplexResultStatus", + "abiName" : "bjs_roundtripConfigurationPort", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultStatus", + "name" : "roundtripConfigurationPort", "parameters" : [ { "label" : "_", - "name" : "active", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "code", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "message", + "name" : "port", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeComplexResultCoordinates", + "abiName" : "bjs_processConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultCoordinates", + "name" : "processConfigurationLogLevel", "parameters" : [ { "label" : "_", - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "y", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "z", + "name" : "level", "type" : { - "double" : { - + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeComplexResultComprehensive", + "abiName" : "bjs_roundtripInternalSupportedMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultComprehensive", + "name" : "roundtripInternalSupportedMethod", "parameters" : [ { "label" : "_", - "name" : "flag1", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "flag2", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "count1", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "count2", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "value1", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "value2", - "type" : { - "double" : { - + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Internal.SupportedMethod" } } - }, + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Internal.SupportedMethod" + } + } + }, + { + "abiName" : "bjs_roundtripAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripAPIResult", + "parameters" : [ { - "label" : "_", - "name" : "text1", + "label" : "result", + "name" : "result", "type" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "APIResult" } } - }, + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "abiName" : "bjs_makeAPIResultSuccess", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAPIResultSuccess", + "parameters" : [ { "label" : "_", - "name" : "text2", + "name" : "value", "type" : { "string" : { } } - }, + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "abiName" : "bjs_makeAPIResultFailure", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAPIResultFailure", + "parameters" : [ { "label" : "_", - "name" : "text3", + "name" : "value", "type" : { - "string" : { + "int" : { } } @@ -9561,41 +9922,41 @@ ], "returnType" : { "associatedValueEnum" : { - "_0" : "ComplexResult" + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeComplexResultInfo", + "abiName" : "bjs_makeAPIResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultInfo", + "name" : "makeAPIResultInfo", "parameters" : [ ], "returnType" : { "associatedValueEnum" : { - "_0" : "ComplexResult" + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeUtilitiesResultSuccess", + "abiName" : "bjs_makeAPIResultFlag", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultSuccess", + "name" : "makeAPIResultFlag", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "value", "type" : { - "string" : { + "bool" : { } } @@ -9603,33 +9964,24 @@ ], "returnType" : { "associatedValueEnum" : { - "_0" : "Utilities.Result" + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeUtilitiesResultFailure", + "abiName" : "bjs_makeAPIResultRate", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultFailure", + "name" : "makeAPIResultRate", "parameters" : [ { "label" : "_", - "name" : "error", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "name" : "value", "type" : { - "int" : { + "float" : { } } @@ -9637,65 +9989,72 @@ ], "returnType" : { "associatedValueEnum" : { - "_0" : "Utilities.Result" + "_0" : "APIResult" } } }, { - "abiName" : "bjs_makeUtilitiesResultStatus", + "abiName" : "bjs_makeAPIResultPrecise", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultStatus", + "name" : "makeAPIResultPrecise", "parameters" : [ { "label" : "_", - "name" : "active", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "code", + "name" : "value", "type" : { - "int" : { + "double" : { } } - }, + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "abiName" : "bjs_roundtripComplexResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripComplexResult", + "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "result", "type" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "ComplexResult" } } } ], "returnType" : { "associatedValueEnum" : { - "_0" : "Utilities.Result" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_makeAPINetworkingResultSuccess", + "abiName" : "bjs_makeComplexResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultSuccess", + "name" : "makeComplexResultSuccess", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "value", "type" : { "string" : { @@ -9705,22 +10064,22 @@ ], "returnType" : { "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_makeAPINetworkingResultFailure", + "abiName" : "bjs_makeComplexResultError", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultFailure", + "name" : "makeComplexResultError", "parameters" : [ { "label" : "_", - "name" : "error", + "name" : "message", "type" : { "string" : { @@ -9739,122 +10098,169 @@ ], "returnType" : { "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundtripUtilitiesResult", + "abiName" : "bjs_makeComplexResultLocation", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripUtilitiesResult", + "name" : "makeComplexResultLocation", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "lat", "type" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "double" : { + } } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" - } - } - }, - { - "abiName" : "bjs_roundtripAPINetworkingResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtripAPINetworkingResult", - "parameters" : [ + }, { "label" : "_", - "name" : "result", + "name" : "lng", "type" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "name", + "type" : { + "string" : { + } } } ], "returnType" : { "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripAllTypesResult", + "abiName" : "bjs_makeComplexResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripAllTypesResult", + "name" : "makeComplexResultStatus", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "active", "type" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { + } } } ], "returnType" : { "associatedValueEnum" : { - "_0" : "AllTypesResult" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripTypedPayloadResult", + "abiName" : "bjs_makeComplexResultCoordinates", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripTypedPayloadResult", + "name" : "makeComplexResultCoordinates", "parameters" : [ { "label" : "_", - "name" : "result", + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "z", "type" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" + "double" : { + } } } ], "returnType" : { "associatedValueEnum" : { - "_0" : "TypedPayloadResult" + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_createPropertyHolder", + "abiName" : "bjs_makeComplexResultComprehensive", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createPropertyHolder", + "name" : "makeComplexResultComprehensive", "parameters" : [ { - "label" : "intValue", - "name" : "intValue", + "label" : "_", + "name" : "flag1", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "flag2", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "count1", "type" : { "int" : { @@ -9862,17 +10268,17 @@ } }, { - "label" : "floatValue", - "name" : "floatValue", + "label" : "_", + "name" : "count2", "type" : { - "float" : { + "int" : { } } }, { - "label" : "doubleValue", - "name" : "doubleValue", + "label" : "_", + "name" : "value1", "type" : { "double" : { @@ -9880,17 +10286,17 @@ } }, { - "label" : "boolValue", - "name" : "boolValue", + "label" : "_", + "name" : "value2", "type" : { - "bool" : { + "double" : { } } }, { - "label" : "stringValue", - "name" : "stringValue", + "label" : "_", + "name" : "text1", "type" : { "string" : { @@ -9898,96 +10304,58 @@ } }, { - "label" : "jsObject", - "name" : "jsObject", + "label" : "_", + "name" : "text2", "type" : { - "jsObject" : { + "string" : { } } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" - } - } - }, - { - "abiName" : "bjs_testPropertyHolder", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testPropertyHolder", - "parameters" : [ + }, { - "label" : "holder", - "name" : "holder", + "label" : "_", + "name" : "text3", "type" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" + "string" : { + } } } ], "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_resetObserverCounts", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "resetObserverCounts", - "parameters" : [ - - ], - "returnType" : { - "void" : { - + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_getObserverStats", + "abiName" : "bjs_makeComplexResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getObserverStats", + "name" : "makeComplexResultInfo", "parameters" : [ ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_testStringDefault", + "abiName" : "bjs_makeUtilitiesResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testStringDefault", + "name" : "makeUtilitiesResultSuccess", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Hello World" - } - }, - "label" : "message", + "label" : "_", "name" : "message", "type" : { "string" : { @@ -9997,28 +10365,32 @@ } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_testIntDefault", + "abiName" : "bjs_makeUtilitiesResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testIntDefault", + "name" : "makeUtilitiesResultFailure", "parameters" : [ { - "defaultValue" : { - "int" : { - "_0" : 42 + "label" : "_", + "name" : "error", + "type" : { + "string" : { + } - }, - "label" : "count", - "name" : "count", + } + }, + { + "label" : "_", + "name" : "code", "type" : { "int" : { @@ -10027,98 +10399,91 @@ } ], "returnType" : { - "int" : { - + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_testBoolDefault", + "abiName" : "bjs_makeUtilitiesResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testBoolDefault", + "name" : "makeUtilitiesResultStatus", "parameters" : [ { - "defaultValue" : { + "label" : "_", + "name" : "active", + "type" : { "bool" : { - "_0" : true + } - }, - "label" : "flag", - "name" : "flag", + } + }, + { + "label" : "_", + "name" : "code", "type" : { - "bool" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { } } } ], "returnType" : { - "bool" : { - + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_testOptionalDefault", + "abiName" : "bjs_makeAPINetworkingResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testOptionalDefault", + "name" : "makeAPINetworkingResultSuccess", "parameters" : [ { - "defaultValue" : { - "null" : { - - } - }, - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "message", "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_testMultipleDefaults", + "abiName" : "bjs_makeAPINetworkingResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testMultipleDefaults", + "name" : "makeAPINetworkingResultFailure", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Default Title" - } - }, - "label" : "title", - "name" : "title", + "label" : "_", + "name" : "error", "type" : { "string" : { @@ -10126,357 +10491,243 @@ } }, { - "defaultValue" : { - "int" : { - "_0" : -10 - } - }, - "label" : "count", - "name" : "count", + "label" : "_", + "name" : "code", "type" : { "int" : { - } - } - }, - { - "defaultValue" : { - "bool" : { - "_0" : false - } - }, - "label" : "enabled", - "name" : "enabled", - "type" : { - "bool" : { - } } } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_testSimpleEnumDefault", + "abiName" : "bjs_roundtripUtilitiesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testSimpleEnumDefault", + "name" : "roundtripUtilitiesResult", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "success" - } - }, - "label" : "status", - "name" : "status", + "label" : "_", + "name" : "result", "type" : { - "caseEnum" : { - "_0" : "Status" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_testDirectionDefault", + "abiName" : "bjs_roundtripAPINetworkingResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testDirectionDefault", + "name" : "roundtripAPINetworkingResult", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Direction", - "_1" : "north" - } - }, - "label" : "direction", - "name" : "direction", + "label" : "_", + "name" : "result", "type" : { - "caseEnum" : { - "_0" : "Direction" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_testRawStringEnumDefault", + "abiName" : "bjs_roundTripAllTypesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testRawStringEnumDefault", + "name" : "roundTripAllTypesResult", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Theme", - "_1" : "light" - } - }, - "label" : "theme", - "name" : "theme", + "label" : "_", + "name" : "result", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } }, { - "abiName" : "bjs_testComplexInit", + "abiName" : "bjs_roundTripTypedPayloadResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testComplexInit", + "name" : "roundTripTypedPayloadResult", "parameters" : [ { - "defaultValue" : { - "objectWithArguments" : { - "_0" : "Greeter", - "_1" : [ - { - "string" : { - "_0" : "DefaultGreeter" - } - } - ] - } - }, - "label" : "greeter", - "name" : "greeter", + "label" : "_", + "name" : "result", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } }, { - "abiName" : "bjs_testEmptyInit", + "abiName" : "bjs_createPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testEmptyInit", + "name" : "createPropertyHolder", "parameters" : [ { - "defaultValue" : { - "object" : { - "_0" : "StaticPropertyHolder" + "label" : "intValue", + "name" : "intValue", + "type" : { + "int" : { + } - }, - "label" : "_", - "name" : "object", + } + }, + { + "label" : "floatValue", + "name" : "floatValue", "type" : { - "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" + "float" : { + + } + } + }, + { + "label" : "doubleValue", + "name" : "doubleValue", + "type" : { + "double" : { + + } + } + }, + { + "label" : "boolValue", + "name" : "boolValue", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { + + } + } + }, + { + "label" : "jsObject", + "name" : "jsObject", + "type" : { + "jsObject" : { + } } } ], "returnType" : { "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" + "_0" : "PropertyHolder" } } }, { - "abiName" : "bjs_arrayWithDefault", + "abiName" : "bjs_testPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayWithDefault", + "name" : "testPropertyHolder", "parameters" : [ { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 1 - } - }, - { - "int" : { - "_0" : 2 - } - }, - { - "int" : { - "_0" : 3 - } - } - ] - } - }, - "label" : "_", - "name" : "values", + "label" : "holder", + "name" : "holder", "type" : { - "array" : { - "_0" : { - "int" : { - - } - } + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } } ], "returnType" : { - "int" : { + "string" : { } } }, { - "abiName" : "bjs_arrayWithOptionalDefault", + "abiName" : "bjs_resetObserverCounts", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayWithOptionalDefault", + "name" : "resetObserverCounts", "parameters" : [ - { - "defaultValue" : { - "null" : { - - } - }, - "label" : "_", - "name" : "values", - "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - } - } - } - }, - "_1" : "null" - } - } - } ], "returnType" : { - "int" : { + "void" : { } } }, { - "abiName" : "bjs_arrayMixedDefaults", + "abiName" : "bjs_getObserverStats", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayMixedDefaults", + "name" : "getObserverStats", "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Sum" - } - }, - "label" : "prefix", - "name" : "prefix", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 10 - } - }, - { - "int" : { - "_0" : 20 - } - } - ] - } - }, - "label" : "values", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "defaultValue" : { - "string" : { - "_0" : "!" - } - }, - "label" : "suffix", - "name" : "suffix", - "type" : { - "string" : { - } - } - } ], "returnType" : { "string" : { @@ -15354,6 +15605,38 @@ } ] }, + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "DefaultArgumentImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "name" : "runJsDefaultArgumentTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, { "functions" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs new file mode 100644 index 000000000..2a4f3773c --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs @@ -0,0 +1,97 @@ +// @ts-check + +import assert from 'node:assert'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["DefaultArgumentImports"]} + */ +export function getImports(importsContext) { + return { + runJsDefaultArgumentTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsDefaultArgumentTests(exports); + }, + }; +} + +/** + * Default argument bridging coverage for BridgeJS runtime tests. + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports + */ +export function runJsDefaultArgumentTests(rootExports) { + const exports = rootExports.DefaultArgumentExports; + const { Status, Direction, Theme } = rootExports; + + assert.equal(exports.testStringDefault(), "Hello World"); + assert.equal(exports.testStringDefault("Custom Message"), "Custom Message"); + + assert.equal(exports.testIntDefault(), 42); + assert.equal(exports.testIntDefault(100), 100); + + assert.equal(exports.testBoolDefault(), true); + assert.equal(exports.testBoolDefault(false), false); + + assert.equal(exports.testOptionalDefault(), null); + assert.equal(exports.testOptionalDefault("Test"), "Test"); + + assert.equal(exports.testMultipleDefaults(), "Default Title: -10 (false)"); + assert.equal(exports.testMultipleDefaults("Custom"), "Custom: -10 (false)"); + assert.equal(exports.testMultipleDefaults("Custom", 5), "Custom: 5 (false)"); + assert.equal(exports.testMultipleDefaults("Custom", undefined, true), "Custom: -10 (true)"); + assert.equal(exports.testMultipleDefaults("Custom", 5, true), "Custom: 5 (true)"); + + assert.equal(exports.testSimpleEnumDefault(), Status.Success); + assert.equal(exports.testSimpleEnumDefault(Status.Loading), Status.Loading); + + assert.equal(exports.testDirectionDefault(), Direction.North); + assert.equal(exports.testDirectionDefault(Direction.South), Direction.South); + + assert.equal(exports.testRawStringEnumDefault(), Theme.Light); + assert.equal(exports.testRawStringEnumDefault(Theme.Dark), Theme.Dark); + + const holder = exports.testEmptyInit(); + assert.notEqual(holder, null); + holder.release(); + + const customHolder = new rootExports.StaticPropertyHolder(); + assert.deepEqual(exports.testEmptyInit(customHolder), customHolder); + customHolder.release(); + + assert.equal(exports.testComplexInit(), "Hello, DefaultGreeter!"); + const customGreeter = new rootExports.Greeter("CustomName"); + assert.equal(exports.testComplexInit(customGreeter), "Hello, CustomName!"); + customGreeter.release(); + + const cd1 = exports.createConstructorDefaults(); + assert.equal(exports.describeConstructorDefaults(cd1), "Default:42:true:success:nil"); + cd1.release(); + + const cd2 = exports.createConstructorDefaults("Custom"); + assert.equal(exports.describeConstructorDefaults(cd2), "Custom:42:true:success:nil"); + cd2.release(); + + const cd3 = exports.createConstructorDefaults("Custom", 100); + assert.equal(exports.describeConstructorDefaults(cd3), "Custom:100:true:success:nil"); + cd3.release(); + + const cd4 = exports.createConstructorDefaults("Custom", undefined, false); + assert.equal(exports.describeConstructorDefaults(cd4), "Custom:42:false:success:nil"); + cd4.release(); + + const cd5 = exports.createConstructorDefaults("Test", 99, false, Status.Loading); + assert.equal(exports.describeConstructorDefaults(cd5), "Test:99:false:loading:nil"); + cd5.release(); + + assert.equal(exports.arrayWithDefault(), 6); + assert.equal(exports.arrayWithDefault([10, 20]), 30); + assert.equal(exports.arrayWithOptionalDefault(), -1); + assert.equal(exports.arrayWithOptionalDefault(null), -1); + assert.equal(exports.arrayWithOptionalDefault([5, 5]), 10); + assert.equal(exports.arrayMixedDefaults(), "Sum: 30!"); + assert.equal(exports.arrayMixedDefaults("Total"), "Total: 30!"); + assert.equal(exports.arrayMixedDefaults("Total", [1, 2, 3]), "Total: 6!"); + assert.equal(exports.arrayMixedDefaults("Val", [100], "?"), "Val: 100?"); + assert.equal(exports.arrayMixedDefaults(undefined, [5, 5]), "Sum: 10!"); + assert.equal(exports.arrayMixedDefaults(undefined, undefined, "?"), "Sum: 30?"); +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 953c9b93a..350386e46 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -9,6 +9,7 @@ import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/J 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'; +import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs'; import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ @@ -163,6 +164,7 @@ export async function setupOptions(options, context) { SwiftClassSupportImports: getSwiftClassSupportImports(importsContext), OptionalSupportImports: getOptionalSupportImports(importsContext), ArraySupportImports: getArraySupportImports(importsContext), + DefaultArgumentImports: getDefaultArgumentImports(importsContext), JSClassSupportImports: getJSClassSupportImports(importsContext), }; }, @@ -786,68 +788,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.Services.Graph.GraphOperations.nodeCount(42), 42); assert.equal(exports.Services.Graph.GraphOperations.nodeCount(0), 0); - // Test default parameters - assert.equal(exports.testStringDefault(), "Hello World"); - assert.equal(exports.testStringDefault("Custom Message"), "Custom Message"); - - assert.equal(exports.testIntDefault(), 42); - assert.equal(exports.testIntDefault(100), 100); - - assert.equal(exports.testBoolDefault(), true); - assert.equal(exports.testBoolDefault(false), false); - - assert.equal(exports.testOptionalDefault(), null); - assert.equal(exports.testOptionalDefault("Test"), "Test"); - - assert.equal(exports.testMultipleDefaults(), "Default Title: -10 (false)"); - assert.equal(exports.testMultipleDefaults("Custom"), "Custom: -10 (false)"); - assert.equal(exports.testMultipleDefaults("Custom", 5), "Custom: 5 (false)"); - assert.equal(exports.testMultipleDefaults("Custom", undefined, true), "Custom: -10 (true)"); - assert.equal(exports.testMultipleDefaults("Custom", 5, true), "Custom: 5 (true)"); - - assert.equal(exports.testSimpleEnumDefault(), exports.Status.Success); - assert.equal(exports.testSimpleEnumDefault(exports.Status.Loading), exports.Status.Loading); - - assert.equal(exports.testDirectionDefault(), exports.Direction.North); - assert.equal(exports.testDirectionDefault(exports.Direction.South), exports.Direction.South); - - assert.equal(exports.testRawStringEnumDefault(), exports.Theme.Light); - assert.equal(exports.testRawStringEnumDefault(exports.Theme.Dark), exports.Theme.Dark); - - const holder = exports.testEmptyInit() - assert.notEqual(holder, null); - holder.release(); - - const customHolder = new exports.StaticPropertyHolder(); - assert.deepEqual(exports.testEmptyInit(customHolder), customHolder); - customHolder.release(); - - assert.equal(exports.testComplexInit(), "Hello, DefaultGreeter!"); - const customGreeter = new exports.Greeter("CustomName"); - assert.equal(exports.testComplexInit(customGreeter), "Hello, CustomName!"); - - customGreeter.release(); - - const cd1 = new exports.ConstructorDefaults(); - assert.equal(cd1.describe(), "Default:42:true:success:nil"); - cd1.release(); - - const cd2 = new exports.ConstructorDefaults("Custom"); - assert.equal(cd2.describe(), "Custom:42:true:success:nil"); - cd2.release(); - - const cd3 = new exports.ConstructorDefaults("Custom", 100); - assert.equal(cd3.describe(), "Custom:100:true:success:nil"); - cd3.release(); - - const cd4 = new exports.ConstructorDefaults("Custom", undefined, false); - assert.equal(cd4.describe(), "Custom:42:false:success:nil"); - cd4.release(); - - const cd5 = new exports.ConstructorDefaults("Test", 99, false, exports.Status.Loading); - assert.equal(cd5.describe(), "Test:99:false:loading:nil"); - cd5.release(); - testProtocolSupport(exports); testArraySupport(exports); } @@ -1224,18 +1164,21 @@ function testArraySupport(exports) { assert.equal(exports.roundTripOptionalGreeterArrayType(null), null); og1.release(); optGreeterResult.forEach(g => g.release()); - // Default values - assert.equal(exports.arrayWithDefault(), 6); - assert.equal(exports.arrayWithDefault([10, 20]), 30); - assert.equal(exports.arrayWithOptionalDefault(), -1); - assert.equal(exports.arrayWithOptionalDefault(null), -1); - assert.equal(exports.arrayWithOptionalDefault([5, 5]), 10); - assert.equal(exports.arrayMixedDefaults(), "Sum: 30!"); - assert.equal(exports.arrayMixedDefaults("Total"), "Total: 30!"); - assert.equal(exports.arrayMixedDefaults("Total", [1, 2, 3]), "Total: 6!"); - assert.equal(exports.arrayMixedDefaults("Val", [100], "?"), "Val: 100?"); - assert.equal(exports.arrayMixedDefaults(undefined, [5, 5]), "Sum: 10!"); - assert.equal(exports.arrayMixedDefaults(undefined, undefined, "?"), "Sum: 30?"); + const helper1 = new exports.Greeter("Helper1"); + const jsProcessor1 = { + count: 1, name: "Processor1", optionalTag: null, optionalCount: null, + direction: null, optionalTheme: null, httpStatus: null, apiResult: null, + helper: helper1, optionalHelper: null, + increment(by) { this.count += by; }, + getValue() { return this.count; }, + setLabelElements(a, b) { }, getLabel() { return ""; }, + isEven() { return this.count % 2 === 0; }, + processGreeter(g) { return ""; }, createGreeter() { return new exports.Greeter("P1"); }, + processOptionalGreeter(g) { return ""; }, createOptionalGreeter() { return null; }, + handleAPIResult(r) { }, getAPIResult() { return null; } + }; + + helper1.release(); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ From c0785e188093fa95fbde1450be41e6303e0d63d2 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Fri, 27 Feb 2026 13:37:20 +0900 Subject: [PATCH 006/140] [NFC] BridgeJS: Move all Optional tests into OptionalSupportTests (#680) --- .../BridgeJSRuntimeTests/ExportAPITests.swift | 15 - .../Generated/BridgeJS.swift | 651 ++- .../Generated/JavaScript/BridgeJS.json | 4681 +++++++++-------- .../JavaScript/OptionalSupportTests.mjs | 98 +- .../OptionalSupportTests.swift | 189 +- Tests/prelude.mjs | 33 - 6 files changed, 2781 insertions(+), 2886 deletions(-) diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index cfc1b47b5..764544ab3 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1174,21 +1174,6 @@ enum GraphOperations { } } -// MARK: - Array Tests - -// Optional arrays -@JS func roundTripOptionalIntArrayType(_ values: [Int]?) -> [Int]? { - return values -} - -@JS func roundTripOptionalStringArrayType(_ values: [String]?) -> [String]? { - return values -} - -@JS func roundTripOptionalGreeterArrayType(_ greeters: [Greeter]?) -> [Greeter]? { - return greeters -} - class ExportAPITests: XCTestCase { func testAll() { var hasDeinitGreeter = false diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 34637a322..2b9b02793 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3652,6 +3652,304 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_se #endif } +@_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 +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 = OptionalSupportExports.roundTripOptionalNamespacedEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + 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 { + #if arch(wasm32) + let ret = OptionalSupportExports.roundTripOptionalSwiftClass(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + 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 { + #if arch(wasm32) + let ret = OptionalSupportExports.roundTripOptionalIntArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() + #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 +} + +@_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 +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 = OptionalSupportExports.roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) + 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 +} + +@_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 + 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 +} + +@_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 + 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 +} + +@_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 +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> OptionalAllTypesResult { switch caseId { @@ -6071,359 +6369,6 @@ public func _bjs_makeAdder(_ base: Int32) -> Int32 { #endif } -@_expose(wasm, "bjs_roundTripOptionalIntArrayType") -@_cdecl("bjs_roundTripOptionalIntArrayType") -public func _bjs_roundTripOptionalIntArrayType() -> Void { - #if arch(wasm32) - let ret = roundTripOptionalIntArrayType(_: Optional<[Int]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalStringArrayType") -@_cdecl("bjs_roundTripOptionalStringArrayType") -public func _bjs_roundTripOptionalStringArrayType() -> Void { - #if arch(wasm32) - let ret = roundTripOptionalStringArrayType(_: Optional<[String]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalGreeterArrayType") -@_cdecl("bjs_roundTripOptionalGreeterArrayType") -public func _bjs_roundTripOptionalGreeterArrayType() -> Void { - #if arch(wasm32) - let ret = roundTripOptionalGreeterArrayType(_: Optional<[Greeter]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalString") -@_cdecl("bjs_roundTripOptionalString") -public func _bjs_roundTripOptionalString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalInt") -@_cdecl("bjs_roundTripOptionalInt") -public func _bjs_roundTripOptionalInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalBool") -@_cdecl("bjs_roundTripOptionalBool") -public func _bjs_roundTripOptionalBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalFloat") -@_cdecl("bjs_roundTripOptionalFloat") -public func _bjs_roundTripOptionalFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalDouble") -@_cdecl("bjs_roundTripOptionalDouble") -public func _bjs_roundTripOptionalDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalSyntax") -@_cdecl("bjs_roundTripOptionalSyntax") -public func _bjs_roundTripOptionalSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalMixSyntax") -@_cdecl("bjs_roundTripOptionalMixSyntax") -public func _bjs_roundTripOptionalMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalSwiftSyntax") -@_cdecl("bjs_roundTripOptionalSwiftSyntax") -public func _bjs_roundTripOptionalSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalWithSpaces") -@_cdecl("bjs_roundTripOptionalWithSpaces") -public func _bjs_roundTripOptionalWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalTypeAlias") -@_cdecl("bjs_roundTripOptionalTypeAlias") -public func _bjs_roundTripOptionalTypeAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalTypeAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalStatus") -@_cdecl("bjs_roundTripOptionalStatus") -public func _bjs_roundTripOptionalStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalTheme") -@_cdecl("bjs_roundTripOptionalTheme") -public func _bjs_roundTripOptionalTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalHttpStatus") -@_cdecl("bjs_roundTripOptionalHttpStatus") -public func _bjs_roundTripOptionalHttpStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalHttpStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalTSDirection") -@_cdecl("bjs_roundTripOptionalTSDirection") -public func _bjs_roundTripOptionalTSDirection(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalTSDirection(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalTSTheme") -@_cdecl("bjs_roundTripOptionalTSTheme") -public func _bjs_roundTripOptionalTSTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalTSTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalNetworkingAPIMethod") -@_cdecl("bjs_roundTripOptionalNetworkingAPIMethod") -public func _bjs_roundTripOptionalNetworkingAPIMethod(_ methodIsSome: Int32, _ methodValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalNetworkingAPIMethod(_: Optional.bridgeJSLiftParameter(methodIsSome, methodValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAPIResult") -@_cdecl("bjs_roundTripOptionalAPIResult") -public func _bjs_roundTripOptionalAPIResult(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAPIResult(value: Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalTypedPayloadResult") -@_cdecl("bjs_roundTripOptionalTypedPayloadResult") -public func _bjs_roundTripOptionalTypedPayloadResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_takeOptionalJSObject") -@_cdecl("bjs_takeOptionalJSObject") -public func _bjs_takeOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - takeOptionalJSObject(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_compareAPIResults") -@_cdecl("bjs_compareAPIResults") -public func _bjs_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 = compareAPIResults(_: _tmp_r1, _: _tmp_r2) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalComplexResult") -@_cdecl("bjs_roundTripOptionalComplexResult") -public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAllTypesResult") -@_cdecl("bjs_roundTripOptionalAllTypesResult") -public func _bjs_roundTripOptionalAllTypesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalPayloadResult") -@_cdecl("bjs_roundTripOptionalPayloadResult") -public func _bjs_roundTripOptionalPayloadResult(_ result: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(result)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalPayloadResultOpt") -@_cdecl("bjs_roundTripOptionalPayloadResultOpt") -public func _bjs_roundTripOptionalPayloadResultOpt(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalClass") -@_cdecl("bjs_roundTripOptionalClass") -public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalGreeter") -@_cdecl("bjs_roundTripOptionalGreeter") -public func _bjs_roundTripOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_applyOptionalGreeter") -@_cdecl("bjs_applyOptionalGreeter") -public func _bjs_applyOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer, _ transform: Int32) -> Void { - #if arch(wasm32) - let ret = applyOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue), _: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC.bridgeJSLift(transform)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_makeOptionalHolder") -@_cdecl("bjs_makeOptionalHolder") -public func _bjs_makeOptionalHolder(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = makeOptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAPIOptionalResult") -@_cdecl("bjs_roundTripOptionalAPIOptionalResult") -public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_roundTripPointerFields") @_cdecl("bjs_roundTripPointerFields") public func _bjs_roundTripPointerFields() -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 74ecd9d50..1d55eb479 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -8011,14 +8011,31 @@ }, { "cases" : [ + + ], + "emitStyle" : "const", + "name" : "OptionalSupportExports", + "staticMethods" : [ { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalString", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalString", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "swiftStruct" : { - "_0" : "Address" + "string" : { + } }, "_1" : "null" @@ -8026,16 +8043,42 @@ } } ], - "name" : "optStruct" + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalInt", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalInt", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "int" : { + } }, "_1" : "null" @@ -8043,15 +8086,41 @@ } } ], - "name" : "optClass" + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalBool", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalBool", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "jsObject" : { + "bool" : { } }, @@ -8060,16 +8129,42 @@ } } ], - "name" : "optJSObject" + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalFloat", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalFloat", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "float" : { + } }, "_1" : "null" @@ -8077,20 +8172,42 @@ } } ], - "name" : "optNestedEnum" + "returnType" : { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalDouble", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalDouble", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "array" : { - "_0" : { - "int" : { + "double" : { - } - } } }, "_1" : "null" @@ -8098,16 +8215,42 @@ } } ], - "name" : "optArray" + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalSyntax", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalSyntax", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "jsObject" : { - "_0" : "Foo" + "string" : { + } }, "_1" : "null" @@ -8115,36 +8258,42 @@ } } ], - "name" : "optJsClass" + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ - + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalCaseEnum", + "namespace" : [ + "OptionalSupportExports" ], - "name" : "empty" - } - ], - "emitStyle" : "const", - "name" : "OptionalAllTypesResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "OptionalAllTypesResult", - "tsFullPath" : "OptionalAllTypesResult" - }, - { - "cases" : [ - { - "associatedValues" : [ + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "string" : { - + "caseEnum" : { + "_0" : "Status" } }, "_1" : "null" @@ -8152,69 +8301,220 @@ } } ], - "name" : "success" + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStringRawValueEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "int" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } }, "_1" : "null" } } - }, - { - "type" : { - "nullable" : { - "_0" : { - "bool" : { - - } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalIntRawValueEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, "_1" : "null" } } } ], - "name" : "failure" + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } }, { - "associatedValues" : [ + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalTSEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalTSEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "bool" : { - + "caseEnum" : { + "_0" : "TSDirection" } }, "_1" : "null" } } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "TSDirection" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalTSStringEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "int" : { - + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } }, "_1" : "null" } } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalNamespacedEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ { + "label" : "_", + "name" : "v", "type" : { "nullable" : { "_0" : { - "string" : { - + "caseEnum" : { + "_0" : "Networking.API.Method" } }, "_1" : "null" @@ -8222,1697 +8522,1711 @@ } } ], - "name" : "status" - } - ], - "emitStyle" : "const", - "name" : "APIOptionalResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIOptionalResult", - "tsFullPath" : "APIOptionalResult" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundTripVoid", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripVoid", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "int" : { - + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_roundTripUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUInt", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "uint" : { - + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalSwiftClass", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "uint" : { - - } - } - }, - { - "abiName" : "bjs_roundTripFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripFloat", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "float" : { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalIntArray", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_roundTripDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDouble", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "double" : { + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_roundTripBool", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripBool", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "bool" : { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStringArray", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_roundTripString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripString", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "string" : { + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_roundTripSwiftHeapObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSwiftHeapObject", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalSwiftClassArray", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "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" + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalAPIResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } } } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripUnsafeMutableRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUnsafeMutableRawPointer", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalTypedPayloadResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { "_0" : { - "kind" : "unsafeMutableRawPointer" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalComplexResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalComplexResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" + } } } - } - } - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "abiName" : "bjs_roundTripOpaquePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOpaquePointer", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { + ], + "returnType" : { + "nullable" : { "_0" : { - "kind" : "opaquePointer" - } + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "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" + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalAllTypesResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + }, + "_1" : "null" + } } } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } } - } - ], - "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" + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalPayloadResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } } } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } } - } - ], - "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" : { - + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalPayloadResultOpt", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "jsObject" : { - - } - } - }, - { - "abiName" : "bjs_roundTripDictionaryExport", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDictionaryExport", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "dictionary" : { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalAPIOptionalResult", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { "_0" : { - "int" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_takeOptionalJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "takeOptionalJSObject", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + } + }, + "_1" : "null" } } } - } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "int" : { + ], + "returnType" : { + "void" : { } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalDictionaryExport", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalDictionaryExport", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "dictionary" : { + "abiName" : "bjs_OptionalSupportExports_static_applyOptionalGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "applyOptionalGreeter", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { "_0" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } - } + }, + "_1" : "null" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" } }, "_1" : "null" } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { + }, + { + "abiName" : "bjs_OptionalSupportExports_static_makeOptionalHolder", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "makeOptionalHolder", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "nullableGreeter", + "name" : "nullableGreeter", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + }, + { + "label" : "undefinedNumber", + "name" : "undefinedNumber", + "type" : { + "nullable" : { + "_0" : { + "double" : { + } + }, + "_1" : "undefined" } } } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "OptionalHolder" + } }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_roundTripJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripJSValue", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "jsValue" : { - + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } - } - ], - "returnType" : { - "jsValue" : { - - } - } - }, - { - "abiName" : "bjs_roundTripOptionalJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalJSValue", - "parameters" : [ + }, { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "jsValue" : { - + "abiName" : "bjs_OptionalSupportExports_static_compareAPIResults", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "compareAPIResults", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "r1", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } - }, - "_1" : "null" + } + }, + { + "label" : "_", + "name" : "r2", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" } } } ], - "returnType" : { - "nullable" : { - "_0" : { - "jsValue" : { + "staticProperties" : [ - } - }, - "_1" : "null" - } - } + ], + "swiftCallName" : "OptionalSupportExports", + "tsFullPath" : "OptionalSupportExports" }, { - "abiName" : "bjs_roundTripOptionalJSValueArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalJSValueArray", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "array" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { "_0" : { - "jsValue" : { - + "swiftStruct" : { + "_0" : "Address" } - } + }, + "_1" : "null" } - }, - "_1" : "null" + } } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { - + ], + "name" : "optStruct" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } } - }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_makeImportedFoo", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "makeImportedFoo", - "parameters" : [ + ], + "name" : "optClass" + }, { - "label" : "value", - "name" : "value", - "type" : { - "string" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "jsObject" : { - "_0" : "Foo" - } - } - }, - { - "abiName" : "bjs_throwsSwiftError", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsSwiftError", - "parameters" : [ + ], + "name" : "optJSObject" + }, { - "label" : "shouldThrow", - "name" : "shouldThrow", - "type" : { - "bool" : { - + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_throwsWithIntResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithIntResult", - "parameters" : [ - - ], - "returnType" : { - "int" : { - - } - } - }, - { - "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" : true - }, - "name" : "throwsWithFloatResult", - "parameters" : [ - - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_throwsWithDoubleResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithDoubleResult", - "parameters" : [ + ], + "name" : "optNestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { - ], - "returnType" : { - "double" : { + } + } + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optArray" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optJsClass" + }, + { + "associatedValues" : [ + ], + "name" : "empty" } - } - }, - { - "abiName" : "bjs_throwsWithSwiftHeapObjectResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithSwiftHeapObjectResult", - "parameters" : [ - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "abiName" : "bjs_throwsWithJSObjectResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsWithJSObjectResult", - "parameters" : [ + "emitStyle" : "const", + "name" : "OptionalAllTypesResult", + "staticMethods" : [ ], - "returnType" : { - "jsObject" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripVoid", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripVoid", - "parameters" : [ + "staticProperties" : [ ], - "returnType" : { - "void" : { - - } - } + "swiftCallName" : "OptionalAllTypesResult", + "tsFullPath" : "OptionalAllTypesResult" }, { - "abiName" : "bjs_asyncRoundTripInt", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripInt", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "int" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripFloat", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripFloat", - "parameters" : [ + ], + "name" : "success" + }, { - "label" : "v", - "name" : "v", - "type" : { - "float" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "int" : { - } - } - } - ], - "returnType" : { - "float" : { + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { - } - } - }, - { - "abiName" : "bjs_asyncRoundTripDouble", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripDouble", - "parameters" : [ + } + }, + "_1" : "null" + } + } + } + ], + "name" : "failure" + }, { - "label" : "v", - "name" : "v", - "type" : { - "double" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { - } - } - } - ], - "returnType" : { - "double" : { + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "int" : { - } - } - }, - { - "abiName" : "bjs_asyncRoundTripBool", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripBool", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "bool" : { + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" + } + } } - } + ], + "name" : "status" } ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripString", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripString", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "string" : { + "emitStyle" : "const", + "name" : "APIOptionalResult", + "staticMethods" : [ - } - } - } ], - "returnType" : { - "string" : { + "staticProperties" : [ - } - } - }, + ], + "swiftCallName" : "APIOptionalResult", + "tsFullPath" : "APIOptionalResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ { - "abiName" : "bjs_asyncRoundTripSwiftHeapObject", + "abiName" : "bjs_roundTripVoid", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripSwiftHeapObject", + "name" : "roundTripVoid", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } + ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "void" : { + } } }, { - "abiName" : "bjs_asyncRoundTripJSObject", + "abiName" : "bjs_roundTripInt", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripJSObject", + "name" : "roundTripInt", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "jsObject" : { + "int" : { } } } ], "returnType" : { - "jsObject" : { + "int" : { } } }, { - "abiName" : "bjs_takeGreeter", + "abiName" : "bjs_roundTripUInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "takeGreeter", + "name" : "roundTripUInt", "parameters" : [ { - "label" : "g", - "name" : "g", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "label" : "name", - "name" : "name", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "uint" : { } } } ], "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_createCalculator", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createCalculator", - "parameters" : [ + "uint" : { - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Calculator" } } }, { - "abiName" : "bjs_useCalculator", + "abiName" : "bjs_roundTripFloat", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "useCalculator", + "name" : "roundTripFloat", "parameters" : [ { - "label" : "calc", - "name" : "calc", - "type" : { - "swiftHeapObject" : { - "_0" : "Calculator" - } - } - }, - { - "label" : "x", - "name" : "x", - "type" : { - "int" : { - - } - } - }, - { - "label" : "y", - "name" : "y", + "label" : "v", + "name" : "v", "type" : { - "int" : { + "float" : { } } } ], "returnType" : { - "int" : { + "float" : { } } }, { - "abiName" : "bjs_testGreeterToJSValue", + "abiName" : "bjs_roundTripDouble", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testGreeterToJSValue", + "name" : "roundTripDouble", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "double" : { - ], - "returnType" : { - "jsObject" : { - + } + } } - } - }, - { - "abiName" : "bjs_testCalculatorToJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testCalculatorToJSValue", - "parameters" : [ - ], "returnType" : { - "jsObject" : { + "double" : { } } }, { - "abiName" : "bjs_testSwiftClassAsJSValue", + "abiName" : "bjs_roundTripBool", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testSwiftClassAsJSValue", + "name" : "roundTripBool", "parameters" : [ { - "label" : "greeter", - "name" : "greeter", + "label" : "v", + "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "bool" : { + } } } ], "returnType" : { - "jsObject" : { + "bool" : { } } }, { - "abiName" : "bjs_setDirection", + "abiName" : "bjs_roundTripString", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setDirection", + "name" : "roundTripString", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "string" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" - } - } - }, - { - "abiName" : "bjs_getDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getDirection", - "parameters" : [ + "string" : { - ], - "returnType" : { - "caseEnum" : { - "_0" : "Direction" } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "roundTripSwiftHeapObject", "parameters" : [ { - "label" : "_", - "name" : "input", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_roundTripUnsafeRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "roundTripUnsafeRawPointer", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - }, - { - "abiName" : "bjs_getTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTheme", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } }, { - "abiName" : "bjs_setHttpStatus", + "abiName" : "bjs_roundTripUnsafeMutableRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setHttpStatus", + "name" : "roundTripUnsafeMutableRawPointer", "parameters" : [ { - "label" : "_", - "name" : "status", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } }, { - "abiName" : "bjs_getHttpStatus", + "abiName" : "bjs_roundTripOpaquePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getHttpStatus", + "name" : "roundTripOpaquePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } } } }, { - "abiName" : "bjs_processTheme", + "abiName" : "bjs_roundTripUnsafePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processTheme", + "name" : "roundTripUnsafePointer", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_setTSDirection", + "abiName" : "bjs_roundTripUnsafeMutablePointer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSDirection", + "name" : "roundTripUnsafeMutablePointer", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "TSDirection" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_getTSDirection", + "abiName" : "bjs_roundTripJSObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSDirection", + "name" : "roundTripJSObject", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "jsObject" : { + } } }, { - "abiName" : "bjs_setTSTheme", + "abiName" : "bjs_roundTripDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTSTheme", + "name" : "roundTripDictionaryExport", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "dictionary" : { + "_0" : { + "int" : { + + } + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "dictionary" : { + "_0" : { + "int" : { + + } + } } } }, { - "abiName" : "bjs_getTSTheme", + "abiName" : "bjs_roundTripOptionalDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTSTheme", + "name" : "roundTripOptionalDictionaryExport", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_createConverter", + "abiName" : "bjs_roundTripJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createConverter", + "name" : "roundTripJSValue", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsValue" : { + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "jsValue" : { + } } }, { - "abiName" : "bjs_useConverter", + "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "useConverter", + "name" : "roundTripOptionalJSValue", "parameters" : [ { - "label" : "converter", - "name" : "converter", - "type" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" - } - } - }, - { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "int" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripConverterArray", + "abiName" : "bjs_roundTripOptionalJSValueArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripConverterArray", + "name" : "roundTripOptionalJSValueArray", "parameters" : [ { - "label" : "_", - "name" : "converters", + "label" : "v", + "name" : "v", "type" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "array" : { + "_0" : { + "jsValue" : { + + } + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Utils.Converter" + "array" : { + "_0" : { + "jsValue" : { + + } + } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_createHTTPServer", + "abiName" : "bjs_makeImportedFoo", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "createHTTPServer", + "name" : "makeImportedFoo", "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Networking.API.HTTPServer" + "jsObject" : { + "_0" : "Foo" } } }, { - "abiName" : "bjs_createUUID", + "abiName" : "bjs_throwsSwiftError", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "createUUID", + "name" : "throwsSwiftError", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "shouldThrow", + "name" : "shouldThrow", "type" : { - "string" : { + "bool" : { } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "void" : { + } } }, { - "abiName" : "bjs_roundTripUUID", + "abiName" : "bjs_throwsWithIntResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripUUID", + "name" : "throwsWithIntResult", "parameters" : [ - { - "label" : "_", - "name" : "uuid", - "type" : { - "swiftHeapObject" : { - "_0" : "UUID" - } - } - } + ], "returnType" : { - "swiftHeapObject" : { - "_0" : "UUID" + "int" : { + } } }, { - "abiName" : "bjs_roundtripNetworkingAPIMethod", + "abiName" : "bjs_throwsWithStringResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripNetworkingAPIMethod", + "name" : "throwsWithStringResult", "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Networking.API.Method" + "string" : { + } } }, { - "abiName" : "bjs_roundtripConfigurationLogLevel", + "abiName" : "bjs_throwsWithBoolResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripConfigurationLogLevel", + "name" : "throwsWithBoolResult", "parameters" : [ - { - "label" : "_", - "name" : "level", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" + "bool" : { + } } }, { - "abiName" : "bjs_roundtripConfigurationPort", + "abiName" : "bjs_throwsWithFloatResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripConfigurationPort", + "name" : "throwsWithFloatResult", "parameters" : [ - { - "label" : "_", - "name" : "port", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" + "float" : { + } } }, { - "abiName" : "bjs_processConfigurationLogLevel", + "abiName" : "bjs_throwsWithDoubleResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "processConfigurationLogLevel", + "name" : "throwsWithDoubleResult", "parameters" : [ - { - "label" : "_", - "name" : "level", - "type" : { - "rawValueEnum" : { - "_0" : "Configuration.LogLevel", - "_1" : "String" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "Configuration.Port", - "_1" : "Int" + "double" : { + } } }, { - "abiName" : "bjs_roundtripInternalSupportedMethod", + "abiName" : "bjs_throwsWithSwiftHeapObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripInternalSupportedMethod", + "name" : "throwsWithSwiftHeapObjectResult", "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_roundtripAPIResult", + "abiName" : "bjs_throwsWithJSObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundtripAPIResult", + "name" : "throwsWithJSObjectResult", "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeAPIResultSuccess", + "abiName" : "bjs_asyncRoundTripVoid", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultSuccess", + "name" : "asyncRoundTripVoid", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "void" : { + } } }, { - "abiName" : "bjs_makeAPIResultFailure", + "abiName" : "bjs_asyncRoundTripInt", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultFailure", + "name" : "asyncRoundTripInt", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { "int" : { @@ -9921,251 +10235,233 @@ } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "int" : { + } } }, { - "abiName" : "bjs_makeAPIResultInfo", + "abiName" : "bjs_asyncRoundTripFloat", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultInfo", + "name" : "asyncRoundTripFloat", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "float" : { + } + } + } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "float" : { + } } }, { - "abiName" : "bjs_makeAPIResultFlag", + "abiName" : "bjs_asyncRoundTripDouble", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultFlag", + "name" : "asyncRoundTripDouble", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "bool" : { + "double" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "double" : { + } } }, { - "abiName" : "bjs_makeAPIResultRate", + "abiName" : "bjs_asyncRoundTripBool", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultRate", + "name" : "asyncRoundTripBool", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "float" : { + "bool" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "bool" : { + } } }, { - "abiName" : "bjs_makeAPIResultPrecise", + "abiName" : "bjs_asyncRoundTripString", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPIResultPrecise", + "name" : "asyncRoundTripString", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "double" : { + "string" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "string" : { + } } }, { - "abiName" : "bjs_roundtripComplexResult", + "abiName" : "bjs_asyncRoundTripSwiftHeapObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripComplexResult", + "name" : "asyncRoundTripSwiftHeapObject", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "v", + "name" : "v", "type" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_makeComplexResultSuccess", + "abiName" : "bjs_asyncRoundTripJSObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultSuccess", + "name" : "asyncRoundTripJSObject", "parameters" : [ { - "label" : "_", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "jsObject" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeComplexResultError", + "abiName" : "bjs_takeGreeter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultError", + "name" : "takeGreeter", "parameters" : [ { - "label" : "_", - "name" : "message", + "label" : "g", + "name" : "g", "type" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "label" : "_", - "name" : "code", + "label" : "name", + "name" : "name", "type" : { - "int" : { + "string" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "void" : { + } } }, { - "abiName" : "bjs_makeComplexResultLocation", + "abiName" : "bjs_createCalculator", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultLocation", + "name" : "createCalculator", "parameters" : [ - { - "label" : "_", - "name" : "lat", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "lng", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "name", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "abiName" : "bjs_makeComplexResultStatus", + "abiName" : "bjs_useCalculator", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultStatus", + "name" : "useCalculator", "parameters" : [ { - "label" : "_", - "name" : "active", + "label" : "calc", + "name" : "calc", "type" : { - "bool" : { - + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "label" : "_", - "name" : "code", + "label" : "x", + "name" : "x", "type" : { "int" : { @@ -10173,1798 +10469,1555 @@ } }, { - "label" : "_", - "name" : "message", + "label" : "y", + "name" : "y", "type" : { - "string" : { + "int" : { } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "int" : { + } } }, { - "abiName" : "bjs_makeComplexResultCoordinates", + "abiName" : "bjs_testGreeterToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultCoordinates", + "name" : "testGreeterToJSValue", "parameters" : [ - { - "label" : "_", - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "label" : "_", - "name" : "y", - "type" : { - "double" : { - } - } - }, - { - "label" : "_", - "name" : "z", - "type" : { - "double" : { - - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "jsObject" : { + } } }, { - "abiName" : "bjs_makeComplexResultComprehensive", + "abiName" : "bjs_testCalculatorToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultComprehensive", + "name" : "testCalculatorToJSValue", "parameters" : [ - { - "label" : "_", - "name" : "flag1", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "flag2", - "type" : { - "bool" : { - } - } - }, - { - "label" : "_", - "name" : "count1", - "type" : { - "int" : { + ], + "returnType" : { + "jsObject" : { - } - } - }, + } + } + }, + { + "abiName" : "bjs_testSwiftClassAsJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testSwiftClassAsJSValue", + "parameters" : [ { - "label" : "_", - "name" : "count2", + "label" : "greeter", + "name" : "greeter", "type" : { - "int" : { - + "swiftHeapObject" : { + "_0" : "Greeter" } } - }, - { - "label" : "_", - "name" : "value1", - "type" : { - "double" : { + } + ], + "returnType" : { + "jsObject" : { - } - } - }, + } + } + }, + { + "abiName" : "bjs_setDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setDirection", + "parameters" : [ { "label" : "_", - "name" : "value2", + "name" : "direction", "type" : { - "double" : { - + "caseEnum" : { + "_0" : "Direction" } } - }, - { - "label" : "_", - "name" : "text1", - "type" : { - "string" : { + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "abiName" : "bjs_getDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getDirection", + "parameters" : [ - } - } - }, + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "abiName" : "bjs_processDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDirection", + "parameters" : [ { "label" : "_", - "name" : "text2", + "name" : "input", "type" : { - "string" : { - + "caseEnum" : { + "_0" : "Direction" } } - }, + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "abiName" : "bjs_setTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTheme", + "parameters" : [ { "label" : "_", - "name" : "text3", + "name" : "theme", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_makeComplexResultInfo", + "abiName" : "bjs_getTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeComplexResultInfo", + "name" : "getTheme", "parameters" : [ ], "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_makeUtilitiesResultSuccess", + "abiName" : "bjs_setHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultSuccess", + "name" : "setHttpStatus", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "status", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeUtilitiesResultFailure", + "abiName" : "bjs_getHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultFailure", + "name" : "getHttpStatus", "parameters" : [ - { - "label" : "_", - "name" : "error", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "code", - "type" : { - "int" : { - } - } - } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeUtilitiesResultStatus", + "abiName" : "bjs_processTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeUtilitiesResultStatus", + "name" : "processTheme", "parameters" : [ { "label" : "_", - "name" : "active", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "_", - "name" : "code", - "type" : { - "int" : { - - } - } - }, - { - "label" : "_", - "name" : "message", + "name" : "theme", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeAPINetworkingResultSuccess", + "abiName" : "bjs_setTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultSuccess", + "name" : "setTSDirection", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "direction", "type" : { - "string" : { - + "caseEnum" : { + "_0" : "TSDirection" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "caseEnum" : { + "_0" : "TSDirection" } } }, { - "abiName" : "bjs_makeAPINetworkingResultFailure", + "abiName" : "bjs_getTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAPINetworkingResultFailure", + "name" : "getTSDirection", "parameters" : [ - { - "label" : "_", - "name" : "error", - "type" : { - "string" : { - } - } - }, + ], + "returnType" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + }, + { + "abiName" : "bjs_setTSTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSTheme", + "parameters" : [ { "label" : "_", - "name" : "code", + "name" : "theme", "type" : { - "int" : { - + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundtripUtilitiesResult", + "abiName" : "bjs_getTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripUtilitiesResult", + "name" : "getTSTheme", "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" - } - } + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } + } + }, + { + "abiName" : "bjs_createConverter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createConverter", + "parameters" : [ + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" + "swiftHeapObject" : { + "_0" : "Utils.Converter" } } }, { - "abiName" : "bjs_roundtripAPINetworkingResult", + "abiName" : "bjs_useConverter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundtripAPINetworkingResult", + "name" : "useConverter", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "converter", + "name" : "converter", "type" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } + }, + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "API.NetworkingResult" + "string" : { + } } }, { - "abiName" : "bjs_roundTripAllTypesResult", + "abiName" : "bjs_roundTripConverterArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripAllTypesResult", + "name" : "roundTripConverterArray", "parameters" : [ { "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + "name" : "converters", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Utils.Converter" + } + } } } }, { - "abiName" : "bjs_roundTripTypedPayloadResult", + "abiName" : "bjs_createHTTPServer", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripTypedPayloadResult", + "name" : "createHTTPServer", "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" - } - } - } + ], "returnType" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" + "swiftHeapObject" : { + "_0" : "Networking.API.HTTPServer" } } }, { - "abiName" : "bjs_createPropertyHolder", + "abiName" : "bjs_createUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createPropertyHolder", + "name" : "createUUID", "parameters" : [ { - "label" : "intValue", - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "label" : "floatValue", - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "label" : "doubleValue", - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "label" : "boolValue", - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "stringValue", - "name" : "stringValue", + "label" : "value", + "name" : "value", "type" : { "string" : { - } - } - }, - { - "label" : "jsObject", - "name" : "jsObject", - "type" : { - "jsObject" : { - } } } ], "returnType" : { "swiftHeapObject" : { - "_0" : "PropertyHolder" + "_0" : "UUID" } } }, { - "abiName" : "bjs_testPropertyHolder", + "abiName" : "bjs_roundTripUUID", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testPropertyHolder", + "name" : "roundTripUUID", "parameters" : [ { - "label" : "holder", - "name" : "holder", + "label" : "_", + "name" : "uuid", "type" : { "swiftHeapObject" : { - "_0" : "PropertyHolder" + "_0" : "UUID" } } } ], "returnType" : { - "string" : { - + "swiftHeapObject" : { + "_0" : "UUID" } } }, { - "abiName" : "bjs_resetObserverCounts", + "abiName" : "bjs_roundtripNetworkingAPIMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "resetObserverCounts", + "name" : "roundtripNetworkingAPIMethod", "parameters" : [ - + { + "label" : "_", + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + } + } ], "returnType" : { - "void" : { - + "caseEnum" : { + "_0" : "Networking.API.Method" } } }, { - "abiName" : "bjs_getObserverStats", + "abiName" : "bjs_roundtripConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getObserverStats", + "name" : "roundtripConfigurationLogLevel", "parameters" : [ - + { + "label" : "_", + "name" : "level", + "type" : { + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" + } + } + } ], "returnType" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } }, { - "abiName" : "bjs_formatName", + "abiName" : "bjs_roundtripConfigurationPort", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "formatName", + "name" : "roundtripConfigurationPort", "parameters" : [ { "label" : "_", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "label" : "transform", - "name" : "transform", + "name" : "port", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - "useJSTypedClosure" : false + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } } ], "returnType" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeFormatter", + "abiName" : "bjs_processConfigurationLogLevel", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeFormatter", + "name" : "processConfigurationLogLevel", "parameters" : [ { - "label" : "prefix", - "name" : "prefix", + "label" : "_", + "name" : "level", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Configuration.LogLevel", + "_1" : "String" } } } ], "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - "useJSTypedClosure" : false + "rawValueEnum" : { + "_0" : "Configuration.Port", + "_1" : "Int" } } }, { - "abiName" : "bjs_makeAdder", + "abiName" : "bjs_roundtripInternalSupportedMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAdder", + "name" : "roundtripInternalSupportedMethod", "parameters" : [ { - "label" : "base", - "name" : "base", + "label" : "_", + "name" : "method", "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "int" : { - - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - "useJSTypedClosure" : false + "caseEnum" : { + "_0" : "Internal.SupportedMethod" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Internal.SupportedMethod" } } }, { - "abiName" : "bjs_roundTripOptionalIntArrayType", + "abiName" : "bjs_roundtripAPIResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalIntArrayType", + "name" : "roundtripAPIResult", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "result", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalStringArrayType", + "abiName" : "bjs_makeAPIResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStringArrayType", + "name" : "makeAPIResultSuccess", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "string" : { + "string" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalGreeterArrayType", + "abiName" : "bjs_makeAPIResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalGreeterArrayType", + "name" : "makeAPIResultFailure", "parameters" : [ { "label" : "_", - "name" : "greeters", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - }, - "_1" : "null" + "int" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalString", + "abiName" : "bjs_makeAPIResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalString", + "name" : "makeAPIResultInfo", "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "nullable" : { - "_0" : { - "string" : { - } - }, - "_1" : "null" - } - } - } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalInt", + "abiName" : "bjs_makeAPIResultFlag", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalInt", + "name" : "makeAPIResultFlag", "parameters" : [ { - "label" : "value", + "label" : "_", "name" : "value", "type" : { - "nullable" : { - "_0" : { - "int" : { + "bool" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "int" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalBool", + "abiName" : "bjs_makeAPIResultRate", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalBool", + "name" : "makeAPIResultRate", "parameters" : [ { - "label" : "flag", - "name" : "flag", + "label" : "_", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "bool" : { + "float" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "bool" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalFloat", + "abiName" : "bjs_makeAPIResultPrecise", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalFloat", + "name" : "makeAPIResultPrecise", "parameters" : [ { - "label" : "number", - "name" : "number", + "label" : "_", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "float" : { + "double" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "float" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "APIResult" } } }, { - "abiName" : "bjs_roundTripOptionalDouble", + "abiName" : "bjs_roundtripComplexResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDouble", + "name" : "roundtripComplexResult", "parameters" : [ { - "label" : "precision", - "name" : "precision", + "label" : "_", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "double" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "double" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalSyntax", + "abiName" : "bjs_makeComplexResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalSyntax", + "name" : "makeComplexResultSuccess", "parameters" : [ { - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "value", "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalMixSyntax", + "abiName" : "bjs_makeComplexResultError", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalMixSyntax", + "name" : "makeComplexResultError", "parameters" : [ { - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "message", "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalSwiftSyntax", + "abiName" : "bjs_makeComplexResultLocation", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalSwiftSyntax", + "name" : "makeComplexResultLocation", "parameters" : [ { - "label" : "name", + "label" : "_", + "name" : "lat", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "lng", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", "name" : "name", "type" : { - "nullable" : { - "_0" : { - "string" : { + "string" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalWithSpaces", + "abiName" : "bjs_makeComplexResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalWithSpaces", + "name" : "makeComplexResultStatus", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "active", "type" : { - "nullable" : { - "_0" : { - "double" : { + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "double" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalTypeAlias", + "abiName" : "bjs_makeComplexResultCoordinates", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTypeAlias", + "name" : "makeComplexResultCoordinates", "parameters" : [ { - "label" : "age", - "name" : "age", + "label" : "_", + "name" : "x", "type" : { - "nullable" : { - "_0" : { - "int" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "z", + "type" : { + "double" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "int" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalStatus", + "abiName" : "bjs_makeComplexResultComprehensive", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStatus", + "name" : "makeComplexResultComprehensive", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "flag1", "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - }, - "_1" : "null" + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "flag2", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "count1", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "count2", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "value1", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "value2", + "type" : { + "double" : { + + } + } + }, + { + "label" : "_", + "name" : "text1", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "text2", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "text3", + "type" : { + "string" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalTheme", + "abiName" : "bjs_makeComplexResultInfo", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTheme", + "name" : "makeComplexResultInfo", "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - }, - "_1" : "null" - } - } - } + ], "returnType" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "ComplexResult" } } }, { - "abiName" : "bjs_roundTripOptionalHttpStatus", + "abiName" : "bjs_makeUtilitiesResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalHttpStatus", + "name" : "makeUtilitiesResultSuccess", "parameters" : [ { - "label" : "value", - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - }, - "_1" : "null" + "label" : "_", + "name" : "message", + "type" : { + "string" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_roundTripOptionalTSDirection", + "abiName" : "bjs_makeUtilitiesResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTSDirection", + "name" : "makeUtilitiesResultFailure", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "error", "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - }, - "_1" : "null" + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_roundTripOptionalTSTheme", + "abiName" : "bjs_makeUtilitiesResultStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTSTheme", + "name" : "makeUtilitiesResultStatus", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "active", "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - }, - "_1" : "null" + "bool" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + + } + } + }, + { + "label" : "_", + "name" : "message", + "type" : { + "string" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_roundTripOptionalNetworkingAPIMethod", + "abiName" : "bjs_makeAPINetworkingResultSuccess", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalNetworkingAPIMethod", + "name" : "makeAPINetworkingResultSuccess", "parameters" : [ { "label" : "_", - "name" : "method", + "name" : "message", "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - }, - "_1" : "null" + "string" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_roundTripOptionalAPIResult", + "abiName" : "bjs_makeAPINetworkingResultFailure", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalAPIResult", + "name" : "makeAPINetworkingResultFailure", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "error", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "code", + "type" : { + "int" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_roundTripOptionalTypedPayloadResult", + "abiName" : "bjs_roundtripUtilitiesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTypedPayloadResult", + "name" : "roundtripUtilitiesResult", "parameters" : [ { "label" : "_", "name" : "result", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "TypedPayloadResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Utilities.Result" } } }, { - "abiName" : "bjs_takeOptionalJSObject", + "abiName" : "bjs_roundtripAPINetworkingResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "takeOptionalJSObject", + "name" : "roundtripAPINetworkingResult", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "jsObject" : { - - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } } ], "returnType" : { - "void" : { - + "associatedValueEnum" : { + "_0" : "API.NetworkingResult" } } }, { - "abiName" : "bjs_compareAPIResults", + "abiName" : "bjs_roundTripAllTypesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "compareAPIResults", + "name" : "roundTripAllTypesResult", "parameters" : [ { "label" : "_", - "name" : "r1", - "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" - } - } - }, - { - "label" : "_", - "name" : "r2", + "name" : "result", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } } ], "returnType" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } }, { - "abiName" : "bjs_roundTripOptionalComplexResult", + "abiName" : "bjs_roundTripTypedPayloadResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalComplexResult", + "name" : "roundTripTypedPayloadResult", "parameters" : [ { "label" : "_", "name" : "result", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } }, { - "abiName" : "bjs_roundTripOptionalAllTypesResult", + "abiName" : "bjs_createPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalAllTypesResult", + "name" : "createPropertyHolder", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "intValue", + "name" : "intValue", + "type" : { + "int" : { + + } + } + }, + { + "label" : "floatValue", + "name" : "floatValue", + "type" : { + "float" : { + + } + } + }, + { + "label" : "doubleValue", + "name" : "doubleValue", + "type" : { + "double" : { + + } + } + }, + { + "label" : "boolValue", + "name" : "boolValue", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" - } - }, - "_1" : "null" + "bool" : { + } } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "AllTypesResult" + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { + } - }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalPayloadResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalPayloadResult", - "parameters" : [ + } + }, { - "label" : "_", - "name" : "result", + "label" : "jsObject", + "name" : "jsObject", "type" : { - "associatedValueEnum" : { - "_0" : "OptionalAllTypesResult" + "jsObject" : { + } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "OptionalAllTypesResult" + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } }, { - "abiName" : "bjs_roundTripOptionalPayloadResultOpt", + "abiName" : "bjs_testPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalPayloadResultOpt", + "name" : "testPropertyHolder", "parameters" : [ { - "label" : "_", - "name" : "result", + "label" : "holder", + "name" : "holder", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "OptionalAllTypesResult" - } - }, - "_1" : "null" + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "OptionalAllTypesResult" - } - }, - "_1" : "null" + "string" : { + } } }, { - "abiName" : "bjs_roundTripOptionalClass", + "abiName" : "bjs_resetObserverCounts", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalClass", + "name" : "resetObserverCounts", "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" - } - } - } + ], "returnType" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "void" : { + } } }, { - "abiName" : "bjs_roundTripOptionalGreeter", + "abiName" : "bjs_getObserverStats", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalGreeter", + "name" : "getObserverStats", "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" - } - } - } + ], "returnType" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } }, { - "abiName" : "bjs_applyOptionalGreeter", + "abiName" : "bjs_formatName", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "applyOptionalGreeter", + "name" : "formatName", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "name", "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } }, { - "label" : "_", + "label" : "transform", "name" : "transform", "type" : { "closure" : { "_0" : { "isAsync" : false, "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC", + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } ], "returnType" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } }, @@ -11974,92 +12027,94 @@ } ], "returnType" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } }, { - "abiName" : "bjs_makeOptionalHolder", + "abiName" : "bjs_makeFormatter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeOptionalHolder", + "name" : "makeFormatter", "parameters" : [ { - "label" : "nullableGreeter", - "name" : "nullableGreeter", - "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" - } - } - }, - { - "label" : "undefinedNumber", - "name" : "undefinedNumber", + "label" : "prefix", + "name" : "prefix", "type" : { - "nullable" : { - "_0" : { - "double" : { + "string" : { - } - }, - "_1" : "undefined" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "OptionalHolder" + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false } } }, { - "abiName" : "bjs_roundTripOptionalAPIOptionalResult", + "abiName" : "bjs_makeAdder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalAPIOptionalResult", + "name" : "makeAdder", "parameters" : [ { - "label" : "result", - "name" : "result", + "label" : "base", + "name" : "base", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - }, - "_1" : "null" + "int" : { + } } } ], "returnType" : { - "nullable" : { + "closure" : { "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } } }, - "_1" : "null" + "useJSTypedClosure" : false } } }, diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index 1a41cc43f..aaa05a70a 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -48,9 +48,11 @@ export function getImports(importsContext) { /** * Optional value bridging coverage for BridgeJS runtime tests. - * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports */ -export function runJsOptionalSupportTests(exports) { +export function runJsOptionalSupportTests(rootExports) { + const exports = rootExports.OptionalSupportExports; + const { Status, Theme, HttpStatus, Networking, ComplexResult, APIResult, Greeter, OptionalPropertyHolder, TypedPayloadResult, Direction } = rootExports; assert.equal(exports.roundTripOptionalString(null), null); assert.equal(exports.roundTripOptionalInt(null), null); assert.equal(exports.roundTripOptionalBool(null), null); @@ -65,47 +67,45 @@ export function runJsOptionalSupportTests(exports) { assert.equal(exports.roundTripOptionalSyntax(null), null); assert.equal(exports.roundTripOptionalSyntax('Test'), 'Test'); - assert.equal(exports.roundTripOptionalMixSyntax(null), null); - assert.equal(exports.roundTripOptionalMixSyntax('Mix'), 'Mix'); - assert.equal(exports.roundTripOptionalSwiftSyntax(null), null); - assert.equal(exports.roundTripOptionalSwiftSyntax('Swift'), 'Swift'); - assert.equal(exports.roundTripOptionalWithSpaces(null), null); - assert.equal(exports.roundTripOptionalWithSpaces(1.618), 1.618); - assert.equal(exports.roundTripOptionalTypeAlias(null), null); - assert.equal(exports.roundTripOptionalTypeAlias(25), 25); - assert.equal(exports.roundTripOptionalStatus(exports.Status.Success), StatusValues.Success); - assert.equal(exports.roundTripOptionalTheme(exports.Theme.Light), ThemeValues.Light); - assert.equal(exports.roundTripOptionalHttpStatus(exports.HttpStatus.Ok), HttpStatusValues.Ok); - assert.equal(exports.roundTripOptionalTSDirection(TSDirection.North), TSDirection.North); - assert.equal(exports.roundTripOptionalTSTheme(TSTheme.Light), TSTheme.Light); - assert.equal(exports.roundTripOptionalNetworkingAPIMethod(exports.Networking.API.Method.Get), exports.Networking.API.Method.Get); + assert.equal(exports.roundTripOptionalCaseEnum(Status.Success), StatusValues.Success); + assert.equal(exports.roundTripOptionalStringRawValueEnum(Theme.Light), ThemeValues.Light); + assert.equal(exports.roundTripOptionalIntRawValueEnum(HttpStatus.Ok), HttpStatusValues.Ok); + 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); + + // Optional arrays + assert.deepEqual(exports.roundTripOptionalIntArray([1, 2, 3]), [1, 2, 3]); + assert.equal(exports.roundTripOptionalIntArray(null), null); + assert.deepEqual(exports.roundTripOptionalStringArray(["a", "b"]), ["a", "b"]); + assert.equal(exports.roundTripOptionalStringArray(null), null); const pVal = 3.141592653589793; const p1 = { tag: APIResultValues.Tag.Precise, param0: pVal }; - const cl1 = { tag: exports.ComplexResult.Tag.Location, param0: 37.7749, param1: -122.4194, param2: 'San Francisco' }; + const cl1 = { tag: ComplexResult.Tag.Location, param0: 37.7749, param1: -122.4194, param2: 'San Francisco' }; assert.deepEqual(exports.roundTripOptionalAPIResult(p1), p1); assert.deepEqual(exports.roundTripOptionalComplexResult(cl1), cl1); - const apiSuccess = { tag: exports.APIResult.Tag.Success, param0: 'test success' }; - const apiFailure = { tag: exports.APIResult.Tag.Failure, param0: 404 }; - const apiInfo = { tag: exports.APIResult.Tag.Info }; + const apiSuccess = { tag: APIResult.Tag.Success, param0: 'test success' }; + const apiFailure = { tag: APIResult.Tag.Failure, param0: 404 }; + const apiInfo = { tag: APIResult.Tag.Info }; assert.equal(exports.compareAPIResults(apiSuccess, apiFailure), 'r1:success:test success,r2:failure:404'); assert.equal(exports.compareAPIResults(null, apiInfo), 'r1:nil,r2:info'); assert.equal(exports.compareAPIResults(apiFailure, null), 'r1:failure:404,r2:nil'); assert.equal(exports.compareAPIResults(null, null), 'r1:nil,r2:nil'); - const optionalGreeter = new exports.Greeter('Schrödinger'); - const optionalGreeter2 = exports.roundTripOptionalClass(optionalGreeter); + const optionalGreeter = new Greeter('Schrödinger'); + const optionalGreeter2 = exports.roundTripOptionalSwiftClass(optionalGreeter); assert.equal(optionalGreeter2?.greet() ?? '', 'Hello, Schrödinger!'); assert.equal(optionalGreeter2?.name ?? '', 'Schrödinger'); assert.equal(optionalGreeter2?.prefix ?? '', 'Hello'); - assert.equal(exports.roundTripOptionalClass(null), null); + assert.equal(exports.roundTripOptionalSwiftClass(null), null); optionalGreeter.release(); optionalGreeter2?.release(); - const optionalsHolder = new exports.OptionalPropertyHolder(null); + const optionalsHolder = new OptionalPropertyHolder(null); assert.equal(optionalsHolder.optionalName, null); assert.equal(optionalsHolder.optionalAge, null); @@ -116,7 +116,7 @@ export function runJsOptionalSupportTests(exports) { assert.equal(optionalsHolder.optionalName, 'Alice'); assert.equal(optionalsHolder.optionalAge, 25); - const testPropertyGreeter = new exports.Greeter('Bob'); + const testPropertyGreeter = new Greeter('Bob'); optionalsHolder.optionalGreeter = testPropertyGreeter; assert.equal(optionalsHolder.optionalGreeter.greet(), 'Hello, Bob!'); assert.equal(optionalsHolder.optionalGreeter.name, 'Bob'); @@ -130,14 +130,14 @@ export function runJsOptionalSupportTests(exports) { testPropertyGreeter.release(); optionalsHolder.release(); - const optGreeter = new exports.Greeter('Optionaly'); - assert.equal(exports.roundTripOptionalGreeter(null), null); - const optGreeterReturned = exports.roundTripOptionalGreeter(optGreeter); - assert.equal(optGreeterReturned.name, 'Optionaly'); - assert.equal(optGreeterReturned.greet(), 'Hello, Optionaly!'); + const optGreeter = new Greeter('Optionaly'); + assert.equal(exports.roundTripOptionalSwiftClass(null), null); + const optGreeterReturned = exports.roundTripOptionalSwiftClass(optGreeter); + assert.equal(optGreeterReturned?.name, 'Optionaly'); + assert.equal(optGreeterReturned?.greet(), 'Hello, Optionaly!'); const appliedOptional = exports.applyOptionalGreeter(null, (g) => g ?? optGreeter); - assert.equal(appliedOptional.name, 'Optionaly'); + assert.equal(appliedOptional?.name, 'Optionaly'); const holderOpt = exports.makeOptionalHolder(null, undefined); assert.equal(holderOpt.nullableGreeter, null); @@ -147,7 +147,7 @@ export function runJsOptionalSupportTests(exports) { assert.equal(holderOpt.nullableGreeter.name, 'Optionaly'); assert.equal(holderOpt.undefinedNumber, 123.5); holderOpt.release(); - optGreeterReturned.release(); + optGreeterReturned?.release(); optGreeter.release(); const aor1 = { tag: APIOptionalResultValues.Tag.Success, param0: 'hello world' }; @@ -174,15 +174,25 @@ export function runJsOptionalSupportTests(exports) { assert.equal(exports.roundTripOptionalAPIOptionalResult(null), null); // Optional TypedPayloadResult roundtrip - const tpr_precision = { tag: exports.TypedPayloadResult.Tag.Precision, param0: Math.fround(0.1) }; + /** + * @typedef {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').TypedPayloadResultTag} TypedPayloadResultTag + * @typedef {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').PrecisionTag} PrecisionTag + */ + + /** @type {TypedPayloadResultTag} */ + const tpr_precision = { tag: TypedPayloadResult.Tag.Precision, param0: /** @type {PrecisionTag} */ (Math.fround(0.1)) }; assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_precision), tpr_precision); - const tpr_direction = { tag: exports.TypedPayloadResult.Tag.Direction, param0: exports.Direction.North }; + /** @type {TypedPayloadResultTag} */ + const tpr_direction = { tag: TypedPayloadResult.Tag.Direction, param0: Direction.North }; assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_direction), tpr_direction); - const tpr_optPrecisionSome = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: Math.fround(0.001) }; + /** @type {TypedPayloadResultTag} */ + const tpr_optPrecisionSome = { tag: TypedPayloadResult.Tag.OptPrecision, param0: /** @type {PrecisionTag} */ (Math.fround(0.001)) }; assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_optPrecisionSome), tpr_optPrecisionSome); - const tpr_optPrecisionNull = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: null }; + /** @type {TypedPayloadResultTag} */ + const tpr_optPrecisionNull = { tag: TypedPayloadResult.Tag.OptPrecision, param0: null }; assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_optPrecisionNull), tpr_optPrecisionNull); - const tpr_empty = { tag: exports.TypedPayloadResult.Tag.Empty }; + /** @type {TypedPayloadResultTag} */ + const tpr_empty = { tag: TypedPayloadResult.Tag.Empty }; assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_empty), tpr_empty); assert.equal(exports.roundTripOptionalTypedPayloadResult(null), null); @@ -202,10 +212,12 @@ export function runJsOptionalSupportTests(exports) { const oatr_structNone = { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: null }; assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_structNone), oatr_structNone); - const oatr_classSome = { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: new exports.Greeter("OptEnumUser") }; + const oatr_classSome = { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: new Greeter("OptEnumUser") }; const oatr_classSome_result = exports.roundTripOptionalPayloadResult(oatr_classSome); assert.equal(oatr_classSome_result.tag, OptionalAllTypesResultValues.Tag.OptClass); - assert.equal(oatr_classSome_result.param0.name, "OptEnumUser"); + if (oatr_classSome_result.tag === OptionalAllTypesResultValues.Tag.OptClass) { + assert.equal(oatr_classSome_result.param0?.name, "OptEnumUser"); + } const oatr_classNone = { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: null }; assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_classNone), oatr_classNone); @@ -213,7 +225,9 @@ export function runJsOptionalSupportTests(exports) { const oatr_jsObjectSome = { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: { key: "value" } }; const oatr_jsObjectSome_result = exports.roundTripOptionalPayloadResult(oatr_jsObjectSome); assert.equal(oatr_jsObjectSome_result.tag, OptionalAllTypesResultValues.Tag.OptJSObject); - assert.equal(oatr_jsObjectSome_result.param0.key, "value"); + if (oatr_jsObjectSome_result.tag === OptionalAllTypesResultValues.Tag.OptJSObject) { + assert.equal(oatr_jsObjectSome_result.param0?.key, "value"); + } const oatr_jsObjectNone = { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: null }; assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_jsObjectNone), oatr_jsObjectNone); @@ -233,7 +247,9 @@ export function runJsOptionalSupportTests(exports) { const oatr_jsClassSome = { tag: OptionalAllTypesResultValues.Tag.OptJsClass, param0: new ImportedFoo("optEnumFoo") }; const oatr_jsClassSome_result = exports.roundTripOptionalPayloadResult(oatr_jsClassSome); assert.equal(oatr_jsClassSome_result.tag, OptionalAllTypesResultValues.Tag.OptJsClass); - assert.equal(oatr_jsClassSome_result.param0.value, "optEnumFoo"); + if (oatr_jsClassSome_result.tag === OptionalAllTypesResultValues.Tag.OptJsClass) { + assert.equal(oatr_jsClassSome_result.param0?.value, "optEnumFoo"); + } const oatr_jsClassNone = { tag: OptionalAllTypesResultValues.Tag.OptJsClass, param0: null }; assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_jsClassNone), oatr_jsClassNone); diff --git a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift index c8cc9894b..520a608ad 100644 --- a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -83,115 +83,70 @@ final class OptionalSupportTests: XCTestCase { // } } -// MARK: - Optional Bridging - -@JS func roundTripOptionalString(name: String?) -> String? { - name -} - -@JS func roundTripOptionalInt(value: Int?) -> Int? { - value -} - -@JS func roundTripOptionalBool(flag: Bool?) -> Bool? { - flag -} - -@JS func roundTripOptionalFloat(number: Float?) -> Float? { - number -} - -@JS func roundTripOptionalDouble(precision: Double?) -> Double? { - precision -} - -@JS func roundTripOptionalSyntax(name: Optional) -> Optional { - name -} - -@JS func roundTripOptionalMixSyntax(name: String?) -> Optional { - name -} - -@JS func roundTripOptionalSwiftSyntax(name: Swift.Optional) -> Swift.Optional { - name -} - -@JS func roundTripOptionalWithSpaces(value: Optional) -> Optional { - value -} - -typealias OptionalAge = Int? -@JS func roundTripOptionalTypeAlias(age: OptionalAge) -> OptionalAge { - age -} - -@JS func roundTripOptionalStatus(value: Status?) -> Status? { - value -} - -@JS func roundTripOptionalTheme(value: Theme?) -> Theme? { - value -} - -@JS func roundTripOptionalHttpStatus(value: HttpStatus?) -> HttpStatus? { - value -} - -@JS func roundTripOptionalTSDirection(value: TSDirection?) -> TSDirection? { - value -} - -@JS func roundTripOptionalTSTheme(value: TSTheme?) -> TSTheme? { - value -} - -@JS func roundTripOptionalNetworkingAPIMethod(_ method: Networking.API.Method?) -> Networking.API.Method? { - method -} - -@JS func roundTripOptionalAPIResult(value: APIResult?) -> APIResult? { - value -} - -@JS func roundTripOptionalTypedPayloadResult(_ result: TypedPayloadResult?) -> TypedPayloadResult? { - result -} - -@JS func takeOptionalJSObject(_ value: JSObject?) {} - -@JS func compareAPIResults(_ r1: APIResult?, _ r2: APIResult?) -> String { - let r1Str: String - switch r1 { - case .none: r1Str = "nil" - case .some(.success(let msg)): r1Str = "success:\(msg)" - case .some(.failure(let code)): r1Str = "failure:\(code)" - case .some(.info): r1Str = "info" - case .some(.flag(let b)): r1Str = "flag:\(b)" - case .some(.rate(let r)): r1Str = "rate:\(r)" - case .some(.precise(let p)): r1Str = "precise:\(p)" +@JS enum OptionalSupportExports { + @JS static func roundTripOptionalString(_ v: String?) -> String? { v } + @JS static func roundTripOptionalInt(_ v: Int?) -> Int? { v } + @JS static func roundTripOptionalBool(_ v: Bool?) -> Bool? { v } + @JS static func roundTripOptionalFloat(_ v: Float?) -> Float? { v } + @JS static func roundTripOptionalDouble(_ v: Double?) -> Double? { v } + @JS static func roundTripOptionalSyntax(_ v: Optional) -> Optional { v } + @JS static func roundTripOptionalCaseEnum(_ v: Status?) -> Status? { v } + @JS static func roundTripOptionalStringRawValueEnum(_ v: Theme?) -> Theme? { v } + @JS static func roundTripOptionalIntRawValueEnum(_ v: HttpStatus?) -> HttpStatus? { v } + @JS static func roundTripOptionalTSEnum(_ v: TSDirection?) -> TSDirection? { v } + @JS static func roundTripOptionalTSStringEnum(_ v: TSTheme?) -> TSTheme? { v } + @JS static func roundTripOptionalNamespacedEnum(_ v: Networking.API.Method?) -> Networking.API.Method? { v } + @JS static func roundTripOptionalSwiftClass(_ v: Greeter?) -> Greeter? { v } + @JS static func roundTripOptionalIntArray(_ v: [Int]?) -> [Int]? { v } + @JS static func roundTripOptionalStringArray(_ v: [String]?) -> [String]? { v } + @JS static func roundTripOptionalSwiftClassArray(_ v: [Greeter]?) -> [Greeter]? { v } + + @JS static func roundTripOptionalAPIResult(_ v: APIResult?) -> APIResult? { v } + @JS static func roundTripOptionalTypedPayloadResult(_ v: TypedPayloadResult?) -> TypedPayloadResult? { v } + @JS static func roundTripOptionalComplexResult(_ v: ComplexResult?) -> ComplexResult? { v } + @JS static func roundTripOptionalAllTypesResult(_ v: AllTypesResult?) -> AllTypesResult? { v } + @JS static func roundTripOptionalPayloadResult(_ v: OptionalAllTypesResult) -> OptionalAllTypesResult { v } + @JS static func roundTripOptionalPayloadResultOpt(_ v: OptionalAllTypesResult?) -> OptionalAllTypesResult? { v } + @JS static func roundTripOptionalAPIOptionalResult(_ v: APIOptionalResult?) -> APIOptionalResult? { v } + + @JS static func takeOptionalJSObject(_ value: JSObject?) {} + + @JS static func applyOptionalGreeter(_ value: Greeter?, _ transform: (Greeter?) -> Greeter?) -> Greeter? { + transform(value) } - let r2Str: String - switch r2 { - case .none: r2Str = "nil" - case .some(.success(let msg)): r2Str = "success:\(msg)" - case .some(.failure(let code)): r2Str = "failure:\(code)" - case .some(.info): r2Str = "info" - case .some(.flag(let b)): r2Str = "flag:\(b)" - case .some(.rate(let r)): r2Str = "rate:\(r)" - case .some(.precise(let p)): r2Str = "precise:\(p)" + @JS static func makeOptionalHolder( + nullableGreeter: Greeter?, + undefinedNumber: JSUndefinedOr + ) -> OptionalHolder { + OptionalHolder(nullableGreeter: nullableGreeter, undefinedNumber: undefinedNumber) } - return "r1:\(r1Str),r2:\(r2Str)" -} + @JS static func compareAPIResults(_ r1: APIResult?, _ r2: APIResult?) -> String { + let r1Str: String + switch r1 { + case .none: r1Str = "nil" + case .some(.success(let msg)): r1Str = "success:\(msg)" + case .some(.failure(let code)): r1Str = "failure:\(code)" + case .some(.info): r1Str = "info" + case .some(.flag(let b)): r1Str = "flag:\(b)" + case .some(.rate(let r)): r1Str = "rate:\(r)" + case .some(.precise(let p)): r1Str = "precise:\(p)" + } -@JS func roundTripOptionalComplexResult(_ result: ComplexResult?) -> ComplexResult? { - result -} + let r2Str: String + switch r2 { + case .none: r2Str = "nil" + case .some(.success(let msg)): r2Str = "success:\(msg)" + case .some(.failure(let code)): r2Str = "failure:\(code)" + case .some(.info): r2Str = "info" + case .some(.flag(let b)): r2Str = "flag:\(b)" + case .some(.rate(let r)): r2Str = "rate:\(r)" + case .some(.precise(let p)): r2Str = "precise:\(p)" + } -@JS func roundTripOptionalAllTypesResult(_ result: AllTypesResult?) -> AllTypesResult? { - result + return "r1:\(r1Str),r2:\(r2Str)" + } } @JS @@ -205,26 +160,6 @@ enum OptionalAllTypesResult { case empty } -@JS func roundTripOptionalPayloadResult(_ result: OptionalAllTypesResult) -> OptionalAllTypesResult { - result -} - -@JS func roundTripOptionalPayloadResultOpt(_ result: OptionalAllTypesResult?) -> OptionalAllTypesResult? { - result -} - -@JS func roundTripOptionalClass(value: Greeter?) -> Greeter? { - value -} - -@JS func roundTripOptionalGreeter(_ value: Greeter?) -> Greeter? { - value -} - -@JS func applyOptionalGreeter(_ value: Greeter?, _ transform: (Greeter?) -> Greeter?) -> Greeter? { - transform(value) -} - @JS class OptionalHolder { @JS var nullableGreeter: Greeter? @JS var undefinedNumber: JSUndefinedOr @@ -235,10 +170,6 @@ enum OptionalAllTypesResult { } } -@JS func makeOptionalHolder(nullableGreeter: Greeter?, undefinedNumber: JSUndefinedOr) -> OptionalHolder { - OptionalHolder(nullableGreeter: nullableGreeter, undefinedNumber: undefinedNumber) -} - @JS class OptionalPropertyHolder { @JS var optionalName: String? @JS var optionalAge: Int? = nil @@ -255,7 +186,3 @@ enum APIOptionalResult { case failure(Int?, Bool?) case status(Bool?, Int?, String?) } - -@JS func roundTripOptionalAPIOptionalResult(result: APIOptionalResult?) -> APIOptionalResult? { - result -} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 350386e46..5fa7c11d1 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -789,7 +789,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.Services.Graph.GraphOperations.nodeCount(0), 0); testProtocolSupport(exports); - testArraySupport(exports); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ @@ -1149,38 +1148,6 @@ function setupTestGlobals(global) { }; } -/** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ -function testArraySupport(exports) { - const { Direction, Status, Theme, HttpStatus, Greeter } = exports; - - // Optional arrays - assert.deepEqual(exports.roundTripOptionalIntArrayType([1, 2, 3]), [1, 2, 3]); - assert.equal(exports.roundTripOptionalIntArrayType(null), null); - assert.deepEqual(exports.roundTripOptionalStringArrayType(["a", "b"]), ["a", "b"]); - assert.equal(exports.roundTripOptionalStringArrayType(null), null); - const og1 = new Greeter("OptGreeter"); - const optGreeterResult = exports.roundTripOptionalGreeterArrayType([og1]); - assert.equal(optGreeterResult[0].name, "OptGreeter"); - assert.equal(exports.roundTripOptionalGreeterArrayType(null), null); - og1.release(); - optGreeterResult.forEach(g => g.release()); - const helper1 = new exports.Greeter("Helper1"); - const jsProcessor1 = { - count: 1, name: "Processor1", optionalTag: null, optionalCount: null, - direction: null, optionalTheme: null, httpStatus: null, apiResult: null, - helper: helper1, optionalHelper: null, - increment(by) { this.count += by; }, - getValue() { return this.count; }, - setLabelElements(a, b) { }, getLabel() { return ""; }, - isEven() { return this.count % 2 === 0; }, - processGreeter(g) { return ""; }, createGreeter() { return new exports.Greeter("P1"); }, - processOptionalGreeter(g) { return ""; }, createOptionalGreeter() { return null; }, - handleAPIResult(r) { }, getAPIResult() { return null; } - }; - - helper1.release(); -} - /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function testProtocolSupport(exports) { let processorValue = 0; From fed1176d835c5bb0f4eacce13d72252aa2f4af2f Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Wed, 25 Feb 2026 20:56:12 +0900 Subject: [PATCH 007/140] BridgeJS: Unify `JSUndefinedOr` and `Optional` intrinsic methods --- .../JavaScriptKit/BridgeJSIntrinsics.swift | 820 ++++++------------ Sources/JavaScriptKit/JSUndefinedOr.swift | 2 +- 2 files changed, 263 insertions(+), 559 deletions(-) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 2f1e7feb0..0b0dfa982 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -181,12 +181,17 @@ extension _BridgedSwiftStackType { /// Types that bridge with the same (isSome, value) ABI as Optional. /// Used by JSUndefinedOr so all bridge methods delegate to Optional. -public protocol _BridgedAsOptional { +@_spi(BridgeJS) public protocol _BridgedAsOptional { associatedtype Wrapped var asOptional: Wrapped? { get } init(optional: Wrapped?) } +@_spi(BridgeJS) extension Optional: _BridgedAsOptional { + public var asOptional: Wrapped? { self } + public init(optional: Wrapped?) { self = optional } +} + extension Bool: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { @@ -1224,7 +1229,6 @@ extension UnsafeMutablePointer: _BridgedSwiftUnsafePointerLike { } } -// Optional support for JSTypedClosure extension Optional { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Int32 @@ -1233,7 +1237,6 @@ extension Optional { case .none: return (isSome: 0, value: 0) case .some(let wrapped): - // Use return lowering to retain the JS function so JS lifting can fetch it from the heap. return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) } } @@ -1354,221 +1357,231 @@ extension Double: _BridgedSwiftOptionalScalarSideChannelBridge { } } -extension Optional where Wrapped: _BridgedSwiftOptionalScalarBridge { +extension _BridgedAsOptional where Wrapped == JSValue { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Wrapped.WasmCoreType + isSome: Int32, kind: Int32, payload1: Int32, payload2: Double ) { - switch consume self { + switch asOptional { case .none: - return (isSome: 0, value: Wrapped.bridgeJSOptionalScalarNonePayload) + return (isSome: 0, kind: 0, payload1: 0, payload2: 0) case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) + let lowered = wrapped.bridgeJSLowerParameter() + return ( + isSome: 1, + kind: lowered.kind, + payload1: lowered.payload1, + payload2: lowered.payload2 + ) } } @_spi(BridgeJS) public static func bridgeJSLiftParameter( _ isSome: Int32, - _ wrappedValue: Wrapped.WasmCoreType - ) -> Wrapped? { + _ kind: Int32, + _ payload1: Int32, + _ payload2: Double + ) -> Self { if isSome == 0 { - return nil + return Self(optional: nil) + } else { + return Self(optional: JSValue.bridgeJSLiftParameter(kind, payload1, payload2)) } - return Wrapped.bridgeJSLiftParameter(wrappedValue) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { - case .none: - Wrapped.bridgeJSWriteOptionalReturn(0, Wrapped.bridgeJSOptionalScalarNonePayload) - case .some(let value): - Wrapped.bridgeJSWriteOptionalReturn(1, value.bridgeJSLowerReturn()) - } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + asOptional.bridgeJSStackPush() } } -extension Optional where Wrapped: _BridgedSwiftOptionalScalarSideChannelBridge { - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { - let isSome = Wrapped.bridgeJSReadOptionalSideChannelPresence() - if isSome == 0 { - return nil - } - return Wrapped.bridgeJSLiftReturn(Wrapped.bridgeJSReadOptionalSideChannelPayload()) - } +public protocol _BridgedSwiftTypeLoweredIntoVoidType { + // MARK: ExportSwift + consuming func bridgeJSLowerReturn() -> Void } -extension Optional where Wrapped == Bool { - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Bool? { - switch value { - case -1: - return nil - case 0: - return false - case 1: - return true - default: - return nil // Treat invalid values as null - } +// MARK: - _BridgedAsOptional (optional bridge implementations) + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Wrapped.bridgeJSStackPopAsOptional()) } -} -extension Optional where Wrapped == String { - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Int32 - ) { - _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + Wrapped.bridgeJSStackPushAsOptional(asOptional) } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ bytes: Int32, _ count: Int32) -> String? - { - _bridgeJSLiftParameter(isSome, (bytes, count), liftWrapped: { String.bridgeJSLiftParameter($0.0, $0.1) }) + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { + Self(optional: Wrapped.bridgeJSStackPopAsOptional()) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> String? { - let length = _swift_js_get_optional_string() - if length < 0 { - return nil - } else { - return String.bridgeJSLiftReturn(length) - } + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { + Self(optional: Wrapped.bridgeJSStackPopAsOptional()) } +} - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { - switch self { +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped, Wrapped: _BridgedSwiftTypeLoweredIntoVoidType +{ + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + switch asOptional { case .none: - _swift_js_return_optional_string(0, nil, 0) - case .some(var value): - return value.withUTF8 { ptr in - _swift_js_return_optional_string(1, ptr.baseAddress, Int32(ptr.count)) - } + return 0 + case .some(let array): + array.bridgeJSLowerReturn() + return 1 } } -} -extension Optional where Wrapped == JSObject { - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Int32 - ) { - _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + Wrapped.bridgeJSStackPushAsOptional(asOptional) } +} - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> JSObject? { - _bridgeJSLiftParameter(isSome, objectId, liftWrapped: JSObject.bridgeJSLiftParameter) +extension Optional: _BridgedSwiftStackType +where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { + public typealias StackLiftResult = Wrapped? + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + Wrapped.bridgeJSStackPopAsOptional() } - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { - _bridgeJSLowerReturn( - noneValue: 0, - lowerWrapped: { $0.bridgeJSLowerReturn() }, - write: _swift_js_return_optional_object - ) + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + Wrapped.bridgeJSStackPushAsOptional(self) } } -extension Optional where Wrapped == JSValue { - // MARK: ExportSwift - +extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarBridge { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, kind: Int32, payload1: Int32, payload2: Double + isSome: Int32, value: Wrapped.WasmCoreType ) { - switch consume self { + switch asOptional { case .none: - return (isSome: 0, kind: 0, payload1: 0, payload2: 0) + return (isSome: 0, value: Wrapped.bridgeJSOptionalScalarNonePayload) case .some(let wrapped): - let lowered = wrapped.bridgeJSLowerParameter() - return ( - isSome: 1, - kind: lowered.kind, - payload1: lowered.payload1, - payload2: lowered.payload2 - ) + return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) } } @_spi(BridgeJS) public static func bridgeJSLiftParameter( _ isSome: Int32, - _ kind: Int32, - _ payload1: Int32, - _ payload2: Double - ) -> JSValue? { - if isSome == 0 { - return nil - } else { - return JSValue.bridgeJSLiftParameter(kind, payload1, payload2) - } + _ wrappedValue: Wrapped.WasmCoreType + ) -> Self { + Self(optional: isSome == 0 ? nil : Wrapped.bridgeJSLiftParameter(wrappedValue)) } - @_spi(BridgeJS) public func bridgeJSLowerReturn() { - self.bridgeJSStackPush() + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + switch asOptional { + case .none: + Wrapped.bridgeJSWriteOptionalReturn(0, Wrapped.bridgeJSOptionalScalarNonePayload) + case .some(let value): + Wrapped.bridgeJSWriteOptionalReturn(1, value.bridgeJSLowerReturn()) + } } } -extension Optional { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 - where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { - switch consume self { - case .none: - return 0 - case .some(let array): - array.bridgeJSLowerReturn() - return 1 +extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + let isSome = Wrapped.bridgeJSReadOptionalSideChannelPresence() + if isSome == 0 { + return Self(optional: nil) } + return Self(optional: Wrapped.bridgeJSLiftReturn(Wrapped.bridgeJSReadOptionalSideChannelPayload())) } +} - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> [Element]? - where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { - return self.bridgeJSStackPop() +extension _BridgedAsOptional where Wrapped == Bool { + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { + let opt: Bool? = + switch value { + case -1: nil + case 0: false + case 1: true + default: nil // Treat invalid values as null + } + return Self(optional: opt) } +} - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [Element]? - where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { - return self.bridgeJSStackPop() +extension _BridgedAsOptional where Wrapped == String { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Int32 + ) { + asOptional._bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void - where Wrapped == [Element], Element: _BridgedSwiftStackType, Element == Element.StackLiftResult { - self.bridgeJSStackPush() + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ bytes: Int32, + _ count: Int32 + ) -> Self { + Self( + optional: Optional._bridgeJSLiftParameter( + isSome, + (bytes, count), + liftWrapped: { String.bridgeJSLiftParameter($0.0, $0.1) } + ) + ) } -} -extension Optional { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 - where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { - switch consume self { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + let length = _swift_js_get_optional_string() + if length < 0 { + return Self(optional: nil) + } else { + return Self(optional: String.bridgeJSLiftReturn(length)) + } + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + switch asOptional { case .none: - return 0 - case .some(let value): - value.bridgeJSLowerReturn() - return 1 + _swift_js_return_optional_string(0, nil, 0) + case .some(var value): + value.withUTF8 { ptr in + _swift_js_return_optional_string(1, ptr.baseAddress, Int32(ptr.count)) + } } } +} - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> [String: Value]? - where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { - return self.bridgeJSStackPop() +extension _BridgedAsOptional where Wrapped == JSObject { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Int32 + ) { + asOptional._bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) } - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Value]? - where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { - return self.bridgeJSStackPop() + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { + Self( + optional: Optional._bridgeJSLiftParameter( + isSome, + objectId, + liftWrapped: JSObject.bridgeJSLiftParameter + ) + ) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void - where Wrapped == [String: Value], Value: _BridgedSwiftStackType, Value == Value.StackLiftResult { - self.bridgeJSStackPush() + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional._bridgeJSLowerReturn( + noneValue: 0, + lowerWrapped: { $0.bridgeJSLowerReturn() }, + write: _swift_js_return_optional_object + ) } } -extension Optional where Wrapped: _BridgedSwiftProtocolWrapper { - // MARK: ExportSwift - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Wrapped? { - _bridgeJSLiftParameter(isSome, objectId, liftWrapped: Wrapped.bridgeJSLiftParameter) +extension _BridgedAsOptional where Wrapped: _BridgedSwiftProtocolWrapper { + @_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 { - switch consume self { + switch asOptional { case .none: _swift_js_return_optional_object(0, 0) case .some(let wrapper): @@ -1578,19 +1591,11 @@ extension Optional where Wrapped: _BridgedSwiftProtocolWrapper { } } -/// Optional support for Swift heap objects -extension Optional where Wrapped: _BridgedSwiftHeapObject { - // MARK: ExportSwift - /// Lowers optional Swift heap object as (isSome, pointer) tuple for protocol parameters. - /// - /// Transfer ownership to JavaScript for imported optional heap-object parameters; JS must - /// release via `release()` or finalizer. - /// - /// - Returns: A tuple containing presence flag (0 for nil, 1 for some) and retained pointer +extension _BridgedAsOptional where Wrapped: _BridgedSwiftHeapObject { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, pointer: UnsafeMutableRawPointer ) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, pointer: UnsafeMutableRawPointer(bitPattern: 1)!) case .some(let value): @@ -1598,35 +1603,38 @@ extension Optional where Wrapped: _BridgedSwiftHeapObject { } } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ pointer: UnsafeMutableRawPointer) -> Wrapped? - { + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ pointer: UnsafeMutableRawPointer) -> Self { if pointer == UnsafeMutableRawPointer(bitPattern: 0) { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSLiftReturn(pointer) + return Self(optional: Wrapped.bridgeJSLiftReturn(pointer)) } } - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( _ isSome: Int32, _ pointer: UnsafeMutableRawPointer - ) -> Optional { - _bridgeJSLiftParameter(isSome, pointer, liftWrapped: Wrapped.bridgeJSLiftParameter) + ) -> Self { + Self( + optional: Optional._bridgeJSLiftParameter( + isSome, + pointer, + liftWrapped: Wrapped.bridgeJSLiftParameter + ) + ) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { let pointer = _swift_js_get_optional_heap_object_pointer() if pointer == UnsafeMutableRawPointer(bitPattern: 0) { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSLiftReturn(pointer) + return Self(optional: Wrapped.bridgeJSLiftReturn(pointer)) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { + switch asOptional { case .none: _swift_js_return_optional_heap_object(0, nil) case .some(let value): @@ -1635,28 +1643,32 @@ extension Optional where Wrapped: _BridgedSwiftHeapObject { } } } -/// Optional support for case enums -extension Optional where Wrapped: _BridgedSwiftCaseEnum { - // MARK: ExportSwift +extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) + asOptional._bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Wrapped? { - _bridgeJSLiftParameter(isSome, wrappedValue, liftWrapped: Wrapped.bridgeJSLiftParameter) + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { + Self( + optional: Optional._bridgeJSLiftParameter( + isSome, + wrappedValue, + liftWrapped: Wrapped.bridgeJSLiftParameter + ) + ) } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { if value == -1 { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSLiftReturn(value) + return Self(optional: Wrapped.bridgeJSLiftReturn(value)) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - _bridgeJSLowerReturn( + asOptional._bridgeJSLowerReturn( noneValue: 0, lowerWrapped: { $0.bridgeJSLowerReturn() }, write: _swift_js_return_optional_int @@ -1664,20 +1676,12 @@ extension Optional where Wrapped: _BridgedSwiftCaseEnum { } } -public protocol _BridgedSwiftTypeLoweredIntoVoidType { - // MARK: ExportSwift - consuming func bridgeJSLowerReturn() -> Void -} - -// MARK: Optional Raw Value Enum Support - -extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { - // MARK: ExportSwift - +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Int32 ) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, value: 0) case .some(let wrapped): @@ -1689,31 +1693,31 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres _ isSome: Int32, _ bytes: Int32, _ count: Int32 - ) -> Wrapped? { - let optionalRawValue = String?.bridgeJSLiftParameter(isSome, bytes, count) - return optionalRawValue.flatMap { Wrapped(rawValue: $0) } + ) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, bytes, count) + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { let length = _swift_js_get_optional_string() if length < 0 { - return nil + return Self(optional: nil) } else { let rawValue = String.bridgeJSLiftReturn(length) - return Wrapped(rawValue: rawValue) + return Self(optional: Wrapped(rawValue: rawValue)) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: String? = self?.rawValue + let optionalRawValue: String? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } -extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { - // MARK: ExportSwift +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, value: 0) case .some(let value): @@ -1721,48 +1725,46 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Wrapped? { - let optionalRawValue = Int?.bridgeJSLiftParameter(isSome, wrappedValue) - return optionalRawValue.flatMap { Wrapped(rawValue: $0) } + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { let isSome = _swift_js_get_optional_int_presence() if isSome == 0 { - return nil + return Self(optional: nil) } else { let rawValue = _swift_js_get_optional_int_value() - return Wrapped(rawValue: Int(rawValue)) + return Self(optional: Wrapped(rawValue: Int(rawValue))) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Int? = self?.rawValue + let optionalRawValue: Int? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } -extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Bool { - // MARK: ExportSwift - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Wrapped? { - let optionalRawValue = Bool?.bridgeJSLiftParameter(isSome, wrappedValue) - return optionalRawValue.flatMap { Wrapped(rawValue: $0) } +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Bool { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Bool? = self?.rawValue + let optionalRawValue: Bool? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } -extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Float { - // MARK: ExportSwift - +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Float { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Float32 ) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, value: 0.0) case .some(let wrapped): @@ -1770,34 +1772,33 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Wrapped? { - let optionalRawValue = Float?.bridgeJSLiftParameter(isSome, wrappedValue) - return optionalRawValue.flatMap { Wrapped(rawValue: $0) } + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { let isSome = _swift_js_get_optional_float_presence() if isSome == 0 { - return nil + return Self(optional: nil) } else { let rawValue = _swift_js_get_optional_float_value() - return Wrapped(rawValue: Float(rawValue)) + return Self(optional: Wrapped(rawValue: Float(rawValue))) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Float? = self?.rawValue + let optionalRawValue: Float? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } -extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Double { - // MARK: ExportSwift - +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Double { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Float64 ) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, value: 0.0) case .some(let wrapped): @@ -1805,34 +1806,30 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Wrapped? { - let optionalRawValue = Double?.bridgeJSLiftParameter(isSome, wrappedValue) - return optionalRawValue.flatMap { Wrapped(rawValue: $0) } + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { let isSome = _swift_js_get_optional_double_presence() if isSome == 0 { - return nil + return Self(optional: nil) } else { let rawValue = _swift_js_get_optional_double_value() - return Wrapped(rawValue: Double(rawValue)) + return Self(optional: Wrapped(rawValue: Double(rawValue))) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Double? = self?.rawValue + let optionalRawValue: Double? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } -// MARK: Optional Associated Value Enum Support - -extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { - // MARK: ExportSwift - +extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { - switch consume self { + switch asOptional { case .none: return (isSome: 0, caseId: 0) case .some(let value): @@ -1840,314 +1837,50 @@ extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Self { if isSome == 0 { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSLiftParameter(caseId) + return Self(optional: Wrapped.bridgeJSLiftParameter(caseId)) } } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Wrapped? { + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { if caseId == -1 { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSStackPopPayload(caseId) + return Self(optional: Wrapped.bridgeJSStackPopPayload(caseId)) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { - bridgeJSStackPush() + Wrapped.bridgeJSStackPushAsOptional(asOptional) } } -// MARK: Optional Struct Support - -extension Optional where Wrapped: _BridgedSwiftStruct { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Wrapped? { +extension _BridgedAsOptional where Wrapped: _BridgedSwiftStruct { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { if isSome == 0 { - return nil + return Self(optional: nil) } else { - return Wrapped.bridgeJSStackPop() + return Self(optional: Wrapped.bridgeJSStackPop()) } } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - bridgeJSStackPush() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Wrapped? { - bridgeJSStackPop() - } -} - -// MARK: - Optional _BridgedSwiftStackType conformance - -// The default push/pop implementation just goes through -// `_BridgedSwiftStackType.bridgeJSStackPushAsOptional`, but some -// Wrapped types (e.g. case enums) have a more efficient implementation. -extension Optional: _BridgedSwiftStackType -where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { - public typealias StackLiftResult = Wrapped? - - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { - return Wrapped.bridgeJSStackPopAsOptional() - } - - @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - Wrapped.bridgeJSStackPushAsOptional(self) - } -} - -// MARK: - _BridgedAsOptional (JSUndefinedOr) delegating to Optional - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped { - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { - Self(optional: Optional.bridgeJSStackPop()) - } - @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - asOptional.bridgeJSStackPush() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarBridge { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Wrapped.WasmCoreType - ) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter( - _ isSome: Int32, - _ wrappedValue: Wrapped.WasmCoreType - ) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarSideChannelBridge { - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } -} - -extension _BridgedAsOptional where Wrapped == Bool { - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftReturn(value)) - } -} - -extension _BridgedAsOptional where Wrapped == String { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter( - _ isSome: Int32, - _ bytes: Int32, - _ count: Int32 - ) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped == JSObject { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, objectId)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftProtocolWrapper { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, objectId)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftHeapObject { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, pointer: UnsafeMutableRawPointer) - { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter( - _ isSome: Int32, - _ pointer: UnsafeMutableRawPointer - ) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, pointer)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftReturn(caseId)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter( - _ isSome: Int32, - _ bytes: Int32, - _ count: Int32 - ) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Bool { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Float { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Float32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Double { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Float64) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { - asOptional.bridgeJSLowerParameter() - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftReturn(caseId)) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { - asOptional.bridgeJSLowerReturn() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftStruct { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { - Self(optional: Optional.bridgeJSLiftParameter(isSome)) + Wrapped.bridgeJSStackPushAsOptional(asOptional) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { + Self.bridgeJSStackPop() } } // MARK: - Array Support +extension Array: _BridgedSwiftTypeLoweredIntoVoidType +where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element {} + extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element { public typealias StackLiftResult = [Element] @@ -2242,11 +1975,11 @@ where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Val } } -extension Optional where Wrapped: _BridgedSwiftDictionaryStackType { +extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { typealias DictionaryValue = Wrapped.DictionaryValue - private consuming func bridgeJSStackPushPayload() -> Int32 { - switch consume self { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + switch asOptional { case .none: return 0 case .some(let dict): @@ -2254,40 +1987,12 @@ extension Optional where Wrapped: _BridgedSwiftDictionaryStackType { return 1 } } - private static func bridgeJSStackPopPayload(_ isSome: Int32) -> [String: Wrapped.DictionaryValue]? { - if isSome == 0 { - return nil - } - return Dictionary.bridgeJSStackPop() - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSStackPushPayload() - } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> [String: Wrapped.DictionaryValue]? { - return bridgeJSStackPopPayload(isSome) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Wrapped.DictionaryValue]? { - return bridgeJSStackPopPayload(_swift_js_pop_i32()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - bridgeJSStackPush() - } -} - -extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { - typealias DictionaryValue = Wrapped.DictionaryValue - - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { - let opt = asOptional - if let dict = opt { - dict.bridgeJSLowerReturn() - return 1 + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { + if isSome == 0 { + return Self(optional: nil) } - return 0 + return Self(optional: (Dictionary.bridgeJSStackPop() as! Wrapped)) } @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { @@ -2295,11 +2000,10 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { if isSome == 0 { return Self(optional: nil) } - let value = Dictionary.bridgeJSLiftParameter() as! Wrapped - return Self(optional: value) + return Self(optional: (Dictionary.bridgeJSStackPop() as! Wrapped)) } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional.bridgeJSLowerReturn() + Wrapped.bridgeJSStackPushAsOptional(asOptional) } } diff --git a/Sources/JavaScriptKit/JSUndefinedOr.swift b/Sources/JavaScriptKit/JSUndefinedOr.swift index de7be09b4..c4d601738 100644 --- a/Sources/JavaScriptKit/JSUndefinedOr.swift +++ b/Sources/JavaScriptKit/JSUndefinedOr.swift @@ -53,4 +53,4 @@ extension JSUndefinedOr: ConvertibleToJSValue where Wrapped: ConvertibleToJSValu // MARK: - BridgeJS (via _BridgedAsOptional in BridgeJSIntrinsics) -extension JSUndefinedOr: _BridgedAsOptional {} +@_spi(BridgeJS) extension JSUndefinedOr: _BridgedAsOptional {} From 816325f6e92adb3660b62967899319b0d791b04f Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 27 Feb 2026 17:17:00 +0100 Subject: [PATCH 008/140] BridgeJS: Fix property codegen using unqualified type name for namespace-nested classes --- .../Sources/BridgeJSCore/ExportSwift.swift | 15 +++++++++++-- .../Inputs/MacroSwift/EnumNamespace.swift | 6 +++++- .../EnumNamespace.Global.json | 12 +++++++++++ .../EnumNamespace.Global.swift | 21 +++++++++++++++++++ .../BridgeJSCodegenTests/EnumNamespace.json | 12 +++++++++++ .../BridgeJSCodegenTests/EnumNamespace.swift | 21 +++++++++++++++++++ .../EnumNamespace.Global.d.ts | 1 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 7 +++++++ .../BridgeJSLinkTests/EnumNamespace.d.ts | 1 + .../BridgeJSLinkTests/EnumNamespace.js | 7 +++++++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 6 +++++- .../Generated/BridgeJS.swift | 21 +++++++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 12 +++++++++++ Tests/prelude.mjs | 3 +++ 14 files changed, 141 insertions(+), 4 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 4280b266d..6e5c17141 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -395,6 +395,17 @@ public class ExportSwift { } } + var swiftCallName: String { + switch self { + case .enumStatic(let enumDef): + return enumDef.swiftCallName + case .classStatic(let klass), .classInstance(let klass): + return klass.swiftCallName + case .structStatic(let structDef): + return structDef.swiftCallName + } + } + func callName(for property: ExportedProperty) -> String { switch self { case .enumStatic(let enumDef): @@ -423,7 +434,7 @@ public class ExportSwift { if !isStatic { try getterBuilder.liftParameter( - param: Parameter(label: nil, name: "_self", type: .swiftHeapObject(className)) + param: Parameter(label: nil, name: "_self", type: .swiftHeapObject(context.swiftCallName)) ) } @@ -446,7 +457,7 @@ public class ExportSwift { if !isStatic { // Instance properties need _self parameter try setterBuilder.liftParameter( - param: Parameter(label: nil, name: "_self", type: .swiftHeapObject(className)) + param: Parameter(label: nil, name: "_self", type: .swiftHeapObject(context.swiftCallName)) ) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift index dbf044834..218cd4ca3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift @@ -2,7 +2,11 @@ @JS enum Utils { @JS class Converter { - @JS init() {} + @JS var precision: Int + + @JS init() { + self.precision = 2 + } @JS func toString(value: Int) -> String { return String(value) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json index 65b8ba350..f26bd3041 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -48,7 +48,19 @@ "Utils" ], "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "precision", + "namespace" : [ + "Utils" + ], + "type" : { + "int" : { + } + } + } ], "swiftCallName" : "Utils.Converter" }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 47d1ff60a..f3d673a03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -151,6 +151,27 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } +@_expose(wasm, "bjs_Converter_precision_get") +@_cdecl("bjs_Converter_precision_get") +public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Converter_precision_set") +@_cdecl("bjs_Converter_precision_set") +public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Converter_deinit") @_cdecl("bjs_Converter_deinit") public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json index 9b800c743..a4ba27b8c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -48,7 +48,19 @@ "Utils" ], "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "precision", + "namespace" : [ + "Utils" + ], + "type" : { + "int" : { + } + } + } ], "swiftCallName" : "Utils.Converter" }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 47d1ff60a..f3d673a03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -151,6 +151,27 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } +@_expose(wasm, "bjs_Converter_precision_get") +@_cdecl("bjs_Converter_precision_get") +public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Converter_precision_set") +@_cdecl("bjs_Converter_precision_set") +public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Converter_deinit") @_cdecl("bjs_Converter_deinit") public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { 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 be77e759c..17ac74a82 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -84,6 +84,7 @@ export interface SwiftHeapObject { } export interface Converter extends SwiftHeapObject { toString(value: number): string; + precision: number; } export interface HTTPServer extends SwiftHeapObject { call(method: Networking.API.MethodTag): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index ca44d2382..f39031341 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -300,6 +300,13 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; } + get precision() { + const ret = instance.exports.bjs_Converter_precision_get(this.pointer); + return ret; + } + set precision(value) { + instance.exports.bjs_Converter_precision_set(this.pointer, value); + } } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index a6934d6e7..bc8e1601d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -56,6 +56,7 @@ export interface SwiftHeapObject { } export interface Converter extends SwiftHeapObject { toString(value: number): string; + precision: number; } export interface HTTPServer extends SwiftHeapObject { call(method: Networking.API.MethodTag): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 8484951f3..effa7feec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -281,6 +281,13 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; } + get precision() { + const ret = instance.exports.bjs_Converter_precision_get(this.pointer); + return ret; + } + set precision(value) { + instance.exports.bjs_Converter_precision_set(this.pointer, value); + } } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 26f587fa3..bc77cb342 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -313,7 +313,11 @@ struct TestError: Error { @JS enum Utils { @JS class Converter { - @JS init() {} + @JS var precision: Int + + @JS init() { + self.precision = 2 + } @JS func toString(value: Int) -> String { return String(value) diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 6a7ce73c2..47d3ca6a4 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -6947,6 +6947,27 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } +@_expose(wasm, "bjs_Converter_precision_get") +@_cdecl("bjs_Converter_precision_get") +public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Converter_precision_set") +@_cdecl("bjs_Converter_precision_set") +public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Converter_deinit") @_cdecl("bjs_Converter_deinit") public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 4b33632b5..313add018 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -714,7 +714,19 @@ "Utils" ], "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "precision", + "namespace" : [ + "Utils" + ], + "type" : { + "int" : { + } + } + } ], "swiftCallName" : "Utils.Converter" }, diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 4242d8bdb..d2b62a11c 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -607,6 +607,9 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.roundtripInternalSupportedMethod(exports.Networking.APIV2.Internal.SupportedMethod.Get), exports.Networking.APIV2.Internal.SupportedMethod.Get); const converter = new exports.Utils.Converter(); + assert.equal(converter.precision, 2); + converter.precision = 5; + assert.equal(converter.precision, 5); assert.equal(converter.toString(42), "42"); assert.equal(converter.toString(123), "123"); converter.release(); From 494ed169df2b417fe01f212b078953750d544da6 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 27 Feb 2026 17:41:57 +0100 Subject: [PATCH 009/140] BridgeJS: Include namespace prefix in ABI names for namespace-nested classes and structs --- .../Sources/BridgeJSCore/ExportSwift.swift | 18 +-- .../BridgeJSCore/SwiftToSkeleton.swift | 42 +++-- .../Sources/BridgeJSLink/BridgeJSLink.swift | 10 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 22 ++- .../Inputs/MacroSwift/EnumNamespace.swift | 10 ++ .../EnumNamespace.Global.json | 78 ++++++++- .../EnumNamespace.Global.swift | 152 ++++++++++++------ .../BridgeJSCodegenTests/EnumNamespace.json | 78 ++++++++- .../BridgeJSCodegenTests/EnumNamespace.swift | 152 ++++++++++++------ .../BridgeJSCodegenTests/MixedGlobal.json | 4 +- .../BridgeJSCodegenTests/MixedGlobal.swift | 30 ++-- .../BridgeJSCodegenTests/MixedPrivate.json | 4 +- .../BridgeJSCodegenTests/MixedPrivate.swift | 30 ++-- .../Namespaces.Global.json | 16 +- .../Namespaces.Global.swift | 120 +++++++------- .../BridgeJSCodegenTests/Namespaces.json | 16 +- .../BridgeJSCodegenTests/Namespaces.swift | 120 +++++++------- .../EnumNamespace.Global.d.ts | 14 ++ .../BridgeJSLinkTests/EnumNamespace.Global.js | 55 +++++-- .../BridgeJSLinkTests/EnumNamespace.d.ts | 8 + .../BridgeJSLinkTests/EnumNamespace.js | 51 ++++-- .../BridgeJSLinkTests/MixedGlobal.js | 8 +- .../BridgeJSLinkTests/MixedModules.js | 16 +- .../BridgeJSLinkTests/MixedPrivate.js | 8 +- .../BridgeJSLinkTests/Namespaces.Global.js | 32 ++-- .../BridgeJSLinkTests/Namespaces.js | 32 ++-- .../Generated/BridgeJS.swift | 90 +++++------ .../Generated/JavaScript/BridgeJS.json | 12 +- .../Generated/BridgeJS.swift | 132 +++++++-------- .../Generated/JavaScript/BridgeJS.json | 16 +- 30 files changed, 858 insertions(+), 518 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 6e5c17141..50bebb907 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -389,9 +389,9 @@ public class ExportSwift { case .enumStatic(let enumDef): return enumDef.name case .classStatic(let klass), .classInstance(let klass): - return klass.name + return klass.abiName case .structStatic(let structDef): - return structDef.name + return structDef.abiName } } @@ -653,7 +653,7 @@ public class ExportSwift { do { let funcDecl = SwiftCodePattern.buildExposedFunctionDecl( - abiName: "bjs_\(klass.name)_deinit", + abiName: "bjs_\(klass.abiName)_deinit", signature: SwiftSignatureBuilder.buildABIFunctionSignature( abiParameters: [("pointer", .pointer)], returnType: nil @@ -686,8 +686,8 @@ public class ExportSwift { /// fileprivate func _bjs_Greeter_wrap(_: UnsafeMutableRawPointer) -> Int32 /// ``` func renderConvertibleToJSValueExtension(klass: ExportedClass) -> [DeclSyntax] { - let wrapFunctionName = "_bjs_\(klass.name)_wrap" - let externFunctionName = "bjs_\(klass.name)_wrap" + let wrapFunctionName = "_bjs_\(klass.abiName)_wrap" + let externFunctionName = "bjs_\(klass.abiName)_wrap" // If the class has an explicit access control, we need to add it to the extension declaration. let accessControl = klass.explicitAccessControl.map { "\($0) " } ?? "" @@ -1087,10 +1087,10 @@ struct StructCodegen { func renderStructHelpers(_ structDef: ExportedStruct) -> [DeclSyntax] { let typeName = structDef.swiftCallName - let lowerExternName = "swift_js_struct_lower_\(structDef.name)" - let liftExternName = "swift_js_struct_lift_\(structDef.name)" - let lowerFunctionName = "_bjs_struct_lower_\(structDef.name)" - let liftFunctionName = "_bjs_struct_lift_\(structDef.name)" + let lowerExternName = "swift_js_struct_lower_\(structDef.abiName)" + let liftExternName = "swift_js_struct_lift_\(structDef.abiName)" + let lowerFunctionName = "_bjs_struct_lower_\(structDef.abiName)" + let liftFunctionName = "_bjs_struct_lift_\(structDef.abiName)" let printer = CodeFragmentPrinter() printer.write("extension \(typeName): _BridgedSwiftStruct {") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 0cf5a567f..8f1b3fa35 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1060,9 +1060,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { switch state { case .topLevel: staticContext = nil - case .classBody(let className, _): + case .classBody(_, let classKey): if isStatic { - staticContext = .className(className) + let classAbiName = exportedClassByName[classKey]?.abiName ?? "unknown" + staticContext = .className(classAbiName) } else { staticContext = nil } @@ -1077,9 +1078,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { staticContext = isNamespaceEnum ? .namespaceEnum(swiftCallName) : .enumName(enumName) case .protocolBody(_, _): return nil - case .structBody(let structName, _): + case .structBody(_, let structKey): if isStatic { - staticContext = .structName(structName) + let structAbiName = exportedStructByName[structKey]?.abiName ?? "unknown" + staticContext = .structName(structAbiName) } else { staticContext = nil } @@ -1087,10 +1089,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let classNameForABI: String? switch state { - case .classBody(let className, _): - classNameForABI = className - case .structBody(let structName, _): - classNameForABI = structName + case .classBody(_, let classKey): + classNameForABI = exportedClassByName[classKey]?.abiName + case .structBody(_, let structKey): + classNameForABI = exportedStructByName[structKey]?.abiName default: classNameForABI = nil } @@ -1179,7 +1181,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren } switch state { - case .classBody(let className, let classKey): + case .classBody(_, let classKey): if extractNamespace(from: jsAttribute) != nil { diagnose( node: jsAttribute, @@ -1194,14 +1196,15 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + let classAbiName = exportedClassByName[classKey]?.abiName ?? "unknown" let constructor = ExportedConstructor( - abiName: "bjs_\(className)_init", + abiName: "bjs_\(classAbiName)_init", parameters: parameters, effects: effects ) exportedClassByName[classKey]?.constructor = constructor - case .structBody(let structName, let structKey): + case .structBody(_, let structKey): if extractNamespace(from: jsAttribute) != nil { diagnose( node: jsAttribute, @@ -1216,8 +1219,9 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + let structAbiName = exportedStructByName[structKey]?.abiName ?? "unknown" let constructor = ExportedConstructor( - abiName: "bjs_\(structName)_init", + abiName: "bjs_\(structAbiName)_init", parameters: parameters, effects: effects ) @@ -1263,8 +1267,13 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let staticContext: StaticContext? switch state { - case .classBody(let className, _): - staticContext = isStatic ? .className(className) : nil + case .classBody(_, let classKey): + if isStatic { + let classAbiName = exportedClassByName[classKey]?.abiName ?? "unknown" + staticContext = .className(classAbiName) + } else { + staticContext = nil + } case .enumBody(let enumName, let enumKey): if !isStatic { diagnose(node: node, message: "Only static properties are supported in enums") @@ -1280,9 +1289,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren case .protocolBody(let protocolName, let protocolKey): return visitProtocolProperty(node: node, protocolName: protocolName, protocolKey: protocolKey) - case .structBody(let structName, _): + case .structBody(_, let structKey): if isStatic { - staticContext = .structName(structName) + let structAbiName = exportedStructByName[structKey]?.abiName ?? "unknown" + staticContext = .structName(structAbiName) } else { diagnose(node: node, message: "@JS var must be static in structs (instance fields don't need @JS)") return .skipChildren diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 499d6f60b..af2456f81 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -447,7 +447,7 @@ public struct BridgeJSLink { printer.write("}") if !allStructs.isEmpty { for structDef in allStructs { - printer.write("bjs[\"swift_js_struct_lower_\(structDef.name)\"] = function(objectId) {") + printer.write("bjs[\"swift_js_struct_lower_\(structDef.abiName)\"] = function(objectId) {") printer.indent { printer.write( "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" @@ -455,7 +455,7 @@ public struct BridgeJSLink { } printer.write("}") - printer.write("bjs[\"swift_js_struct_lift_\(structDef.name)\"] = function() {") + printer.write("bjs[\"swift_js_struct_lift_\(structDef.abiName)\"] = function() {") printer.indent { printer.write( "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lift();" @@ -1155,7 +1155,7 @@ public struct BridgeJSLink { wrapperLines.append("}") for klass in classes.sorted(by: { $0.name < $1.name }) { - let wrapperFunctionName = "bjs_\(klass.name)_wrap" + let wrapperFunctionName = "bjs_\(klass.abiName)_wrap" let namespacePath = (klass.namespace ?? []).map { ".\($0)" }.joined() let exportsPath = namespacePath.isEmpty ? "_exports['\(klass.name)']" : "_exports\(namespacePath).\(klass.name)" @@ -1967,7 +1967,7 @@ extension BridgeJSLink { jsPrinter.write("static __construct(ptr) {") jsPrinter.indent { jsPrinter.write( - "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.name)_deinit, \(klass.name).prototype);" + "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype);" ) } jsPrinter.write("}") @@ -2069,7 +2069,7 @@ extension BridgeJSLink { for property in klass.properties { try renderClassProperty( property: property, - className: klass.name, + className: klass.abiName, isStatic: property.isStatic, jsPrinter: jsPrinter, dtsPrinter: property.isStatic ? dtsExportEntryPrinter : dtsTypePrinter diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index dab5fae33..967215f6c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1,5 +1,21 @@ // This file is shared between BridgeTool and BridgeJSLink +// MARK: - Namespaced Type Protocol + +public protocol NamespacedExportedType { + var name: String { get } + var namespace: [String]? { get } +} + +extension NamespacedExportedType { + public var abiName: String { + if let namespace = namespace, !namespace.isEmpty { + return (namespace + [name]).joined(separator: "_") + } + return name + } +} + // MARK: - ABI Name Generation /// Utility for generating consistent ABI names across all exported and imported types @@ -412,7 +428,7 @@ public struct StructField: Codable, Equatable, Sendable { } } -public struct ExportedStruct: Codable, Equatable, Sendable { +public struct ExportedStruct: Codable, Equatable, Sendable, NamespacedExportedType { public let name: String public let swiftCallName: String public let explicitAccessControl: String? @@ -490,7 +506,7 @@ public enum EnumEmitStyle: String, Codable, Sendable { case tsEnum } -public struct ExportedEnum: Codable, Equatable, Sendable { +public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType { public static let valuesSuffix = "Values" public static let objectSuffix = "Object" @@ -619,7 +635,7 @@ public struct ExportedFunction: Codable, Equatable, Sendable { } } -public struct ExportedClass: Codable { +public struct ExportedClass: Codable, NamespacedExportedType { public var name: String public var swiftCallName: String public var explicitAccessControl: String? diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift index 218cd4ca3..e46d74423 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift @@ -57,6 +57,16 @@ enum Internal { } } +@JS enum Formatting { + @JS class Converter { + @JS init() {} + + @JS func format(value: Int) -> String { + return "formatted_\(value)" + } + } +} + @JS(namespace: "Services.Graph") enum GraphOperations { @JS static func createGraph(rootId: Int) -> Int { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json index f26bd3041..b519748d4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_Converter_init", + "abiName" : "bjs_Utils_Converter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -15,7 +15,7 @@ }, "methods" : [ { - "abiName" : "bjs_Converter_toString", + "abiName" : "bjs_Utils_Converter_toString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -66,7 +66,7 @@ }, { "constructor" : { - "abiName" : "bjs_HTTPServer_init", + "abiName" : "bjs_Networking_API_HTTPServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -78,7 +78,7 @@ }, "methods" : [ { - "abiName" : "bjs_HTTPServer_call", + "abiName" : "bjs_Networking_API_HTTPServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -119,7 +119,7 @@ }, { "constructor" : { - "abiName" : "bjs_TestServer_init", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -131,7 +131,7 @@ }, "methods" : [ { - "abiName" : "bjs_TestServer_call", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -171,6 +171,57 @@ ], "swiftCallName" : "Internal.TestServer" + }, + { + "constructor" : { + "abiName" : "bjs_Formatting_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Formatting_Converter_format", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "format", + "namespace" : [ + "Formatting" + ], + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Formatting" + ], + "properties" : [ + + ], + "swiftCallName" : "Formatting.Converter" } ], "enums" : [ @@ -417,6 +468,21 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "Formatting", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Formatting", + "tsFullPath" : "Formatting" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "GraphOperations", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index f3d673a03..d4dfa57a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -129,9 +129,9 @@ public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32 #endif } -@_expose(wasm, "bjs_Converter_init") -@_cdecl("bjs_Converter_init") -public func _bjs_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_Converter_init") +@_cdecl("bjs_Utils_Converter_init") +public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Utils.Converter() return ret.bridgeJSLowerReturn() @@ -140,9 +140,9 @@ public func _bjs_Converter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Converter_toString") -@_cdecl("bjs_Converter_toString") -public func _bjs_Converter_toString(_ _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) let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -151,9 +151,9 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } -@_expose(wasm, "bjs_Converter_precision_get") -@_cdecl("bjs_Converter_precision_get") -public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_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 = Utils.Converter.bridgeJSLiftParameter(_self).precision return ret.bridgeJSLowerReturn() @@ -162,9 +162,9 @@ public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> In #endif } -@_expose(wasm, "bjs_Converter_precision_set") -@_cdecl("bjs_Converter_precision_set") -public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: 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) Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) #else @@ -172,9 +172,9 @@ public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ val #endif } -@_expose(wasm, "bjs_Converter_deinit") -@_cdecl("bjs_Converter_deinit") -public func _bjs_Converter_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() #else @@ -184,25 +184,25 @@ public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Utils_Converter_wrap") +fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_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_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Converter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_HTTPServer_init") -@_cdecl("bjs_HTTPServer_init") -public func _bjs_HTTPServer_init() -> 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 = Networking.API.HTTPServer() return ret.bridgeJSLowerReturn() @@ -211,9 +211,9 @@ public func _bjs_HTTPServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_HTTPServer_call") -@_cdecl("bjs_HTTPServer_call") -public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) #else @@ -221,9 +221,9 @@ public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_HTTPServer_deinit") -@_cdecl("bjs_HTTPServer_deinit") -public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -233,25 +233,25 @@ public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Networking_API_HTTPServer_wrap") +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_HTTPServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Networking_API_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Networking_API_HTTPServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_TestServer_init") -@_cdecl("bjs_TestServer_init") -public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { +@_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 = Internal.TestServer() return ret.bridgeJSLowerReturn() @@ -260,9 +260,9 @@ public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_TestServer_call") -@_cdecl("bjs_TestServer_call") -public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) #else @@ -270,9 +270,9 @@ public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_TestServer_deinit") -@_cdecl("bjs_TestServer_deinit") -public func _bjs_TestServer_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() #else @@ -282,18 +282,68 @@ public func _bjs_TestServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Networking_APIV2_Internal_TestServer_wrap") +fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestServer_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_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TestServer_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_Formatting_Converter_init") +@_cdecl("bjs_Formatting_Converter_init") +public func _bjs_Formatting_Converter_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Formatting.Converter() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Formatting_Converter_format") +@_cdecl("bjs_Formatting_Converter_format") +public func _bjs_Formatting_Converter_format(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + let ret = Formatting.Converter.bridgeJSLiftParameter(_self).format(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Formatting_Converter_deinit") +@_cdecl("bjs_Formatting_Converter_deinit") +public func _bjs_Formatting_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Formatting_Converter_wrap") +fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Formatting_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Formatting_Converter_wrap_extern(pointer) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json index a4ba27b8c..a468b2e2c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_Converter_init", + "abiName" : "bjs_Utils_Converter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -15,7 +15,7 @@ }, "methods" : [ { - "abiName" : "bjs_Converter_toString", + "abiName" : "bjs_Utils_Converter_toString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -66,7 +66,7 @@ }, { "constructor" : { - "abiName" : "bjs_HTTPServer_init", + "abiName" : "bjs_Networking_API_HTTPServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -78,7 +78,7 @@ }, "methods" : [ { - "abiName" : "bjs_HTTPServer_call", + "abiName" : "bjs_Networking_API_HTTPServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -119,7 +119,7 @@ }, { "constructor" : { - "abiName" : "bjs_TestServer_init", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -131,7 +131,7 @@ }, "methods" : [ { - "abiName" : "bjs_TestServer_call", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -171,6 +171,57 @@ ], "swiftCallName" : "Internal.TestServer" + }, + { + "constructor" : { + "abiName" : "bjs_Formatting_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Formatting_Converter_format", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "format", + "namespace" : [ + "Formatting" + ], + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Formatting" + ], + "properties" : [ + + ], + "swiftCallName" : "Formatting.Converter" } ], "enums" : [ @@ -417,6 +468,21 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "Formatting", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Formatting", + "tsFullPath" : "Formatting" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "GraphOperations", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index f3d673a03..d4dfa57a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -129,9 +129,9 @@ public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32 #endif } -@_expose(wasm, "bjs_Converter_init") -@_cdecl("bjs_Converter_init") -public func _bjs_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_Converter_init") +@_cdecl("bjs_Utils_Converter_init") +public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Utils.Converter() return ret.bridgeJSLowerReturn() @@ -140,9 +140,9 @@ public func _bjs_Converter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Converter_toString") -@_cdecl("bjs_Converter_toString") -public func _bjs_Converter_toString(_ _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) let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -151,9 +151,9 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } -@_expose(wasm, "bjs_Converter_precision_get") -@_cdecl("bjs_Converter_precision_get") -public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_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 = Utils.Converter.bridgeJSLiftParameter(_self).precision return ret.bridgeJSLowerReturn() @@ -162,9 +162,9 @@ public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> In #endif } -@_expose(wasm, "bjs_Converter_precision_set") -@_cdecl("bjs_Converter_precision_set") -public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: 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) Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) #else @@ -172,9 +172,9 @@ public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ val #endif } -@_expose(wasm, "bjs_Converter_deinit") -@_cdecl("bjs_Converter_deinit") -public func _bjs_Converter_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() #else @@ -184,25 +184,25 @@ public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Utils_Converter_wrap") +fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_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_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Converter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_HTTPServer_init") -@_cdecl("bjs_HTTPServer_init") -public func _bjs_HTTPServer_init() -> 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 = Networking.API.HTTPServer() return ret.bridgeJSLowerReturn() @@ -211,9 +211,9 @@ public func _bjs_HTTPServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_HTTPServer_call") -@_cdecl("bjs_HTTPServer_call") -public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) #else @@ -221,9 +221,9 @@ public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_HTTPServer_deinit") -@_cdecl("bjs_HTTPServer_deinit") -public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -233,25 +233,25 @@ public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Networking_API_HTTPServer_wrap") +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_HTTPServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Networking_API_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Networking_API_HTTPServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_TestServer_init") -@_cdecl("bjs_TestServer_init") -public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { +@_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 = Internal.TestServer() return ret.bridgeJSLowerReturn() @@ -260,9 +260,9 @@ public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_TestServer_call") -@_cdecl("bjs_TestServer_call") -public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) #else @@ -270,9 +270,9 @@ public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_TestServer_deinit") -@_cdecl("bjs_TestServer_deinit") -public func _bjs_TestServer_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() #else @@ -282,18 +282,68 @@ public func _bjs_TestServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Networking_APIV2_Internal_TestServer_wrap") +fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestServer_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_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TestServer_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_Formatting_Converter_init") +@_cdecl("bjs_Formatting_Converter_init") +public func _bjs_Formatting_Converter_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Formatting.Converter() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Formatting_Converter_format") +@_cdecl("bjs_Formatting_Converter_format") +public func _bjs_Formatting_Converter_format(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + let ret = Formatting.Converter.bridgeJSLiftParameter(_self).format(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Formatting_Converter_deinit") +@_cdecl("bjs_Formatting_Converter_deinit") +public func _bjs_Formatting_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Formatting_Converter_wrap") +fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Formatting_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Formatting_Converter_wrap_extern(pointer) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json index 1241c232d..f140fd007 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_GlobalClass_init", + "abiName" : "bjs_GlobalAPI_GlobalClass_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -15,7 +15,7 @@ }, "methods" : [ { - "abiName" : "bjs_GlobalClass_greet", + "abiName" : "bjs_GlobalAPI_GlobalClass_greet", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift index 195a00fa1..802a09638 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift @@ -9,9 +9,9 @@ public func _bjs_GlobalAPI_globalFunction() -> Void { #endif } -@_expose(wasm, "bjs_GlobalClass_init") -@_cdecl("bjs_GlobalClass_init") -public func _bjs_GlobalClass_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_GlobalAPI_GlobalClass_init") +@_cdecl("bjs_GlobalAPI_GlobalClass_init") +public func _bjs_GlobalAPI_GlobalClass_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = GlobalClass() return ret.bridgeJSLowerReturn() @@ -20,9 +20,9 @@ public func _bjs_GlobalClass_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_GlobalClass_greet") -@_cdecl("bjs_GlobalClass_greet") -public func _bjs_GlobalClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_GlobalAPI_GlobalClass_greet") +@_cdecl("bjs_GlobalAPI_GlobalClass_greet") +public func _bjs_GlobalAPI_GlobalClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = GlobalClass.bridgeJSLiftParameter(_self).greet() return ret.bridgeJSLowerReturn() @@ -31,9 +31,9 @@ public func _bjs_GlobalClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_GlobalClass_deinit") -@_cdecl("bjs_GlobalClass_deinit") -public func _bjs_GlobalClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_GlobalAPI_GlobalClass_deinit") +@_cdecl("bjs_GlobalAPI_GlobalClass_deinit") +public func _bjs_GlobalAPI_GlobalClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -43,18 +43,18 @@ public func _bjs_GlobalClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void extension GlobalClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalClass_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalAPI_GlobalClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_GlobalClass_wrap") -fileprivate func _bjs_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_GlobalAPI_GlobalClass_wrap") +fileprivate func _bjs_GlobalAPI_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_GlobalAPI_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_GlobalClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_GlobalClass_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_GlobalAPI_GlobalClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GlobalAPI_GlobalClass_wrap_extern(pointer) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json index 96e188fd2..9e9dc445e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_PrivateClass_init", + "abiName" : "bjs_PrivateAPI_PrivateClass_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -15,7 +15,7 @@ }, "methods" : [ { - "abiName" : "bjs_PrivateClass_greet", + "abiName" : "bjs_PrivateAPI_PrivateClass_greet", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift index 6112dd3e4..50dc9e778 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift @@ -9,9 +9,9 @@ public func _bjs_PrivateAPI_privateFunction() -> Void { #endif } -@_expose(wasm, "bjs_PrivateClass_init") -@_cdecl("bjs_PrivateClass_init") -public func _bjs_PrivateClass_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PrivateAPI_PrivateClass_init") +@_cdecl("bjs_PrivateAPI_PrivateClass_init") +public func _bjs_PrivateAPI_PrivateClass_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = PrivateClass() return ret.bridgeJSLowerReturn() @@ -20,9 +20,9 @@ public func _bjs_PrivateClass_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_PrivateClass_greet") -@_cdecl("bjs_PrivateClass_greet") -public func _bjs_PrivateClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PrivateAPI_PrivateClass_greet") +@_cdecl("bjs_PrivateAPI_PrivateClass_greet") +public func _bjs_PrivateAPI_PrivateClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = PrivateClass.bridgeJSLiftParameter(_self).greet() return ret.bridgeJSLowerReturn() @@ -31,9 +31,9 @@ public func _bjs_PrivateClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_PrivateClass_deinit") -@_cdecl("bjs_PrivateClass_deinit") -public func _bjs_PrivateClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PrivateAPI_PrivateClass_deinit") +@_cdecl("bjs_PrivateAPI_PrivateClass_deinit") +public func _bjs_PrivateAPI_PrivateClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -43,18 +43,18 @@ public func _bjs_PrivateClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void extension PrivateClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PrivateClass_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_PrivateAPI_PrivateClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_PrivateClass_wrap") -fileprivate func _bjs_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_PrivateAPI_PrivateClass_wrap") +fileprivate func _bjs_PrivateAPI_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PrivateAPI_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_PrivateClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PrivateClass_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_PrivateAPI_PrivateClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PrivateAPI_PrivateClass_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 0ef46ac72..29cbddeb7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_Greeter_init", + "abiName" : "bjs___Swift_Foundation_Greeter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -23,7 +23,7 @@ }, "methods" : [ { - "abiName" : "bjs_Greeter_greet", + "abiName" : "bjs___Swift_Foundation_Greeter_greet", "effects" : { "isAsync" : false, "isStatic" : false, @@ -52,7 +52,7 @@ }, { "constructor" : { - "abiName" : "bjs_Converter_init", + "abiName" : "bjs_Utils_Converters_Converter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -64,7 +64,7 @@ }, "methods" : [ { - "abiName" : "bjs_Converter_toString", + "abiName" : "bjs_Utils_Converters_Converter_toString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -102,7 +102,7 @@ { "methods" : [ { - "abiName" : "bjs_UUID_uuidString", + "abiName" : "bjs___Swift_Foundation_UUID_uuidString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -131,7 +131,7 @@ }, { "constructor" : { - "abiName" : "bjs_Container_init", + "abiName" : "bjs_Collections_Container_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -143,7 +143,7 @@ }, "methods" : [ { - "abiName" : "bjs_Container_getItems", + "abiName" : "bjs_Collections_Container_getItems", "effects" : { "isAsync" : false, "isStatic" : false, @@ -164,7 +164,7 @@ } }, { - "abiName" : "bjs_Container_addItem", + "abiName" : "bjs_Collections_Container_addItem", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index 4b9ecd10a..d376a2a54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -20,9 +20,9 @@ public func _bjs_MyModule_Utils_namespacedFunction() -> Void { #endif } -@_expose(wasm, "bjs_Greeter_init") -@_cdecl("bjs_Greeter_init") -public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_init") +@_cdecl("bjs___Swift_Foundation_Greeter_init") +public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) return ret.bridgeJSLowerReturn() @@ -31,9 +31,9 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe #endif } -@_expose(wasm, "bjs_Greeter_greet") -@_cdecl("bjs_Greeter_greet") -public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_greet") +@_cdecl("bjs___Swift_Foundation_Greeter_greet") +public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = Greeter.bridgeJSLiftParameter(_self).greet() return ret.bridgeJSLowerReturn() @@ -42,9 +42,9 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_Greeter_deinit") -@_cdecl("bjs_Greeter_deinit") -public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_deinit") +@_cdecl("bjs___Swift_Foundation_Greeter_deinit") +public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -54,25 +54,25 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_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 +@_extern(wasm, module: "TestModule", name: "bjs___Swift_Foundation_Greeter_wrap") +fileprivate func _bjs___Swift_Foundation_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs___Swift_Foundation_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) +@inline(never) fileprivate func _bjs___Swift_Foundation_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_Greeter_wrap_extern(pointer) } -@_expose(wasm, "bjs_Converter_init") -@_cdecl("bjs_Converter_init") -public func _bjs_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_Converters_Converter_init") +@_cdecl("bjs_Utils_Converters_Converter_init") +public func _bjs_Utils_Converters_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Converter() return ret.bridgeJSLowerReturn() @@ -81,9 +81,9 @@ public func _bjs_Converter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Converter_toString") -@_cdecl("bjs_Converter_toString") -public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_Utils_Converters_Converter_toString") +@_cdecl("bjs_Utils_Converters_Converter_toString") +public func _bjs_Utils_Converters_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) let ret = Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -92,9 +92,9 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } -@_expose(wasm, "bjs_Converter_deinit") -@_cdecl("bjs_Converter_deinit") -public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Utils_Converters_Converter_deinit") +@_cdecl("bjs_Utils_Converters_Converter_deinit") +public func _bjs_Utils_Converters_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -104,25 +104,25 @@ public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Utils_Converters_Converter_wrap") +fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Converter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converters_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converters_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_UUID_uuidString") -@_cdecl("bjs_UUID_uuidString") -public func _bjs_UUID_uuidString(_ _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 = UUID.bridgeJSLiftParameter(_self).uuidString() return ret.bridgeJSLowerReturn() @@ -131,9 +131,9 @@ public func _bjs_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_UUID_deinit") -@_cdecl("bjs_UUID_deinit") -public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -143,25 +143,25 @@ public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_UUID_wrap") -fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs___Swift_Foundation_UUID_wrap") +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_UUID_wrap_extern(pointer) +@inline(never) fileprivate func _bjs___Swift_Foundation_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_UUID_wrap_extern(pointer) } -@_expose(wasm, "bjs_Container_init") -@_cdecl("bjs_Container_init") -public func _bjs_Container_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Collections_Container_init") +@_cdecl("bjs_Collections_Container_init") +public func _bjs_Collections_Container_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Container() return ret.bridgeJSLowerReturn() @@ -170,9 +170,9 @@ public func _bjs_Container_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Container_getItems") -@_cdecl("bjs_Container_getItems") -public func _bjs_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_getItems") +@_cdecl("bjs_Collections_Container_getItems") +public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = Container.bridgeJSLiftParameter(_self).getItems() ret.bridgeJSStackPush() @@ -181,9 +181,9 @@ public func _bjs_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_Container_addItem") -@_cdecl("bjs_Container_addItem") -public func _bjs_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_addItem") +@_cdecl("bjs_Collections_Container_addItem") +public func _bjs_Collections_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Container.bridgeJSLiftParameter(_self).addItem(_: Greeter.bridgeJSLiftParameter(item)) #else @@ -191,9 +191,9 @@ public func _bjs_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: Uns #endif } -@_expose(wasm, "bjs_Container_deinit") -@_cdecl("bjs_Container_deinit") -public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_deinit") +@_cdecl("bjs_Collections_Container_deinit") +public func _bjs_Collections_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -203,18 +203,18 @@ public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Container_wrap") -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Collections_Container_wrap") +fileprivate func _bjs_Collections_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Collections_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) +@inline(never) fileprivate func _bjs_Collections_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Collections_Container_wrap_extern(pointer) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index 1bca1dc5d..619fe0689 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_Greeter_init", + "abiName" : "bjs___Swift_Foundation_Greeter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -23,7 +23,7 @@ }, "methods" : [ { - "abiName" : "bjs_Greeter_greet", + "abiName" : "bjs___Swift_Foundation_Greeter_greet", "effects" : { "isAsync" : false, "isStatic" : false, @@ -52,7 +52,7 @@ }, { "constructor" : { - "abiName" : "bjs_Converter_init", + "abiName" : "bjs_Utils_Converters_Converter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -64,7 +64,7 @@ }, "methods" : [ { - "abiName" : "bjs_Converter_toString", + "abiName" : "bjs_Utils_Converters_Converter_toString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -102,7 +102,7 @@ { "methods" : [ { - "abiName" : "bjs_UUID_uuidString", + "abiName" : "bjs___Swift_Foundation_UUID_uuidString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -131,7 +131,7 @@ }, { "constructor" : { - "abiName" : "bjs_Container_init", + "abiName" : "bjs_Collections_Container_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -143,7 +143,7 @@ }, "methods" : [ { - "abiName" : "bjs_Container_getItems", + "abiName" : "bjs_Collections_Container_getItems", "effects" : { "isAsync" : false, "isStatic" : false, @@ -164,7 +164,7 @@ } }, { - "abiName" : "bjs_Container_addItem", + "abiName" : "bjs_Collections_Container_addItem", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index 4b9ecd10a..d376a2a54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -20,9 +20,9 @@ public func _bjs_MyModule_Utils_namespacedFunction() -> Void { #endif } -@_expose(wasm, "bjs_Greeter_init") -@_cdecl("bjs_Greeter_init") -public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_init") +@_cdecl("bjs___Swift_Foundation_Greeter_init") +public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) return ret.bridgeJSLowerReturn() @@ -31,9 +31,9 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe #endif } -@_expose(wasm, "bjs_Greeter_greet") -@_cdecl("bjs_Greeter_greet") -public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_greet") +@_cdecl("bjs___Swift_Foundation_Greeter_greet") +public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = Greeter.bridgeJSLiftParameter(_self).greet() return ret.bridgeJSLowerReturn() @@ -42,9 +42,9 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_Greeter_deinit") -@_cdecl("bjs_Greeter_deinit") -public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_Greeter_deinit") +@_cdecl("bjs___Swift_Foundation_Greeter_deinit") +public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -54,25 +54,25 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_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 +@_extern(wasm, module: "TestModule", name: "bjs___Swift_Foundation_Greeter_wrap") +fileprivate func _bjs___Swift_Foundation_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs___Swift_Foundation_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) +@inline(never) fileprivate func _bjs___Swift_Foundation_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_Greeter_wrap_extern(pointer) } -@_expose(wasm, "bjs_Converter_init") -@_cdecl("bjs_Converter_init") -public func _bjs_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_Converters_Converter_init") +@_cdecl("bjs_Utils_Converters_Converter_init") +public func _bjs_Utils_Converters_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Converter() return ret.bridgeJSLowerReturn() @@ -81,9 +81,9 @@ public func _bjs_Converter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Converter_toString") -@_cdecl("bjs_Converter_toString") -public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_Utils_Converters_Converter_toString") +@_cdecl("bjs_Utils_Converters_Converter_toString") +public func _bjs_Utils_Converters_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) let ret = Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -92,9 +92,9 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } -@_expose(wasm, "bjs_Converter_deinit") -@_cdecl("bjs_Converter_deinit") -public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Utils_Converters_Converter_deinit") +@_cdecl("bjs_Utils_Converters_Converter_deinit") +public func _bjs_Utils_Converters_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -104,25 +104,25 @@ public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Utils_Converters_Converter_wrap") +fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Converter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converters_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converters_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_UUID_uuidString") -@_cdecl("bjs_UUID_uuidString") -public func _bjs_UUID_uuidString(_ _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 = UUID.bridgeJSLiftParameter(_self).uuidString() return ret.bridgeJSLowerReturn() @@ -131,9 +131,9 @@ public func _bjs_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_UUID_deinit") -@_cdecl("bjs_UUID_deinit") -public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -143,25 +143,25 @@ public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_UUID_wrap") -fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs___Swift_Foundation_UUID_wrap") +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_UUID_wrap_extern(pointer) +@inline(never) fileprivate func _bjs___Swift_Foundation_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_UUID_wrap_extern(pointer) } -@_expose(wasm, "bjs_Container_init") -@_cdecl("bjs_Container_init") -public func _bjs_Container_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Collections_Container_init") +@_cdecl("bjs_Collections_Container_init") +public func _bjs_Collections_Container_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Container() return ret.bridgeJSLowerReturn() @@ -170,9 +170,9 @@ public func _bjs_Container_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Container_getItems") -@_cdecl("bjs_Container_getItems") -public func _bjs_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_getItems") +@_cdecl("bjs_Collections_Container_getItems") +public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = Container.bridgeJSLiftParameter(_self).getItems() ret.bridgeJSStackPush() @@ -181,9 +181,9 @@ public func _bjs_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_Container_addItem") -@_cdecl("bjs_Container_addItem") -public func _bjs_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_addItem") +@_cdecl("bjs_Collections_Container_addItem") +public func _bjs_Collections_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Container.bridgeJSLiftParameter(_self).addItem(_: Greeter.bridgeJSLiftParameter(item)) #else @@ -191,9 +191,9 @@ public func _bjs_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: Uns #endif } -@_expose(wasm, "bjs_Container_deinit") -@_cdecl("bjs_Container_deinit") -public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Collections_Container_deinit") +@_cdecl("bjs_Collections_Container_deinit") +public func _bjs_Collections_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -203,18 +203,18 @@ public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Container_wrap") -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_Collections_Container_wrap") +fileprivate func _bjs_Collections_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Collections_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) +@inline(never) fileprivate func _bjs_Collections_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Collections_Container_wrap_extern(pointer) } \ 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 17ac74a82..936ae6b3a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -30,6 +30,12 @@ declare global { }; type PortTag = typeof PortValues[keyof typeof PortValues]; } + namespace Formatting { + class Converter { + constructor(); + format(value: number): string; + } + } namespace Networking { namespace API { class HTTPServer { @@ -92,11 +98,19 @@ export interface HTTPServer extends SwiftHeapObject { export interface TestServer extends SwiftHeapObject { call(method: Networking.APIV2.Internal.SupportedMethodTag): void; } +export interface Converter extends SwiftHeapObject { + format(value: number): string; +} export type Exports = { Configuration: { LogLevel: LogLevelObject Port: PortObject }, + Formatting: { + Converter: { + new(): Converter; + } + }, Networking: { API: { HTTPServer: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index f39031341..7c3166d36 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -232,15 +232,19 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Utils_Converter_wrap"] = function(pointer) { const obj = _exports.Utils.Converter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_HTTPServer_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Formatting_Converter_wrap"] = function(pointer) { + const obj = _exports.Formatting.Converter.__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_Networking_API_HTTPServer_wrap"] = function(pointer) { const obj = _exports.Networking.API.HTTPServer.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_TestServer_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Networking_APIV2_Internal_TestServer_wrap"] = function(pointer) { const obj = _exports.Networking.APIV2.Internal.TestServer.__construct(pointer); return swift.memory.retain(obj); }; @@ -287,56 +291,75 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype); } constructor() { - const ret = instance.exports.bjs_Converter_init(); + const ret = instance.exports.bjs_Utils_Converter_init(); return Converter.__construct(ret); } toString(value) { - instance.exports.bjs_Converter_toString(this.pointer, value); + instance.exports.bjs_Utils_Converter_toString(this.pointer, value); const ret = tmpRetString; tmpRetString = undefined; return ret; } get precision() { - const ret = instance.exports.bjs_Converter_precision_get(this.pointer); + const ret = instance.exports.bjs_Utils_Converter_precision_get(this.pointer); return ret; } set precision(value) { - instance.exports.bjs_Converter_precision_set(this.pointer, value); + instance.exports.bjs_Utils_Converter_precision_set(this.pointer, value); } } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_HTTPServer_deinit, HTTPServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype); } constructor() { - const ret = instance.exports.bjs_HTTPServer_init(); + const ret = instance.exports.bjs_Networking_API_HTTPServer_init(); return HTTPServer.__construct(ret); } call(method) { - instance.exports.bjs_HTTPServer_call(this.pointer, method); + instance.exports.bjs_Networking_API_HTTPServer_call(this.pointer, method); } } class TestServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestServer_deinit, TestServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype); } constructor() { - const ret = instance.exports.bjs_TestServer_init(); + const ret = instance.exports.bjs_Networking_APIV2_Internal_TestServer_init(); return TestServer.__construct(ret); } call(method) { - instance.exports.bjs_TestServer_call(this.pointer, method); + instance.exports.bjs_Networking_APIV2_Internal_TestServer_call(this.pointer, method); + } + } + class Converter extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype); + } + + constructor() { + const ret = instance.exports.bjs_Formatting_Converter_init(); + return Converter.__construct(ret); + } + format(value) { + instance.exports.bjs_Formatting_Converter_format(this.pointer, value); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } } if (typeof globalThis.Configuration === 'undefined') { globalThis.Configuration = {}; } + if (typeof globalThis.Formatting === 'undefined') { + globalThis.Formatting = {}; + } if (typeof globalThis.Networking === 'undefined') { globalThis.Networking = {}; } @@ -366,6 +389,9 @@ export async function createInstantiator(options, swift) { LogLevel: LogLevelValues, Port: PortValues, }, + Formatting: { + Converter, + }, Networking: { API: { HTTPServer, @@ -410,6 +436,7 @@ export async function createInstantiator(options, swift) { globalThis.Utils.Converter = exports.Utils.Converter; globalThis.Networking.API.HTTPServer = exports.Networking.API.HTTPServer; globalThis.Networking.APIV2.Internal.TestServer = exports.Networking.APIV2.Internal.TestServer; + globalThis.Formatting.Converter = exports.Formatting.Converter; globalThis.Services.Graph.GraphOperations.createGraph = exports.Services.Graph.GraphOperations.createGraph; globalThis.Services.Graph.GraphOperations.nodeCount = exports.Services.Graph.GraphOperations.nodeCount; globalThis.Services.Graph.GraphOperations.validate = exports.Services.Graph.GraphOperations.validate; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index bc8e1601d..23d872d27 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -64,11 +64,19 @@ export interface HTTPServer extends SwiftHeapObject { export interface TestServer extends SwiftHeapObject { call(method: Networking.APIV2.Internal.SupportedMethodTag): void; } +export interface Converter extends SwiftHeapObject { + format(value: number): string; +} export type Exports = { Configuration: { LogLevel: LogLevelObject Port: PortObject }, + Formatting: { + Converter: { + new(): Converter; + } + }, Networking: { API: { HTTPServer: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index effa7feec..6eea84ffa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -213,15 +213,19 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Utils_Converter_wrap"] = function(pointer) { const obj = _exports.Utils.Converter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_HTTPServer_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Formatting_Converter_wrap"] = function(pointer) { + const obj = _exports.Formatting.Converter.__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_Networking_API_HTTPServer_wrap"] = function(pointer) { const obj = _exports.Networking.API.HTTPServer.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_TestServer_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Networking_APIV2_Internal_TestServer_wrap"] = function(pointer) { const obj = _exports.Networking.APIV2.Internal.TestServer.__construct(pointer); return swift.memory.retain(obj); }; @@ -268,51 +272,67 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype); } constructor() { - const ret = instance.exports.bjs_Converter_init(); + const ret = instance.exports.bjs_Utils_Converter_init(); return Converter.__construct(ret); } toString(value) { - instance.exports.bjs_Converter_toString(this.pointer, value); + instance.exports.bjs_Utils_Converter_toString(this.pointer, value); const ret = tmpRetString; tmpRetString = undefined; return ret; } get precision() { - const ret = instance.exports.bjs_Converter_precision_get(this.pointer); + const ret = instance.exports.bjs_Utils_Converter_precision_get(this.pointer); return ret; } set precision(value) { - instance.exports.bjs_Converter_precision_set(this.pointer, value); + instance.exports.bjs_Utils_Converter_precision_set(this.pointer, value); } } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_HTTPServer_deinit, HTTPServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype); } constructor() { - const ret = instance.exports.bjs_HTTPServer_init(); + const ret = instance.exports.bjs_Networking_API_HTTPServer_init(); return HTTPServer.__construct(ret); } call(method) { - instance.exports.bjs_HTTPServer_call(this.pointer, method); + instance.exports.bjs_Networking_API_HTTPServer_call(this.pointer, method); } } class TestServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestServer_deinit, TestServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype); } constructor() { - const ret = instance.exports.bjs_TestServer_init(); + const ret = instance.exports.bjs_Networking_APIV2_Internal_TestServer_init(); return TestServer.__construct(ret); } call(method) { - instance.exports.bjs_TestServer_call(this.pointer, method); + instance.exports.bjs_Networking_APIV2_Internal_TestServer_call(this.pointer, method); + } + } + class Converter extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype); + } + + constructor() { + const ret = instance.exports.bjs_Formatting_Converter_init(); + return Converter.__construct(ret); + } + format(value) { + instance.exports.bjs_Formatting_Converter_format(this.pointer, value); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } } const exports = { @@ -320,6 +340,9 @@ export async function createInstantiator(options, swift) { LogLevel: LogLevelValues, Port: PortValues, }, + Formatting: { + Converter, + }, Networking: { API: { HTTPServer, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 9460ed45e..dd0e0c55e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -188,7 +188,7 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_GlobalClass_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_GlobalAPI_GlobalClass_wrap"] = function(pointer) { const obj = _exports.GlobalAPI.GlobalClass.__construct(pointer); return swift.memory.retain(obj); }; @@ -235,15 +235,15 @@ export async function createInstantiator(options, swift) { } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalClass_deinit, GlobalClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype); } constructor() { - const ret = instance.exports.bjs_GlobalClass_init(); + const ret = instance.exports.bjs_GlobalAPI_GlobalClass_init(); return GlobalClass.__construct(ret); } greet() { - instance.exports.bjs_GlobalClass_greet(this.pointer); + instance.exports.bjs_GlobalAPI_GlobalClass_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 5b99112ab..523df73cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -188,7 +188,7 @@ export async function createInstantiator(options, swift) { if (!importObject["GlobalModule"]) { importObject["GlobalModule"] = {}; } - importObject["GlobalModule"]["bjs_GlobalClass_wrap"] = function(pointer) { + importObject["GlobalModule"]["bjs_GlobalAPI_GlobalClass_wrap"] = function(pointer) { const obj = _exports.GlobalAPI.GlobalClass.__construct(pointer); return swift.memory.retain(obj); }; @@ -196,7 +196,7 @@ export async function createInstantiator(options, swift) { if (!importObject["PrivateModule"]) { importObject["PrivateModule"] = {}; } - importObject["PrivateModule"]["bjs_PrivateClass_wrap"] = function(pointer) { + importObject["PrivateModule"]["bjs_PrivateAPI_PrivateClass_wrap"] = function(pointer) { const obj = _exports.PrivateAPI.PrivateClass.__construct(pointer); return swift.memory.retain(obj); }; @@ -243,15 +243,15 @@ export async function createInstantiator(options, swift) { } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalClass_deinit, GlobalClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype); } constructor() { - const ret = instance.exports.bjs_GlobalClass_init(); + const ret = instance.exports.bjs_GlobalAPI_GlobalClass_init(); return GlobalClass.__construct(ret); } greet() { - instance.exports.bjs_GlobalClass_greet(this.pointer); + instance.exports.bjs_GlobalAPI_GlobalClass_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -259,15 +259,15 @@ export async function createInstantiator(options, swift) { } class PrivateClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateClass_deinit, PrivateClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype); } constructor() { - const ret = instance.exports.bjs_PrivateClass_init(); + const ret = instance.exports.bjs_PrivateAPI_PrivateClass_init(); return PrivateClass.__construct(ret); } greet() { - instance.exports.bjs_PrivateClass_greet(this.pointer); + instance.exports.bjs_PrivateAPI_PrivateClass_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index e600c1eb9..4d08957d0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -188,7 +188,7 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_PrivateClass_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_PrivateAPI_PrivateClass_wrap"] = function(pointer) { const obj = _exports.PrivateAPI.PrivateClass.__construct(pointer); return swift.memory.retain(obj); }; @@ -235,15 +235,15 @@ export async function createInstantiator(options, swift) { } class PrivateClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateClass_deinit, PrivateClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype); } constructor() { - const ret = instance.exports.bjs_PrivateClass_init(); + const ret = instance.exports.bjs_PrivateAPI_PrivateClass_init(); return PrivateClass.__construct(ret); } greet() { - instance.exports.bjs_PrivateClass_greet(this.pointer); + instance.exports.bjs_PrivateAPI_PrivateClass_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 303dd5274..ac55ae750 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -188,19 +188,19 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_Container_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Collections_Container_wrap"] = function(pointer) { const obj = _exports.Collections.Container.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Utils_Converters_Converter_wrap"] = function(pointer) { const obj = _exports.Utils.Converters.Converter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs___Swift_Foundation_Greeter_wrap"] = function(pointer) { const obj = _exports.__Swift.Foundation.Greeter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_UUID_wrap"] = function(pointer) { + importObject["TestModule"]["bjs___Swift_Foundation_UUID_wrap"] = function(pointer) { const obj = _exports.__Swift.Foundation.UUID.__construct(pointer); return swift.memory.retain(obj); }; @@ -247,17 +247,17 @@ export async function createInstantiator(options, swift) { } class Greeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_Greeter_deinit, Greeter.prototype); } constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); - const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); + const ret = instance.exports.bjs___Swift_Foundation_Greeter_init(nameId, nameBytes.length); return Greeter.__construct(ret); } greet() { - instance.exports.bjs_Greeter_greet(this.pointer); + instance.exports.bjs___Swift_Foundation_Greeter_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -265,15 +265,15 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype); } constructor() { - const ret = instance.exports.bjs_Converter_init(); + const ret = instance.exports.bjs_Utils_Converters_Converter_init(); return Converter.__construct(ret); } toString(value) { - instance.exports.bjs_Converter_toString(this.pointer, value); + instance.exports.bjs_Utils_Converters_Converter_toString(this.pointer, value); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -281,11 +281,11 @@ export async function createInstantiator(options, swift) { } class UUID extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UUID_deinit, UUID.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype); } uuidString() { - instance.exports.bjs_UUID_uuidString(this.pointer); + instance.exports.bjs___Swift_Foundation_UUID_uuidString(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -293,15 +293,15 @@ export async function createInstantiator(options, swift) { } class Container extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Container_deinit, Container.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype); } constructor() { - const ret = instance.exports.bjs_Container_init(); + const ret = instance.exports.bjs_Collections_Container_init(); return Container.__construct(ret); } getItems() { - instance.exports.bjs_Container_getItems(this.pointer); + instance.exports.bjs_Collections_Container_getItems(this.pointer); const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { @@ -313,7 +313,7 @@ export async function createInstantiator(options, swift) { return arrayResult; } addItem(item) { - instance.exports.bjs_Container_addItem(this.pointer, item.pointer); + instance.exports.bjs_Collections_Container_addItem(this.pointer, item.pointer); } } if (typeof globalThis.Collections === 'undefined') { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 85c45665d..1fb247cbe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -188,19 +188,19 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } - importObject["TestModule"]["bjs_Container_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Collections_Container_wrap"] = function(pointer) { const obj = _exports.Collections.Container.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs_Utils_Converters_Converter_wrap"] = function(pointer) { const obj = _exports.Utils.Converters.Converter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { + importObject["TestModule"]["bjs___Swift_Foundation_Greeter_wrap"] = function(pointer) { const obj = _exports.__Swift.Foundation.Greeter.__construct(pointer); return swift.memory.retain(obj); }; - importObject["TestModule"]["bjs_UUID_wrap"] = function(pointer) { + importObject["TestModule"]["bjs___Swift_Foundation_UUID_wrap"] = function(pointer) { const obj = _exports.__Swift.Foundation.UUID.__construct(pointer); return swift.memory.retain(obj); }; @@ -247,17 +247,17 @@ export async function createInstantiator(options, swift) { } class Greeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_Greeter_deinit, Greeter.prototype); } constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); - const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); + const ret = instance.exports.bjs___Swift_Foundation_Greeter_init(nameId, nameBytes.length); return Greeter.__construct(ret); } greet() { - instance.exports.bjs_Greeter_greet(this.pointer); + instance.exports.bjs___Swift_Foundation_Greeter_greet(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -265,15 +265,15 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype); } constructor() { - const ret = instance.exports.bjs_Converter_init(); + const ret = instance.exports.bjs_Utils_Converters_Converter_init(); return Converter.__construct(ret); } toString(value) { - instance.exports.bjs_Converter_toString(this.pointer, value); + instance.exports.bjs_Utils_Converters_Converter_toString(this.pointer, value); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -281,11 +281,11 @@ export async function createInstantiator(options, swift) { } class UUID extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UUID_deinit, UUID.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype); } uuidString() { - instance.exports.bjs_UUID_uuidString(this.pointer); + instance.exports.bjs___Swift_Foundation_UUID_uuidString(this.pointer); const ret = tmpRetString; tmpRetString = undefined; return ret; @@ -293,15 +293,15 @@ export async function createInstantiator(options, swift) { } class Container extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Container_deinit, Container.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype); } constructor() { - const ret = instance.exports.bjs_Container_init(); + const ret = instance.exports.bjs_Collections_Container_init(); return Container.__construct(ret); } getItems() { - instance.exports.bjs_Container_getItems(this.pointer); + instance.exports.bjs_Collections_Container_getItems(this.pointer); const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { @@ -313,7 +313,7 @@ export async function createInstantiator(options, swift) { return arrayResult; } addItem(item) { - instance.exports.bjs_Container_addItem(this.pointer, item.pointer); + instance.exports.bjs_Collections_Container_addItem(this.pointer, item.pointer); } } const exports = { diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index b34b78bb0..ca9968838 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -176,9 +176,9 @@ public func _bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedDou #endif } -@_expose(wasm, "bjs_TestHTTPServer_init") -@_cdecl("bjs_TestHTTPServer_init") -public func _bjs_TestHTTPServer_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_GlobalNetworking_API_TestHTTPServer_init") +@_cdecl("bjs_GlobalNetworking_API_TestHTTPServer_init") +public func _bjs_GlobalNetworking_API_TestHTTPServer_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = GlobalNetworking.API.TestHTTPServer() return ret.bridgeJSLowerReturn() @@ -187,9 +187,9 @@ public func _bjs_TestHTTPServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_TestHTTPServer_call") -@_cdecl("bjs_TestHTTPServer_call") -public func _bjs_TestHTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { +@_expose(wasm, "bjs_GlobalNetworking_API_TestHTTPServer_call") +@_cdecl("bjs_GlobalNetworking_API_TestHTTPServer_call") +public func _bjs_GlobalNetworking_API_TestHTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) GlobalNetworking.API.TestHTTPServer.bridgeJSLiftParameter(_self).call(_: GlobalNetworking.API.CallMethod.bridgeJSLiftParameter(method)) #else @@ -197,9 +197,9 @@ public func _bjs_TestHTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: #endif } -@_expose(wasm, "bjs_TestHTTPServer_deinit") -@_cdecl("bjs_TestHTTPServer_deinit") -public func _bjs_TestHTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_GlobalNetworking_API_TestHTTPServer_deinit") +@_cdecl("bjs_GlobalNetworking_API_TestHTTPServer_deinit") +public func _bjs_GlobalNetworking_API_TestHTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -209,25 +209,25 @@ public func _bjs_TestHTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo extension GlobalNetworking.API.TestHTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestHTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalNetworking_API_TestHTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_TestHTTPServer_wrap") -fileprivate func _bjs_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_GlobalNetworking_API_TestHTTPServer_wrap") +fileprivate func _bjs_GlobalNetworking_API_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_GlobalNetworking_API_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_TestHTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TestHTTPServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_GlobalNetworking_API_TestHTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GlobalNetworking_API_TestHTTPServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_TestInternalServer_init") -@_cdecl("bjs_TestInternalServer_init") -public func _bjs_TestInternalServer_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_init") +@_cdecl("bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_init") +public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Internal.TestInternalServer() return ret.bridgeJSLowerReturn() @@ -236,9 +236,9 @@ public func _bjs_TestInternalServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_TestInternalServer_call") -@_cdecl("bjs_TestInternalServer_call") -public func _bjs_TestInternalServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { +@_expose(wasm, "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call") +@_cdecl("bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call") +public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) Internal.TestInternalServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedServerMethod.bridgeJSLiftParameter(method)) #else @@ -246,9 +246,9 @@ public func _bjs_TestInternalServer_call(_ _self: UnsafeMutableRawPointer, _ met #endif } -@_expose(wasm, "bjs_TestInternalServer_deinit") -@_cdecl("bjs_TestInternalServer_deinit") -public func _bjs_TestInternalServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_deinit") +@_cdecl("bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_deinit") +public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -258,25 +258,25 @@ public func _bjs_TestInternalServer_deinit(_ pointer: UnsafeMutableRawPointer) - extension Internal.TestInternalServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestInternalServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_TestInternalServer_wrap") -fileprivate func _bjs_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap") +fileprivate func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_TestInternalServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TestInternalServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_PublicConverter_init") -@_cdecl("bjs_PublicConverter_init") -public func _bjs_PublicConverter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_GlobalUtils_PublicConverter_init") +@_cdecl("bjs_GlobalUtils_PublicConverter_init") +public func _bjs_GlobalUtils_PublicConverter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = GlobalUtils.PublicConverter() return ret.bridgeJSLowerReturn() @@ -285,9 +285,9 @@ public func _bjs_PublicConverter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_PublicConverter_toString") -@_cdecl("bjs_PublicConverter_toString") -public func _bjs_PublicConverter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_GlobalUtils_PublicConverter_toString") +@_cdecl("bjs_GlobalUtils_PublicConverter_toString") +public func _bjs_GlobalUtils_PublicConverter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) let ret = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -296,9 +296,9 @@ public func _bjs_PublicConverter_toString(_ _self: UnsafeMutableRawPointer, _ va #endif } -@_expose(wasm, "bjs_PublicConverter_deinit") -@_cdecl("bjs_PublicConverter_deinit") -public func _bjs_PublicConverter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_GlobalUtils_PublicConverter_deinit") +@_cdecl("bjs_GlobalUtils_PublicConverter_deinit") +public func _bjs_GlobalUtils_PublicConverter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) Unmanaged.fromOpaque(pointer).release() #else @@ -308,18 +308,18 @@ public func _bjs_PublicConverter_deinit(_ pointer: UnsafeMutableRawPointer) -> V extension GlobalUtils.PublicConverter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PublicConverter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalUtils_PublicConverter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_PublicConverter_wrap") -fileprivate func _bjs_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_GlobalUtils_PublicConverter_wrap") +fileprivate func _bjs_GlobalUtils_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_GlobalUtils_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PublicConverter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_GlobalUtils_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GlobalUtils_PublicConverter_wrap_extern(pointer) } \ No newline at end of file diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index e7bcf59b6..2eeb8ed2d 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -3,7 +3,7 @@ "classes" : [ { "constructor" : { - "abiName" : "bjs_TestHTTPServer_init", + "abiName" : "bjs_GlobalNetworking_API_TestHTTPServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -15,7 +15,7 @@ }, "methods" : [ { - "abiName" : "bjs_TestHTTPServer_call", + "abiName" : "bjs_GlobalNetworking_API_TestHTTPServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -56,7 +56,7 @@ }, { "constructor" : { - "abiName" : "bjs_TestInternalServer_init", + "abiName" : "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -68,7 +68,7 @@ }, "methods" : [ { - "abiName" : "bjs_TestInternalServer_call", + "abiName" : "bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -111,7 +111,7 @@ }, { "constructor" : { - "abiName" : "bjs_PublicConverter_init", + "abiName" : "bjs_GlobalUtils_PublicConverter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -123,7 +123,7 @@ }, "methods" : [ { - "abiName" : "bjs_PublicConverter_toString", + "abiName" : "bjs_GlobalUtils_PublicConverter_toString", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e8a0b9476..00d1b47e3 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -7103,9 +7103,9 @@ fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_PackageGreeter_wrap_extern(pointer) } -@_expose(wasm, "bjs_Converter_init") -@_cdecl("bjs_Converter_init") -public func _bjs_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_Converter_init") +@_cdecl("bjs_Utils_Converter_init") +public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = Utils.Converter() return ret.bridgeJSLowerReturn() @@ -7114,9 +7114,9 @@ public func _bjs_Converter_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Converter_toString") -@_cdecl("bjs_Converter_toString") -public func _bjs_Converter_toString(_ _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) let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() @@ -7125,9 +7125,9 @@ public func _bjs_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: I #endif } -@_expose(wasm, "bjs_Converter_precision_get") -@_cdecl("bjs_Converter_precision_get") -public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_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 = Utils.Converter.bridgeJSLiftParameter(_self).precision return ret.bridgeJSLowerReturn() @@ -7136,9 +7136,9 @@ public func _bjs_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> In #endif } -@_expose(wasm, "bjs_Converter_precision_set") -@_cdecl("bjs_Converter_precision_set") -public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: 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) Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) #else @@ -7146,9 +7146,9 @@ public func _bjs_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ val #endif } -@_expose(wasm, "bjs_Converter_deinit") -@_cdecl("bjs_Converter_deinit") -public func _bjs_Converter_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() #else @@ -7158,25 +7158,25 @@ public func _bjs_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_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_Converter_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_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Converter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_HTTPServer_init") -@_cdecl("bjs_HTTPServer_init") -public func _bjs_HTTPServer_init() -> 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 = Networking.API.HTTPServer() return ret.bridgeJSLowerReturn() @@ -7185,9 +7185,9 @@ public func _bjs_HTTPServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_HTTPServer_call") -@_cdecl("bjs_HTTPServer_call") -public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) #else @@ -7195,9 +7195,9 @@ public func _bjs_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_HTTPServer_deinit") -@_cdecl("bjs_HTTPServer_deinit") -public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -7207,25 +7207,25 @@ public func _bjs_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_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_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_HTTPServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Networking_API_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Networking_API_HTTPServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_UUID_init") -@_cdecl("bjs_UUID_init") -public func _bjs_UUID_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { +@_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 = UUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() @@ -7234,9 +7234,9 @@ public func _bjs_UUID_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeM #endif } -@_expose(wasm, "bjs_UUID_uuidString") -@_cdecl("bjs_UUID_uuidString") -public func _bjs_UUID_uuidString(_ _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 = UUID.bridgeJSLiftParameter(_self).uuidString() return ret.bridgeJSLowerReturn() @@ -7245,9 +7245,9 @@ public func _bjs_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_expose(wasm, "bjs_UUID_deinit") -@_cdecl("bjs_UUID_deinit") -public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> 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) Unmanaged.fromOpaque(pointer).release() #else @@ -7257,25 +7257,25 @@ public func _bjs_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_UUID_wrap") -fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_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_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_UUID_wrap_extern(pointer) +@inline(never) fileprivate func _bjs___Swift_Foundation_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_UUID_wrap_extern(pointer) } -@_expose(wasm, "bjs_TestServer_init") -@_cdecl("bjs_TestServer_init") -public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { +@_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 = Internal.TestServer() return ret.bridgeJSLowerReturn() @@ -7284,9 +7284,9 @@ public func _bjs_TestServer_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_TestServer_call") -@_cdecl("bjs_TestServer_call") -public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> 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) Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) #else @@ -7294,9 +7294,9 @@ public func _bjs_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int #endif } -@_expose(wasm, "bjs_TestServer_deinit") -@_cdecl("bjs_TestServer_deinit") -public func _bjs_TestServer_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() #else @@ -7306,20 +7306,20 @@ public func _bjs_TestServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_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_TestServer_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_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TestServer_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_SimplePropertyHolder_init") diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 66027d719..e635af160 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -835,7 +835,7 @@ }, { "constructor" : { - "abiName" : "bjs_Converter_init", + "abiName" : "bjs_Utils_Converter_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -847,7 +847,7 @@ }, "methods" : [ { - "abiName" : "bjs_Converter_toString", + "abiName" : "bjs_Utils_Converter_toString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -898,7 +898,7 @@ }, { "constructor" : { - "abiName" : "bjs_HTTPServer_init", + "abiName" : "bjs_Networking_API_HTTPServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -910,7 +910,7 @@ }, "methods" : [ { - "abiName" : "bjs_HTTPServer_call", + "abiName" : "bjs_Networking_API_HTTPServer_call", "effects" : { "isAsync" : false, "isStatic" : false, @@ -951,7 +951,7 @@ }, { "constructor" : { - "abiName" : "bjs_UUID_init", + "abiName" : "bjs___Swift_Foundation_UUID_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -971,7 +971,7 @@ }, "methods" : [ { - "abiName" : "bjs_UUID_uuidString", + "abiName" : "bjs___Swift_Foundation_UUID_uuidString", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1000,7 +1000,7 @@ }, { "constructor" : { - "abiName" : "bjs_TestServer_init", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1012,7 +1012,7 @@ }, "methods" : [ { - "abiName" : "bjs_TestServer_call", + "abiName" : "bjs_Networking_APIV2_Internal_TestServer_call", "effects" : { "isAsync" : false, "isStatic" : false, From bcb952c581db76594c04d92835016ad979979dc7 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Wed, 25 Feb 2026 21:22:35 +0900 Subject: [PATCH 010/140] BridgeJS: Remove `_BridgedSwiftDictionaryStackType` protocol --- .../JavaScriptKit/BridgeJSIntrinsics.swift | 39 +++++++------------ 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 0b0dfa982..87f83d8a9 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1920,25 +1920,9 @@ extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, E // MARK: - Dictionary Support -public protocol _BridgedSwiftDictionaryStackType: _BridgedSwiftTypeLoweredIntoVoidType, - _BridgedSwiftStackType -where StackLiftResult == Self { - associatedtype DictionaryValue: _BridgedSwiftStackType - where DictionaryValue.StackLiftResult == DictionaryValue -} - extension Dictionary: _BridgedSwiftStackType where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { public typealias StackLiftResult = [String: Value] - // Lowering/return use stack-based encoding, so dictionary also behaves like a void-lowered type. - // Optional/JSUndefinedOr wrappers rely on this conformance to push an isSome flag and - // then delegate to the stack-based lowering defined below. - // swiftlint:disable:next type_name -} - -extension Dictionary: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftDictionaryStackType -where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { - public typealias DictionaryValue = Value @_spi(BridgeJS) public static func bridgeJSStackPop() -> [String: Value] { let count = Int(_swift_js_pop_i32()) @@ -1960,7 +1944,10 @@ where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Val } _swift_js_push_i32(count) } +} +extension Dictionary: _BridgedSwiftTypeLoweredIntoVoidType +where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> [String: Value] { bridgeJSStackPop() } @@ -1975,10 +1962,9 @@ where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Val } } -extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { - typealias DictionaryValue = Wrapped.DictionaryValue - - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { +extension _BridgedAsOptional { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 + where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { switch asOptional { case .none: return 0 @@ -1988,22 +1974,25 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { + @_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() as! Wrapped)) + return Self(optional: Dictionary.bridgeJSStackPop()) } - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { + @_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() as! Wrapped)) + return Self(optional: Dictionary.bridgeJSStackPop()) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void + where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { Wrapped.bridgeJSStackPushAsOptional(asOptional) } } From cf60e851af28ec267e54e3b8d9376ed72e2e4388 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Wed, 25 Feb 2026 21:22:50 +0900 Subject: [PATCH 011/140] BridgeJS: Migrate Dictionary tests to use conventional style --- .../Sources/BridgeJSCore/ExportSwift.swift | 40 +-- .../DictionarySupportTests.swift | 54 +++ .../DictionaryTests.swift | 96 ----- .../Generated/BridgeJS.swift | 210 +++++------ .../Generated/JavaScript/BridgeJS.json | 336 +++++++++--------- .../JavaScript/DictionarySupportTests.mjs | 26 ++ .../JavaScript/OptionalSupportTests.mjs | 6 + .../OptionalSupportTests.swift | 27 +- Tests/prelude.mjs | 26 +- 9 files changed, 384 insertions(+), 437 deletions(-) create mode 100644 Tests/BridgeJSRuntimeTests/DictionarySupportTests.swift delete mode 100644 Tests/BridgeJSRuntimeTests/DictionaryTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 6e5c17141..d6912bbd7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -724,14 +724,12 @@ struct StackCodegen { switch type { case .string, .int, .uint, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, - .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array: + .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary: return "\(raw: type.swiftType).bridgeJSStackPop()" case .jsObject(let className?): return "\(raw: className)(unsafelyWrapping: JSObject.bridgeJSStackPop())" case .nullable(let wrappedType, let kind): return liftNullableExpression(wrappedType: wrappedType, kind: kind) - case .dictionary(let valueType): - return liftDictionaryExpression(valueType: valueType) case .closure: return "JSObject.bridgeJSStackPop()" case .void, .namespaceEnum: @@ -739,42 +737,6 @@ struct StackCodegen { } } - func liftDictionaryExpression(valueType: BridgeType) -> ExprSyntax { - switch valueType { - case .jsObject(let className?) where className != "JSObject": - return """ - { - let __dict = [String: JSObject].bridgeJSStackPop() - return __dict.mapValues { \(raw: className)(unsafelyWrapping: $0) } - }() - """ - case .nullable, .closure: - return liftDictionaryExpressionInline(valueType: valueType) - case .void, .namespaceEnum: - fatalError("Invalid dictionary value type: \(valueType)") - default: - return "[String: \(raw: valueType.swiftType)].bridgeJSStackPop()" - } - } - - private func liftDictionaryExpressionInline(valueType: BridgeType) -> ExprSyntax { - let valueLift = liftExpression(for: valueType) - let swiftTypeName = valueType.swiftType - return """ - { - let __count = Int(_swift_js_pop_i32()) - var __result: [String: \(raw: swiftTypeName)] = [:] - __result.reserveCapacity(__count) - for _ in 0..<__count { - let __value = \(valueLift) - let __key = String.bridgeJSStackPop() - __result[__key] = __value - } - return __result - }() - """ - } - private func liftNullableExpression(wrappedType: BridgeType, kind: JSOptionalKind) -> ExprSyntax { let typeName = kind == .null ? "Optional" : "JSUndefinedOr" switch wrappedType { diff --git a/Tests/BridgeJSRuntimeTests/DictionarySupportTests.swift b/Tests/BridgeJSRuntimeTests/DictionarySupportTests.swift new file mode 100644 index 000000000..8f935da12 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/DictionarySupportTests.swift @@ -0,0 +1,54 @@ +@_spi(BridgeJS) import JavaScriptKit +import XCTest + +@JSClass struct DictionarySupportImports { + @JSFunction static func jsRoundTripDictionaryInt(_ values: [String: Int]) throws(JSException) -> [String: Int] + @JSFunction static func jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] + @JSFunction static func jsRoundTripDictionaryDouble( + _ values: [String: Double] + ) throws(JSException) -> [String: Double] + @JSFunction static func jsRoundTripDictionaryJSObject( + _ values: [String: JSObject] + ) throws(JSException) -> [String: JSObject] + @JSFunction static func jsRoundTripDictionaryJSValue( + _ values: [String: JSValue] + ) throws(JSException) -> [String: JSValue] + @JSFunction static func jsRoundTripDictionaryDoubleArray( + _ values: [String: [Double]] + ) throws(JSException) -> [String: [Double]] +} + +final class DictionarySupportTests: XCTestCase { + + private func roundTripTest(_ fn: ([String: T]) throws -> [String: T], _ input: [String: T]) throws { + let result = try fn(input) + XCTAssertEqual(result, input) + } + + func testRoundTripDictionaryInt() throws { + try roundTripTest(DictionarySupportImports.jsRoundTripDictionaryInt, ["a": 1, "b": 2]) + } + + func testRoundTripDictionaryBool() throws { + try roundTripTest(DictionarySupportImports.jsRoundTripDictionaryBool, ["yes": true, "no": false]) + } + + func testRoundTripDictionaryDouble() throws { + try roundTripTest(DictionarySupportImports.jsRoundTripDictionaryDouble, ["pi": 3.14, "tau": 6.28]) + } + + func testRoundTripDictionaryJSObject() throws { + try roundTripTest(DictionarySupportImports.jsRoundTripDictionaryJSObject, ["global": JSObject.global]) + } + + func testRoundTripDictionaryJSValue() throws { + try roundTripTest( + DictionarySupportImports.jsRoundTripDictionaryJSValue, + ["number": .number(123.5), "boolean": .boolean(true), "string": .string("hello"), "null": .null] + ) + } + + func testRoundTripDictionaryDoubleArray() throws { + try roundTripTest(DictionarySupportImports.jsRoundTripDictionaryDoubleArray, ["xs": [1.0, 2.5], "ys": []]) + } +} diff --git a/Tests/BridgeJSRuntimeTests/DictionaryTests.swift b/Tests/BridgeJSRuntimeTests/DictionaryTests.swift deleted file mode 100644 index 95f2706e6..000000000 --- a/Tests/BridgeJSRuntimeTests/DictionaryTests.swift +++ /dev/null @@ -1,96 +0,0 @@ -@_spi(BridgeJS) import JavaScriptKit -import XCTest - -final class DictionaryTests: XCTestCase { - func testRoundTripDictionary() throws { - let input: [String: Int] = ["a": 1, "b": 2] - let result = try jsRoundTripDictionary(input) - XCTAssertEqual(result, input) - } - - func testRoundTripDictionaryBool() throws { - let input: [String: Bool] = ["yes": true, "no": false] - let result = try jsRoundTripDictionaryBool(input) - XCTAssertEqual(result, input) - } - - func testRoundTripDictionaryDouble() throws { - let input: [String: Double] = ["pi": 3.14, "tau": 6.28] - let result = try jsRoundTripDictionaryDouble(input) - XCTAssertEqual(result, input) - } - - func testRoundTripDictionaryJSObject() throws { - let global = JSObject.global - let input: [String: JSObject] = [ - "global": global - ] - let result = try jsRoundTripDictionaryJSObject(input) - XCTAssertEqual(result, input) - } - - func testRoundTripDictionaryJSValue() throws { - let input: [String: JSValue] = [ - "number": .number(123.5), - "boolean": .boolean(true), - "string": .string("hello"), - "null": .null, - ] - let result = try jsRoundTripDictionaryJSValue(input) - XCTAssertEqual(result, input) - } - - func testRoundTripNestedDictionary() throws { - let input: [String: [Double]] = [ - "xs": [1.0, 2.5], - "ys": [], - ] - let result = try jsRoundTripNestedDictionary(input) - XCTAssertEqual(result, input) - } - - func testRoundTripOptionalDictionaryNull() throws { - let some: [String: String]? = ["k": "v"] - XCTAssertEqual(try jsRoundTripOptionalDictionary(some), some) - XCTAssertNil(try jsRoundTripOptionalDictionary(nil)) - } - - func testRoundTripOptionalDictionaryUndefined() throws { - let some: JSUndefinedOr<[String: Int]> = .value(["n": 42]) - let undefined: JSUndefinedOr<[String: Int]> = .undefined - - let returnedSome = try jsRoundTripUndefinedDictionary(some) - switch returnedSome { - case .value(let dict): - XCTAssertEqual(dict, ["n": 42]) - case .undefined: - XCTFail("Expected defined dictionary") - } - - let returnedUndefined = try jsRoundTripUndefinedDictionary(undefined) - switch returnedUndefined { - case .value: - XCTFail("Expected undefined") - case .undefined: - break - } - } -} - -@JSFunction func jsRoundTripDictionary(_ values: [String: Int]) throws(JSException) -> [String: Int] - -@JSFunction func jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] - -@JSFunction func jsRoundTripDictionaryDouble(_ values: [String: Double]) throws(JSException) -> [String: Double] - -@JSFunction func jsRoundTripDictionaryJSObject(_ values: [String: JSObject]) throws(JSException) -> [String: JSObject] - -@JSFunction func jsRoundTripDictionaryJSValue(_ values: [String: JSValue]) throws(JSException) -> [String: JSValue] - -@JSFunction func jsRoundTripNestedDictionary(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] - -@JSFunction func jsRoundTripOptionalDictionary(_ values: [String: String]?) throws(JSException) -> [String: String]? - -@JSFunction func jsRoundTripUndefinedDictionary( - _ values: JSUndefinedOr<[String: Int]> -) throws(JSException) -> JSUndefinedOr<[String: Int]> diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e8a0b9476..7e63f8b98 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -10013,171 +10013,129 @@ func _$DefaultArgumentImports_runJsDefaultArgumentTests() throws(JSException) -> } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionary") -fileprivate func bjs_jsRoundTripDictionary_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripDictionary_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripDictionary() -> Void { - return bjs_jsRoundTripDictionary_extern() -} - -func _$jsRoundTripDictionary(_ values: [String: Int]) throws(JSException) -> [String: Int] { - let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripDictionary() - if let error = _swift_js_take_exception() { - throw error - } - return [String: Int].bridgeJSLiftReturn() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryBool") -fileprivate func bjs_jsRoundTripDictionaryBool_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripDictionaryBool_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripDictionaryBool() -> Void { - return bjs_jsRoundTripDictionaryBool_extern() -} - -func _$jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] { - let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripDictionaryBool() - if let error = _swift_js_take_exception() { - throw error - } - return [String: Bool].bridgeJSLiftReturn() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryDouble") -fileprivate func bjs_jsRoundTripDictionaryDouble_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripDictionaryDouble_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripDictionaryDouble() -> Void { - return bjs_jsRoundTripDictionaryDouble_extern() -} - -func _$jsRoundTripDictionaryDouble(_ values: [String: Double]) throws(JSException) -> [String: Double] { - let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripDictionaryDouble() - if let error = _swift_js_take_exception() { - throw error - } - return [String: Double].bridgeJSLiftReturn() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryJSObject") -fileprivate func bjs_jsRoundTripDictionaryJSObject_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripDictionaryJSObject_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripDictionaryJSObject() -> Void { - return bjs_jsRoundTripDictionaryJSObject_extern() -} - -func _$jsRoundTripDictionaryJSObject(_ values: [String: JSObject]) throws(JSException) -> [String: JSObject] { - let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripDictionaryJSObject() - if let error = _swift_js_take_exception() { - throw error - } - return [String: JSObject].bridgeJSLiftReturn() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryJSValue") -fileprivate func bjs_jsRoundTripDictionaryJSValue_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripDictionaryJSValue_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripDictionaryJSValue() -> Void { - return bjs_jsRoundTripDictionaryJSValue_extern() -} - -func _$jsRoundTripDictionaryJSValue(_ values: [String: JSValue]) throws(JSException) -> [String: JSValue] { - let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripDictionaryJSValue() - if let error = _swift_js_take_exception() { - throw error - } - return [String: JSValue].bridgeJSLiftReturn() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripNestedDictionary") -fileprivate func bjs_jsRoundTripNestedDictionary_extern() -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static") +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static_extern() -> Void #else -fileprivate func bjs_jsRoundTripNestedDictionary_extern() -> Void { +fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripNestedDictionary() -> Void { - return bjs_jsRoundTripNestedDictionary_extern() +@inline(never) fileprivate func bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static() -> Void { + return bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static_extern() } -func _$jsRoundTripNestedDictionary(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] { +func _$DictionarySupportImports_jsRoundTripDictionaryInt(_ values: [String: Int]) throws(JSException) -> [String: Int] { let _ = values.bridgeJSLowerParameter() - bjs_jsRoundTripNestedDictionary() + bjs_DictionarySupportImports_jsRoundTripDictionaryInt_static() if let error = _swift_js_take_exception() { throw error } - return [String: [Double]].bridgeJSLiftReturn() + return [String: Int].bridgeJSLiftReturn() } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalDictionary") -fileprivate func bjs_jsRoundTripOptionalDictionary_extern(_ values: Int32) -> Void -#else -fileprivate func bjs_jsRoundTripOptionalDictionary_extern(_ values: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_jsRoundTripOptionalDictionary(_ values: Int32) -> Void { - return bjs_jsRoundTripOptionalDictionary_extern(values) +func _$DictionarySupportImports_jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] { + let _ = values.bridgeJSLowerParameter() + bjs_DictionarySupportImports_jsRoundTripDictionaryBool_static() + if let error = _swift_js_take_exception() { + throw error + } + return [String: Bool].bridgeJSLiftReturn() } -func _$jsRoundTripOptionalDictionary(_ values: Optional<[String: String]>) throws(JSException) -> Optional<[String: String]> { - let valuesIsSome = values.bridgeJSLowerParameter() - bjs_jsRoundTripOptionalDictionary(valuesIsSome) +func _$DictionarySupportImports_jsRoundTripDictionaryDouble(_ values: [String: Double]) throws(JSException) -> [String: Double] { + let _ = values.bridgeJSLowerParameter() + bjs_DictionarySupportImports_jsRoundTripDictionaryDouble_static() if let error = _swift_js_take_exception() { throw error } - return Optional<[String: String]>.bridgeJSLiftReturn() + return [String: Double].bridgeJSLiftReturn() } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripUndefinedDictionary") -fileprivate func bjs_jsRoundTripUndefinedDictionary_extern(_ values: Int32) -> Void -#else -fileprivate func bjs_jsRoundTripUndefinedDictionary_extern(_ values: Int32) -> Void { - fatalError("Only available on WebAssembly") +func _$DictionarySupportImports_jsRoundTripDictionaryJSObject(_ values: [String: JSObject]) throws(JSException) -> [String: JSObject] { + let _ = values.bridgeJSLowerParameter() + bjs_DictionarySupportImports_jsRoundTripDictionaryJSObject_static() + if let error = _swift_js_take_exception() { + throw error + } + return [String: JSObject].bridgeJSLiftReturn() } -#endif -@inline(never) fileprivate func bjs_jsRoundTripUndefinedDictionary(_ values: Int32) -> Void { - return bjs_jsRoundTripUndefinedDictionary_extern(values) + +func _$DictionarySupportImports_jsRoundTripDictionaryJSValue(_ values: [String: JSValue]) throws(JSException) -> [String: JSValue] { + let _ = values.bridgeJSLowerParameter() + bjs_DictionarySupportImports_jsRoundTripDictionaryJSValue_static() + if let error = _swift_js_take_exception() { + throw error + } + return [String: JSValue].bridgeJSLiftReturn() } -func _$jsRoundTripUndefinedDictionary(_ values: JSUndefinedOr<[String: Int]>) throws(JSException) -> JSUndefinedOr<[String: Int]> { - let valuesIsSome = values.bridgeJSLowerParameter() - bjs_jsRoundTripUndefinedDictionary(valuesIsSome) +func _$DictionarySupportImports_jsRoundTripDictionaryDoubleArray(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] { + let _ = values.bridgeJSLowerParameter() + bjs_DictionarySupportImports_jsRoundTripDictionaryDoubleArray_static() if let error = _swift_js_take_exception() { throw error } - return JSUndefinedOr<[String: Int]>.bridgeJSLiftReturn() + return [String: [Double]].bridgeJSLiftReturn() } #if arch(wasm32) @@ -11424,6 +11382,18 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_ return bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(v) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern(_ v: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern(_ v: Int32) -> 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) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static") fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(_ v: Int32) -> Void @@ -11436,6 +11406,18 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDic return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(v) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(_ v: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(_ v: Int32) -> 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) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void @@ -11493,6 +11475,15 @@ func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull(_ v: Optional< return Optional<[JSValue]>.bridgeJSLiftReturn() } +func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined(_ v: JSUndefinedOr<[JSValue]>) throws(JSException) -> JSUndefinedOr<[JSValue]> { + let vIsSome = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static(vIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr<[JSValue]>.bridgeJSLiftReturn() +} + func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull(_ v: Optional<[String: String]>) throws(JSException) -> Optional<[String: String]> { let vIsSome = v.bridgeJSLowerParameter() bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static(vIsSome) @@ -11502,6 +11493,15 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull(_ return Optional<[String: String]>.bridgeJSLiftReturn() } +func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined(_ v: JSUndefinedOr<[String: String]>) throws(JSException) -> JSUndefinedOr<[String: String]> { + let vIsSome = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static(vIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr<[String: String]>.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 66027d719..4b0617e3a 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -15706,245 +15706,187 @@ }, { "functions" : [ + + ], + "types" : [ { - "name" : "jsRoundTripDictionary", - "parameters" : [ - { - "name" : "values", - "type" : { - "dictionary" : { - "_0" : { - "int" : { + "getters" : [ - } - } - } - } - } ], - "returnType" : { - "dictionary" : { - "_0" : { - "int" : { + "methods" : [ - } - } - } - } - }, - { - "name" : "jsRoundTripDictionaryBool", - "parameters" : [ + ], + "name" : "DictionarySupportImports", + "setters" : [ + + ], + "staticMethods" : [ { - "name" : "values", - "type" : { - "dictionary" : { - "_0" : { - "bool" : { + "name" : "jsRoundTripDictionaryInt", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "int" : { + } + } } } } - } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "bool" : { - - } - } - } - } - }, - { - "name" : "jsRoundTripDictionaryDouble", - "parameters" : [ - { - "name" : "values", - "type" : { + ], + "returnType" : { "dictionary" : { "_0" : { - "double" : { + "int" : { } } } } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "double" : { + }, + { + "name" : "jsRoundTripDictionaryBool", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "bool" : { + } + } + } + } } - } - } - } - }, - { - "name" : "jsRoundTripDictionaryJSObject", - "parameters" : [ - { - "name" : "values", - "type" : { + ], + "returnType" : { "dictionary" : { "_0" : { - "jsObject" : { + "bool" : { } } } } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "jsObject" : { + }, + { + "name" : "jsRoundTripDictionaryDouble", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "double" : { + } + } + } + } } - } - } - } - }, - { - "name" : "jsRoundTripDictionaryJSValue", - "parameters" : [ - { - "name" : "values", - "type" : { + ], + "returnType" : { "dictionary" : { "_0" : { - "jsValue" : { + "double" : { } } } } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "jsValue" : { - - } - } - } - } - }, - { - "name" : "jsRoundTripNestedDictionary", - "parameters" : [ + }, { - "name" : "values", - "type" : { - "dictionary" : { - "_0" : { - "array" : { + "name" : "jsRoundTripDictionaryJSObject", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { "_0" : { - "double" : { + "jsObject" : { } } } } } - } - } - ], - "returnType" : { - "dictionary" : { - "_0" : { - "array" : { + ], + "returnType" : { + "dictionary" : { "_0" : { - "double" : { + "jsObject" : { } } } } - } - } - }, - { - "name" : "jsRoundTripOptionalDictionary", - "parameters" : [ + }, { - "name" : "values", - "type" : { - "nullable" : { - "_0" : { + "name" : "jsRoundTripDictionaryJSValue", + "parameters" : [ + { + "name" : "values", + "type" : { "dictionary" : { "_0" : { - "string" : { + "jsValue" : { } } } - }, - "_1" : "null" + } } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { + ], + "returnType" : { "dictionary" : { "_0" : { - "string" : { + "jsValue" : { } } } - }, - "_1" : "null" - } - } - }, - { - "name" : "jsRoundTripUndefinedDictionary", - "parameters" : [ + } + }, { - "name" : "values", - "type" : { - "nullable" : { - "_0" : { + "name" : "jsRoundTripDictionaryDoubleArray", + "parameters" : [ + { + "name" : "values", + "type" : { "dictionary" : { "_0" : { - "int" : { + "array" : { + "_0" : { + "double" : { + } + } } } } - }, - "_1" : "undefined" + } } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { + ], + "returnType" : { "dictionary" : { "_0" : { - "int" : { + "array" : { + "_0" : { + "double" : { + } + } } } } - }, - "_1" : "undefined" + } } - } + ] } - ], - "types" : [ - ] }, { @@ -17099,6 +17041,42 @@ } } }, + { + "name" : "jsRoundTripOptionalJSValueArrayUndefined", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "undefined" + } + } + }, { "name" : "jsRoundTripOptionalStringToStringDictionaryNull", "parameters" : [ @@ -17135,6 +17113,42 @@ } } }, + { + "name" : "jsRoundTripOptionalStringToStringDictionaryUndefined", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "undefined" + } + } + }, { "name" : "runJsOptionalSupportTests", "parameters" : [ diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs new file mode 100644 index 000000000..09956341c --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs @@ -0,0 +1,26 @@ + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["DictionarySupportImports"]} + */ +export function getImports(importsContext) { + return { + "jsRoundTripDictionaryInt": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryBool": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryDouble": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryJSObject": (dict) => { + return dict; + }, + "jsRoundTripDictionaryJSValue": (dict) => { + return dict; + }, + "jsRoundTripDictionaryDoubleArray": (dict) => { + return Object.fromEntries(Object.entries(dict).map(([k, v]) => [k, [...v]])); + }, + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index aaa05a70a..f9fa397f6 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -35,9 +35,15 @@ export function getImports(importsContext) { jsRoundTripOptionalJSValueArrayNull: (v) => { return v ?? null; }, + jsRoundTripOptionalJSValueArrayUndefined: (v) => { + return v === undefined ? undefined : v; + }, jsRoundTripOptionalStringToStringDictionaryNull: (v) => { return v ?? null; }, + jsRoundTripOptionalStringToStringDictionaryUndefined: (v) => { + return v === undefined ? undefined : v; + }, 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 520a608ad..7f9708f57 100644 --- a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -13,16 +13,16 @@ import JavaScriptEventLoop @JSFunction static func jsRoundTripOptionalJSValueArrayNull( _ v: Optional<[JSValue]> ) throws(JSException) -> Optional<[JSValue]> - // @JSFunction static func jsRoundTripOptionalJSValueArrayUndefined( - // _ v: JSUndefinedOr<[JSValue]> - // ) throws(JSException) -> JSUndefinedOr<[JSValue]> + @JSFunction static func jsRoundTripOptionalJSValueArrayUndefined( + _ v: JSUndefinedOr<[JSValue]> + ) throws(JSException) -> JSUndefinedOr<[JSValue]> @JSFunction static func jsRoundTripOptionalStringToStringDictionaryNull( _ v: Optional<[String: String]> ) throws(JSException) -> Optional<[String: String]> - // @JSFunction static func jsRoundTripOptionalStringToStringDictionaryUndefined( - // _ v: JSUndefinedOr<[String: String]> - // ) throws(JSException) -> JSUndefinedOr<[String: String]> + @JSFunction static func jsRoundTripOptionalStringToStringDictionaryUndefined( + _ v: JSUndefinedOr<[String: String]> + ) throws(JSException) -> JSUndefinedOr<[String: String]> @JSFunction static func runJsOptionalSupportTests() throws(JSException) } @@ -70,17 +70,20 @@ final class OptionalSupportTests: XCTestCase { try roundTripTest(OptionalSupportImports.jsRoundTripOptionalJSValueArrayNull, [.number(1), .undefined, .null]) } - // func testRoundTripOptionalJSValueArrayUndefined() throws { - // try roundTripTest(OptionalSupportImports.jsRoundTripOptionalJSValueArrayUndefined, [.number(1), .undefined, .null]) - // } + func testRoundTripOptionalJSValueArrayUndefined() throws { + try roundTripTest( + OptionalSupportImports.jsRoundTripOptionalJSValueArrayUndefined, + [.number(1), .undefined, .null] + ) + } func testRoundTripOptionalStringToStringDictionaryNull() throws { try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryNull, ["key": "value"]) } - // func testRoundTripOptionalStringToStringDictionaryUndefined() throws { - // try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryUndefined, ["key": "value"]) - // } + func testRoundTripOptionalStringToStringDictionaryUndefined() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryUndefined, ["key": "value"]) + } } @JS enum OptionalSupportExports { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 3aeb10a8b..e6cc960cd 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -9,6 +9,7 @@ import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/J 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'; +import { getImports as getDictionarySupportImports } from './BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs'; import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs'; import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; @@ -54,30 +55,6 @@ export async function setupOptions(options, context) { "jsRoundTripString": (v) => { return v; }, - "jsRoundTripDictionary": (dict) => { - return { ...dict }; - }, - "jsRoundTripDictionaryBool": (dict) => { - return { ...dict }; - }, - "jsRoundTripDictionaryDouble": (dict) => { - return { ...dict }; - }, - "jsRoundTripDictionaryJSObject": (dict) => { - return dict; - }, - "jsRoundTripDictionaryJSValue": (dict) => { - return dict; - }, - "jsRoundTripNestedDictionary": (dict) => { - return Object.fromEntries(Object.entries(dict).map(([k, v]) => [k, [...v]])); - }, - "jsRoundTripOptionalDictionary": (dict) => { - return dict ?? null; - }, - "jsRoundTripUndefinedDictionary": (dict) => { - return dict; - }, "jsRoundTripJSValue": (v) => { return v; }, @@ -164,6 +141,7 @@ export async function setupOptions(options, context) { SwiftClassSupportImports: getSwiftClassSupportImports(importsContext), OptionalSupportImports: getOptionalSupportImports(importsContext), ArraySupportImports: getArraySupportImports(importsContext), + DictionarySupportImports: getDictionarySupportImports(importsContext), DefaultArgumentImports: getDefaultArgumentImports(importsContext), JSClassSupportImports: getJSClassSupportImports(importsContext), }; From 3eff48a6a97912ea3181fb388ed53a7339f055aa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Mar 2026 09:15:46 +0000 Subject: [PATCH 012/140] Bump rollup from 4.57.1 to 4.59.0 (#686) --- package-lock.json | 212 +++++++++++++++++++++++----------------------- 1 file changed, 104 insertions(+), 108 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9366b618d..5eab62401 100644 --- a/package-lock.json +++ b/package-lock.json @@ -552,9 +552,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", - "integrity": "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", "cpu": [ "arm" ], @@ -566,9 +566,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.1.tgz", - "integrity": "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", "cpu": [ "arm64" ], @@ -580,9 +580,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.1.tgz", - "integrity": "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", "cpu": [ "arm64" ], @@ -594,9 +594,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.1.tgz", - "integrity": "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", "cpu": [ "x64" ], @@ -608,9 +608,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.1.tgz", - "integrity": "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", "cpu": [ "arm64" ], @@ -622,9 +622,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.1.tgz", - "integrity": "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", "cpu": [ "x64" ], @@ -636,9 +636,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.1.tgz", - "integrity": "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", "cpu": [ "arm" ], @@ -650,9 +650,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.1.tgz", - "integrity": "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", "cpu": [ "arm" ], @@ -664,9 +664,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", - "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", "cpu": [ "arm64" ], @@ -678,9 +678,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", - "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", "cpu": [ "arm64" ], @@ -692,9 +692,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.1.tgz", - "integrity": "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", "cpu": [ "loong64" ], @@ -706,9 +706,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.1.tgz", - "integrity": "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", "cpu": [ "loong64" ], @@ -720,9 +720,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.1.tgz", - "integrity": "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", "cpu": [ "ppc64" ], @@ -734,9 +734,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.1.tgz", - "integrity": "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", "cpu": [ "ppc64" ], @@ -748,9 +748,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.1.tgz", - "integrity": "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", "cpu": [ "riscv64" ], @@ -762,9 +762,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.1.tgz", - "integrity": "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", "cpu": [ "riscv64" ], @@ -776,9 +776,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.1.tgz", - "integrity": "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", "cpu": [ "s390x" ], @@ -790,9 +790,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz", - "integrity": "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", "cpu": [ "x64" ], @@ -804,9 +804,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz", - "integrity": "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", "cpu": [ "x64" ], @@ -818,9 +818,9 @@ ] }, "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.1.tgz", - "integrity": "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", "cpu": [ "x64" ], @@ -832,9 +832,9 @@ ] }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.1.tgz", - "integrity": "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", "cpu": [ "arm64" ], @@ -846,9 +846,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.1.tgz", - "integrity": "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", "cpu": [ "arm64" ], @@ -860,9 +860,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.1.tgz", - "integrity": "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", "cpu": [ "ia32" ], @@ -874,9 +874,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.1.tgz", - "integrity": "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", "cpu": [ "x64" ], @@ -888,9 +888,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.1.tgz", - "integrity": "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", "cpu": [ "x64" ], @@ -938,7 +938,6 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.14.tgz", "integrity": "sha512-Zs/Ollc1SJ8nKUAgc7ivOEdIBM8JAKgrqqUYi2J997JuKO7/tpQC+WCetQ1sypiKCQWHdvdg9wBNpUPEWZae7w==", "dev": true, - "peer": true, "dependencies": { "undici-types": "~6.20.0" } @@ -1401,12 +1400,11 @@ } }, "node_modules/rollup": { - "version": "4.57.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", - "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "1.0.8" }, @@ -1418,31 +1416,31 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.57.1", - "@rollup/rollup-android-arm64": "4.57.1", - "@rollup/rollup-darwin-arm64": "4.57.1", - "@rollup/rollup-darwin-x64": "4.57.1", - "@rollup/rollup-freebsd-arm64": "4.57.1", - "@rollup/rollup-freebsd-x64": "4.57.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", - "@rollup/rollup-linux-arm-musleabihf": "4.57.1", - "@rollup/rollup-linux-arm64-gnu": "4.57.1", - "@rollup/rollup-linux-arm64-musl": "4.57.1", - "@rollup/rollup-linux-loong64-gnu": "4.57.1", - "@rollup/rollup-linux-loong64-musl": "4.57.1", - "@rollup/rollup-linux-ppc64-gnu": "4.57.1", - "@rollup/rollup-linux-ppc64-musl": "4.57.1", - "@rollup/rollup-linux-riscv64-gnu": "4.57.1", - "@rollup/rollup-linux-riscv64-musl": "4.57.1", - "@rollup/rollup-linux-s390x-gnu": "4.57.1", - "@rollup/rollup-linux-x64-gnu": "4.57.1", - "@rollup/rollup-linux-x64-musl": "4.57.1", - "@rollup/rollup-openbsd-x64": "4.57.1", - "@rollup/rollup-openharmony-arm64": "4.57.1", - "@rollup/rollup-win32-arm64-msvc": "4.57.1", - "@rollup/rollup-win32-ia32-msvc": "4.57.1", - "@rollup/rollup-win32-x64-gnu": "4.57.1", - "@rollup/rollup-win32-x64-msvc": "4.57.1", + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", "fsevents": "~2.3.2" } }, @@ -1561,8 +1559,7 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD", - "peer": true + "license": "0BSD" }, "node_modules/typescript": { "version": "5.8.2", @@ -1570,7 +1567,6 @@ "integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From 5529520b25638aa86765ab33b175289f1ab263a3 Mon Sep 17 00:00:00 2001 From: Adin Date: Tue, 3 Mar 2026 15:37:28 +0700 Subject: [PATCH 013/140] Merge pull request #687 from gn-adin-b/adin/property-access-tracing Add property access tracing to JSTracing --- .../FundamentalObjects/JSObject.swift | 38 ++++++++++++ Sources/JavaScriptKit/JSTracing.swift | 2 + Tests/JavaScriptKitTests/JSTracingTests.swift | 60 ++++++++++++++++++- 3 files changed, 97 insertions(+), 3 deletions(-) diff --git a/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift b/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift index caacd49f2..1b6facada 100644 --- a/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift +++ b/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift @@ -153,10 +153,18 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { public subscript(_ name: String) -> JSValue { get { assertOnOwnerThread(hint: "reading '\(name)' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall(.propertyGet(receiver: self, propertyName: name)) + defer { traceEnd?() } + #endif return getJSValue(this: self, name: JSString(name)) } set { assertOnOwnerThread(hint: "writing '\(name)' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall(.propertySet(receiver: self, propertyName: name, value: newValue)) + defer { traceEnd?() } + #endif setJSValue(this: self, name: JSString(name), value: newValue) } } @@ -167,10 +175,20 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { public subscript(_ name: JSString) -> JSValue { get { assertOnOwnerThread(hint: "reading '<>' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall(.propertyGet(receiver: self, propertyName: String(name))) + defer { traceEnd?() } + #endif return getJSValue(this: self, name: name) } set { assertOnOwnerThread(hint: "writing '<>' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall( + .propertySet(receiver: self, propertyName: String(name), value: newValue) + ) + defer { traceEnd?() } + #endif setJSValue(this: self, name: name, value: newValue) } } @@ -181,10 +199,20 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { public subscript(_ index: Int) -> JSValue { get { assertOnOwnerThread(hint: "reading '\(index)' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall(.propertyGet(receiver: self, propertyName: String(index))) + defer { traceEnd?() } + #endif return getJSValue(this: self, index: Int32(index)) } set { assertOnOwnerThread(hint: "writing '\(index)' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall( + .propertySet(receiver: self, propertyName: String(index), value: newValue) + ) + defer { traceEnd?() } + #endif setJSValue(this: self, index: Int32(index), value: newValue) } } @@ -195,10 +223,20 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { public subscript(_ name: JSSymbol) -> JSValue { get { assertOnOwnerThread(hint: "reading '<>' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall(.propertyGet(receiver: self, propertyName: "<>")) + defer { traceEnd?() } + #endif return getJSValue(this: self, symbol: name) } set { assertOnOwnerThread(hint: "writing '<>' property") + #if Tracing + let traceEnd = JSTracingHooks.beginJSCall( + .propertySet(receiver: self, propertyName: "<>", value: newValue) + ) + defer { traceEnd?() } + #endif setJSValue(this: self, symbol: name, value: newValue) } } diff --git a/Sources/JavaScriptKit/JSTracing.swift b/Sources/JavaScriptKit/JSTracing.swift index 8804e9afb..28e2a1bf8 100644 --- a/Sources/JavaScriptKit/JSTracing.swift +++ b/Sources/JavaScriptKit/JSTracing.swift @@ -7,6 +7,8 @@ public struct JSTracing: Sendable { public enum JSCallInfo { case function(function: JSObject, arguments: [JSValue]) case method(receiver: JSObject, methodName: String?, arguments: [JSValue]) + case propertyGet(receiver: JSObject, propertyName: String) + case propertySet(receiver: JSObject, propertyName: String, value: JSValue) } /// Register a hook for Swift to JavaScript calls. diff --git a/Tests/JavaScriptKitTests/JSTracingTests.swift b/Tests/JavaScriptKitTests/JSTracingTests.swift index 84fb9bfc6..755e89d49 100644 --- a/Tests/JavaScriptKitTests/JSTracingTests.swift +++ b/Tests/JavaScriptKitTests/JSTracingTests.swift @@ -16,15 +16,69 @@ final class JSTracingTests: XCTestCase { let prop5 = try XCTUnwrap(globalObject1.prop_5.object) _ = prop5.func6!(true, 1, 2) - XCTAssertEqual(startInfo.count, 1) - guard case let .method(receiver, methodName, arguments) = startInfo.first else { + let methodEvents = startInfo.filter { + if case .method = $0 { return true } + return false + } + XCTAssertEqual(methodEvents.count, 1) + guard case let .method(receiver, methodName, arguments) = methodEvents.first else { XCTFail("Expected method info") return } XCTAssertEqual(receiver.id, prop5.id) XCTAssertEqual(methodName, "func6") XCTAssertEqual(arguments, [.boolean(true), .number(1), .number(2)]) - XCTAssertEqual(ended, 1) + XCTAssertEqual(ended, startInfo.count) + } + + func testJSCallHookReportsPropertyAccess() throws { + var startInfo: [JSTracing.JSCallInfo] = [] + var ended = 0 + let remove = JSTracing.default.addJSCallHook { info in + startInfo.append(info) + return { ended += 1 } + } + defer { remove() } + + let obj = JSObject() + obj.foo = .number(42) + + // Reset after setup so we only capture the reads/writes below. + startInfo.removeAll() + ended = 0 + + // Read a property (triggers propertyGet) + let _: JSValue = obj.foo + + // Write a property (triggers propertySet) + obj.foo = .number(999) + + let propEvents = startInfo.filter { + switch $0 { + case .propertyGet(_, let name) where name == "foo": return true + case .propertySet(_, let name, _) where name == "foo": return true + default: return false + } + } + + XCTAssertEqual(propEvents.count, 2) + + guard case .propertyGet(let getReceiver, let getName) = propEvents[0] else { + XCTFail("Expected propertyGet info") + return + } + XCTAssertEqual(getReceiver.id, obj.id) + XCTAssertEqual(getName, "foo") + + guard case .propertySet(let setReceiver, let setName, let setValue) = propEvents[1] else { + XCTFail("Expected propertySet info") + return + } + XCTAssertEqual(setReceiver.id, obj.id) + XCTAssertEqual(setName, "foo") + XCTAssertEqual(setValue, .number(999)) + + XCTAssertEqual(ended, startInfo.count) } func testJSClosureCallHookReportsMetadata() throws { From 0c4c45a78184c96a685896270aec49e91fb7abfc Mon Sep 17 00:00:00 2001 From: Stephan Diederich Date: Wed, 4 Mar 2026 13:34:30 +0100 Subject: [PATCH 014/140] fix use-after-free in BridgeJS (#690) fix use-after-free --- Sources/JavaScriptKit/BridgeJSIntrinsics.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 87f83d8a9..c0de9413e 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -420,7 +420,12 @@ extension JSObject: _BridgedSwiftStackType { } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { - return _swift_js_retain(Int32(bitPattern: self.id)) + // withExtendedLifetime is required here to prevent a use-after-free. + // In a `consuming func`, Swift ARC may release `self` (and thus release + // the underlying JS reference) as soon as it extracts `self.id`, which + // happens *before* `_swift_js_retain` is called. `withExtendedLifetime` forces + // `self` to stay alive until after `_swift_js_retain` returns. + return withExtendedLifetime(self) { _swift_js_retain(Int32(bitPattern: self.id)) } } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { From bc05d2a82db665c2c4c1f0cafc8f07f04dcf0237 Mon Sep 17 00:00:00 2001 From: Stephan Diederich Date: Wed, 4 Mar 2026 14:12:13 +0100 Subject: [PATCH 015/140] BridgeJS: fix codegen for async + throws exported methods (#691) --- .../BridgeJS/Sources/BridgeJSCore/ExportSwift.swift | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 7311b24be..4c91ebd74 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -319,8 +319,19 @@ public class ExportSwift { 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 = "" + } body = """ - let ret = JSPromise.async { + let ret = JSPromise.async {\(raw: closureHead) \(CodeBlockItemListSyntax(self.body)) }.jsObject return ret.bridgeJSLowerReturn() From 3d25cd9faef03aa0e8c57d38cdab771d8d720a1c Mon Sep 17 00:00:00 2001 From: Simon Leeb <52261246+sliemeobn@users.noreply.github.com> Date: Thu, 5 Mar 2026 12:08:40 +0100 Subject: [PATCH 016/140] [BridgeJS] Pass String parameters unretained as (address, length) (#688) * pass unretained strings as tuple * Generalize lowering parameters with borrowing scope * factored out decodeString global * formatting * format (with Swift 6.2) --------- Co-authored-by: Yuta Saito --- Benchmarks/Sources/Generated/BridgeJS.swift | 15 +- .../PlayBridgeJS/Generated/BridgeJS.swift | 15 +- .../Sources/BridgeJSCore/ClosureCodegen.swift | 7 +- .../Sources/BridgeJSCore/ExportSwift.swift | 19 +- .../Sources/BridgeJSCore/ImportTS.swift | 162 +++++--- .../Sources/BridgeJSLink/BridgeJSLink.swift | 29 +- .../Sources/BridgeJSLink/JSGlueGen.swift | 15 +- .../BridgeJSCodegenTests/EnumRawType.swift | 13 +- .../BridgeJSCodegenTests/GlobalGetter.swift | 13 +- .../GlobalThisImports.swift | 43 ++- .../InvalidPropertyNames.swift | 65 ++-- .../BridgeJSCodegenTests/JSClass.swift | 41 +- .../BridgeJSCodegenTests/Optionals.swift | 71 ++-- .../BridgeJSCodegenTests/Protocol.swift | 68 ++-- .../StringParameter.swift | 28 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 56 +-- .../BridgeJSLinkTests/ArrayTypes.js | 15 +- .../__Snapshots__/BridgeJSLinkTests/Async.js | 15 +- .../BridgeJSLinkTests/DefaultParameters.js | 15 +- .../BridgeJSLinkTests/DictionaryTypes.js | 15 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 15 +- .../BridgeJSLinkTests/EnumCase.js | 15 +- .../BridgeJSLinkTests/EnumNamespace.Global.js | 15 +- .../BridgeJSLinkTests/EnumNamespace.js | 15 +- .../BridgeJSLinkTests/EnumRawType.js | 22 +- .../BridgeJSLinkTests/GlobalGetter.js | 22 +- .../BridgeJSLinkTests/GlobalThisImports.js | 36 +- .../BridgeJSLinkTests/ImportArray.js | 15 +- .../ImportedTypeInExportedInterface.js | 15 +- .../BridgeJSLinkTests/InvalidPropertyNames.js | 50 ++- .../BridgeJSLinkTests/JSClass.js | 36 +- .../JSClassStaticFunctions.js | 15 +- .../BridgeJSLinkTests/JSValue.js | 15 +- .../BridgeJSLinkTests/MixedGlobal.js | 15 +- .../BridgeJSLinkTests/MixedModules.js | 15 +- .../BridgeJSLinkTests/MixedPrivate.js | 15 +- .../BridgeJSLinkTests/Namespaces.Global.js | 15 +- .../BridgeJSLinkTests/Namespaces.js | 15 +- .../BridgeJSLinkTests/Optionals.js | 55 ++- .../BridgeJSLinkTests/PrimitiveParameters.js | 15 +- .../BridgeJSLinkTests/PrimitiveReturn.js | 15 +- .../BridgeJSLinkTests/PropertyTypes.js | 15 +- .../BridgeJSLinkTests/Protocol.js | 53 ++- .../StaticFunctions.Global.js | 15 +- .../BridgeJSLinkTests/StaticFunctions.js | 15 +- .../StaticProperties.Global.js | 15 +- .../BridgeJSLinkTests/StaticProperties.js | 15 +- .../BridgeJSLinkTests/StringParameter.js | 29 +- .../BridgeJSLinkTests/StringReturn.js | 15 +- .../BridgeJSLinkTests/SwiftClass.js | 15 +- .../BridgeJSLinkTests/SwiftClosure.js | 43 +-- .../BridgeJSLinkTests/SwiftClosureImports.js | 15 +- .../BridgeJSLinkTests/SwiftStruct.js | 15 +- .../BridgeJSLinkTests/SwiftStructImports.js | 15 +- .../__Snapshots__/BridgeJSLinkTests/Throws.js | 15 +- .../BridgeJSLinkTests/UnsafePointer.js | 15 +- .../VoidParameterVoidReturn.js | 15 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 35 +- .../Generated/BridgeJS.swift | 359 ++++++++++-------- 59 files changed, 1000 insertions(+), 880 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index bf033ae21..7b7c6e690 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -1750,20 +1750,21 @@ func _$benchmarkHelperNoopWithNumber(_ n: Double) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkRunner") -fileprivate func bjs_benchmarkRunner_extern(_ name: Int32, _ body: Int32) -> Void +fileprivate func bjs_benchmarkRunner_extern(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void #else -fileprivate func bjs_benchmarkRunner_extern(_ name: Int32, _ body: Int32) -> Void { +fileprivate func bjs_benchmarkRunner_extern(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_benchmarkRunner(_ name: Int32, _ body: Int32) -> Void { - return bjs_benchmarkRunner_extern(name, body) +@inline(never) fileprivate func bjs_benchmarkRunner(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void { + return bjs_benchmarkRunner_extern(nameBytes, nameLength, body) } func _$benchmarkRunner(_ name: String, _ body: JSObject) throws(JSException) -> Void { - let nameValue = name.bridgeJSLowerParameter() - let bodyValue = body.bridgeJSLowerParameter() - bjs_benchmarkRunner(nameValue, bodyValue) + name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let bodyValue = body.bridgeJSLowerParameter() + bjs_benchmarkRunner(nameBytes, nameLength, bodyValue) + } if let error = _swift_js_take_exception() { throw error } diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 88cdf900e..f1baf3aa1 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -249,20 +249,23 @@ func _$createTS2Swift() throws(JSException) -> TS2Swift { #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_TS2Swift_convert") -fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ ts: Int32) -> Int32 +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 #else -fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ ts: Int32) -> Int32 { +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ ts: Int32) -> Int32 { - return bjs_TS2Swift_convert_extern(self, ts) +@inline(never) fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 { + return bjs_TS2Swift_convert_extern(self, tsBytes, tsLength) } func _$TS2Swift_convert(_ self: JSObject, _ ts: String) throws(JSException) -> String { let selfValue = self.bridgeJSLowerParameter() - let tsValue = ts.bridgeJSLowerParameter() - let ret = bjs_TS2Swift_convert(selfValue, tsValue) + let ret0 = ts.bridgeJSWithLoweredParameter { (tsBytes, tsLength) in + let ret = bjs_TS2Swift_convert(selfValue, tsBytes, tsLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index d974fc16d..e5648ccf7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -26,9 +26,10 @@ public struct ClosureCodegen { let externName = "invoke_js_callback_\(signature.moduleName)_\(mangledName)" // Use CallJSEmission to generate the callback invocation - let builder = ImportTS.CallJSEmission( + let builder = try ImportTS.CallJSEmission( moduleName: "bjs", abiName: externName, + returnType: signature.returnType, context: .exportSwift ) @@ -41,8 +42,8 @@ public struct ClosureCodegen { } // Generate the call and return value lifting - try builder.call(returnType: signature.returnType) - try builder.liftReturnValue(returnType: signature.returnType) + try builder.call() + try builder.liftReturnValue() // Generate extern declaration using CallJSEmission let externDecl = builder.renderImportDecl() diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 4c91ebd74..dbe4a1312 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -1177,17 +1177,18 @@ struct ProtocolCodegen { var externDecls: [DeclSyntax] = [] for method in proto.methods { - let builder = ImportTS.CallJSEmission( + let builder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: "_extern_\(method.name)", + returnType: method.returnType, context: .exportSwift ) try builder.lowerParameter(param: Parameter(label: nil, name: "jsObject", type: .jsObject(nil))) for param in method.parameters { try builder.lowerParameter(param: param) } - try builder.call(returnType: method.returnType) - try builder.liftReturnValue(returnType: method.returnType) + try builder.call() + try builder.liftReturnValue() // Build function signature using SwiftSignatureBuilder let signature = SwiftSignatureBuilder.buildFunctionSignature( @@ -1275,14 +1276,15 @@ struct ProtocolCodegen { className: protocolName ) - let getterBuilder = ImportTS.CallJSEmission( + let getterBuilder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: getterAbiName, + returnType: property.type, context: .exportSwift ) try getterBuilder.lowerParameter(param: Parameter(label: nil, name: "jsObject", type: .jsObject(nil))) - try getterBuilder.call(returnType: property.type) - try getterBuilder.liftReturnValue(returnType: property.type) + try getterBuilder.call() + try getterBuilder.liftReturnValue() // Build getter extern declaration using helper function let getterExternDeclPrinter = CodeFragmentPrinter() @@ -1307,14 +1309,15 @@ struct ProtocolCodegen { if property.isReadonly { return } - let setterBuilder = ImportTS.CallJSEmission( + let setterBuilder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: setterAbiName, + returnType: .void, context: .exportSwift ) try setterBuilder.lowerParameter(param: Parameter(label: nil, name: "jsObject", type: .jsObject(nil))) try setterBuilder.lowerParameter(param: Parameter(label: nil, name: "newValue", type: property.type)) - try setterBuilder.call(returnType: .void) + try setterBuilder.call() // Build setter extern declaration using helper function let setterExternDeclPrinter = CodeFragmentPrinter() diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 8f5ac511a..1b7dce434 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -66,9 +66,13 @@ public struct ImportTS { _ getter: ImportedGetterSkeleton, topLevelDecls: inout [DeclSyntax] ) throws -> [DeclSyntax] { - let builder = CallJSEmission(moduleName: moduleName, abiName: getter.abiName(context: nil)) - try builder.call(returnType: getter.type) - try builder.liftReturnValue(returnType: getter.type) + let builder = try CallJSEmission( + moduleName: moduleName, + abiName: getter.abiName(context: nil), + returnType: getter.type + ) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return [ builder.renderThunkDecl( @@ -81,8 +85,16 @@ public struct ImportTS { } class CallJSEmission { + private struct BorrowedArgument { + /// The variable name of the `bridgeJSWithLoweredParameter` return value + let returnVariableName: String? + /// The closure to close the borrowing call + let closeBorrowedClosure: (CodeFragmentPrinter) -> Void + } + let abiName: String let moduleName: String + let returnType: BridgeType let context: BridgeContext var body = CodeFragmentPrinter() @@ -95,11 +107,19 @@ public struct ImportTS { var stackLoweringStmts: [String] = [] // Values to extend lifetime during call var valuesToExtendLifetimeDuringCall: [String] = [] + // Closures to close borrowed parameters + private var borrowedArguments: [BorrowedArgument] = [] + private let needsReturnVariable: Bool - init(moduleName: String, abiName: String, context: BridgeContext = .importTS) { + init(moduleName: String, abiName: String, returnType: BridgeType, context: BridgeContext = .importTS) throws { self.moduleName = moduleName self.abiName = abiName + self.returnType = returnType self.context = context + let liftingInfo = try returnType.liftingReturnInfo(context: context) + needsReturnVariable = + !(returnType == .void || returnType.usesSideChannelForOptionalReturn() + || liftingInfo.valueToLift == nil) } func lowerParameter(param: Parameter) throws { @@ -115,12 +135,6 @@ public struct ImportTS { default: break } - let initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") - - if loweringInfo.loweredParameters.isEmpty { - stackLoweringStmts.insert("let _ = \(initializerExpr)", at: 0) - return - } // Generate destructured variable names for all lowered parameters let destructuredNames = loweringInfo.loweredParameters.map { @@ -135,7 +149,30 @@ public struct ImportTS { pattern = "(" + destructuredNames.joined(separator: ", ") + ")" } - body.write("let \(pattern) = \(initializerExpr)") + if loweringInfo.useBorrowing { + let returnVariableName = "ret\(borrowedArguments.count)" + let assign = needsReturnVariable ? "let \(returnVariableName) = " : "" + body.write("\(assign)\(param.name).bridgeJSWithLoweredParameter { \(pattern) in") + body.indent() + borrowedArguments.append( + BorrowedArgument( + returnVariableName: needsReturnVariable ? returnVariableName : nil, + closeBorrowedClosure: { printer in + printer.unindent() + printer.write("}") + } + ) + ) + } else { + let initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + + if loweringInfo.loweredParameters.isEmpty { + stackLoweringStmts.insert("let _ = \(initializerExpr)", at: 0) + return + } + + body.write("let \(pattern) = \(initializerExpr)") + } destructuredVarNames.append(contentsOf: destructuredNames) // Add to signatures and forwardings (unified for both single and multiple) @@ -155,27 +192,35 @@ public struct ImportTS { } } - func call(returnType: BridgeType) throws { - let liftingInfo: BridgeType.LiftingReturnInfo = try returnType.liftingReturnInfo(context: context) + func call() throws { for stmt in stackLoweringStmts { body.write(stmt.description) } - let assign = - (returnType == .void || returnType.usesSideChannelForOptionalReturn() || liftingInfo.valueToLift == nil) - ? "" : "let ret = " - let callExpr = "\(abiName)(\(abiParameterForwardings.joined(separator: ", ")))" + let assign = needsReturnVariable ? "let ret = " : "" + var callExpr = "\(abiName)(\(abiParameterForwardings.joined(separator: ", ")))" if !valuesToExtendLifetimeDuringCall.isEmpty { - body.write( - "\(assign)withExtendedLifetime((\(valuesToExtendLifetimeDuringCall.joined(separator: ", ")))) {" - ) - body.indent { - body.write(callExpr) + callExpr = + "withExtendedLifetime((\(valuesToExtendLifetimeDuringCall.joined(separator: ", ")))) { \(callExpr) }" + } + + body.write("\(assign)\(callExpr)") + + if let firstBorrowedArgument = borrowedArguments.first { + if needsReturnVariable { + body.write("return ret") + } + for borrowedArgument in borrowedArguments.dropFirst().reversed() { + borrowedArgument.closeBorrowedClosure(body) + if let returnVariableName = borrowedArgument.returnVariableName { + body.write("return \(returnVariableName)") + } + } + firstBorrowedArgument.closeBorrowedClosure(body) + if let returnVariableName = firstBorrowedArgument.returnVariableName { + body.write("let ret = \(returnVariableName)") } - body.write("}") - } else { - body.write("\(assign)\(callExpr)") } // Add exception check for ImportTS context @@ -184,7 +229,7 @@ public struct ImportTS { } } - func liftReturnValue(returnType: BridgeType) throws { + func liftReturnValue() throws { let liftingInfo = try returnType.liftingReturnInfo(context: context) if returnType == .void { @@ -294,12 +339,16 @@ public struct ImportTS { _ function: ImportedFunctionSkeleton, topLevelDecls: inout [DeclSyntax] ) throws -> [DeclSyntax] { - let builder = CallJSEmission(moduleName: moduleName, abiName: function.abiName(context: nil)) + let builder = try CallJSEmission( + moduleName: moduleName, + abiName: function.abiName(context: nil), + returnType: function.returnType + ) for param in function.parameters { try builder.lowerParameter(param: param) } - try builder.call(returnType: function.returnType) - try builder.liftReturnValue(returnType: function.returnType) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return [ builder.renderThunkDecl( @@ -316,13 +365,17 @@ public struct ImportTS { var decls: [DeclSyntax] = [] func renderMethod(method: ImportedFunctionSkeleton) throws -> [DeclSyntax] { - let builder = CallJSEmission(moduleName: moduleName, abiName: method.abiName(context: type)) + let builder = try CallJSEmission( + moduleName: moduleName, + abiName: method.abiName(context: type), + returnType: method.returnType + ) try builder.lowerParameter(param: selfParameter) for param in method.parameters { try builder.lowerParameter(param: param) } - try builder.call(returnType: method.returnType) - try builder.liftReturnValue(returnType: method.returnType) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return [ builder.renderThunkDecl( @@ -335,12 +388,12 @@ public struct ImportTS { func renderStaticMethod(method: ImportedFunctionSkeleton) throws -> [DeclSyntax] { let abiName = method.abiName(context: type, operation: "static") - let builder = CallJSEmission(moduleName: moduleName, abiName: abiName) + let builder = try CallJSEmission(moduleName: moduleName, abiName: abiName, returnType: method.returnType) for param in method.parameters { try builder.lowerParameter(param: param) } - try builder.call(returnType: method.returnType) - try builder.liftReturnValue(returnType: method.returnType) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return [ builder.renderThunkDecl( @@ -352,12 +405,16 @@ public struct ImportTS { } func renderConstructorDecl(constructor: ImportedConstructorSkeleton) throws -> [DeclSyntax] { - let builder = CallJSEmission(moduleName: moduleName, abiName: constructor.abiName(context: type)) + let builder = try CallJSEmission( + moduleName: moduleName, + abiName: constructor.abiName(context: type), + returnType: .jsObject(nil) + ) for param in constructor.parameters { try builder.lowerParameter(param: param) } - try builder.call(returnType: .jsObject(nil)) - try builder.liftReturnValue(returnType: .jsObject(nil)) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return [ builder.renderThunkDecl( @@ -369,13 +426,14 @@ public struct ImportTS { } func renderGetterDecl(getter: ImportedGetterSkeleton) throws -> DeclSyntax { - let builder = CallJSEmission( + let builder = try CallJSEmission( moduleName: moduleName, - abiName: getter.abiName(context: type) + abiName: getter.abiName(context: type), + returnType: getter.type ) try builder.lowerParameter(param: selfParameter) - try builder.call(returnType: getter.type) - try builder.liftReturnValue(returnType: getter.type) + try builder.call() + try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) return DeclSyntax( builder.renderThunkDecl( @@ -387,14 +445,15 @@ public struct ImportTS { } func renderSetterDecl(setter: ImportedSetterSkeleton) throws -> DeclSyntax { - let builder = CallJSEmission( + let builder = try CallJSEmission( moduleName: moduleName, - abiName: setter.abiName(context: type) + abiName: setter.abiName(context: type), + returnType: .void ) let newValue = Parameter(label: nil, name: "newValue", type: setter.type) try builder.lowerParameter(param: selfParameter) try builder.lowerParameter(param: newValue) - try builder.call(returnType: .void) + try builder.call() topLevelDecls.append(builder.renderImportDecl()) // Use functionName if available (has lowercase first char), otherwise derive from name let propertyNameForThunk: String @@ -719,12 +778,18 @@ enum SwiftCodePattern { extension BridgeType { struct LoweringParameterInfo { let loweredParameters: [(name: String, type: WasmCoreType)] + /// If true, the parameter should be lowered by using `bridgeJSWithLoweredParameter` + /// that takes a closure to handle the borrowed parameter. + var useBorrowing: Bool = false static let bool = LoweringParameterInfo(loweredParameters: [("value", .i32)]) static let int = LoweringParameterInfo(loweredParameters: [("value", .i32)]) static let float = LoweringParameterInfo(loweredParameters: [("value", .f32)]) static let double = LoweringParameterInfo(loweredParameters: [("value", .f64)]) - static let string = LoweringParameterInfo(loweredParameters: [("value", .i32)]) + static let string = LoweringParameterInfo( + loweredParameters: [("bytes", .i32), ("length", .i32)], + useBorrowing: true + ) static let jsObject = LoweringParameterInfo(loweredParameters: [("value", .i32)]) static let jsValue = LoweringParameterInfo(loweredParameters: [ ("kind", .i32), @@ -761,6 +826,9 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: [("value", .i32)]) } case .rawValueEnum(_, let rawType): + if rawType == .string { + return .string + } let wasmType = rawType.wasmCoreType ?? .i32 return LoweringParameterInfo(loweredParameters: [("value", wasmType)]) case .associatedValueEnum: @@ -784,7 +852,7 @@ extension BridgeType { let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) var params = [("isSome", WasmCoreType.i32)] params.append(contentsOf: wrappedInfo.loweredParameters) - return LoweringParameterInfo(loweredParameters: params) + return LoweringParameterInfo(loweredParameters: params, useBorrowing: wrappedInfo.useBorrowing) case .array, .dictionary: return LoweringParameterInfo(loweredParameters: []) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index af2456f81..68232b673 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -289,6 +289,7 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedInstance);", "let \(JSGlueVariableScope.reservedMemory);", "let \(JSGlueVariableScope.reservedSetException);", + "let \(JSGlueVariableScope.reservedDecodeString);", "const \(JSGlueVariableScope.reservedTextDecoder) = new TextDecoder(\"utf-8\");", "const \(JSGlueVariableScope.reservedTextEncoder) = new TextEncoder(\"utf-8\");", "let \(JSGlueVariableScope.reservedStorageToReturnString);", @@ -337,10 +338,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_return_string\"] = function(ptr, len) {") printer.indent { printer.write( - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len)\(sharedMemory ? ".slice()" : "");" - ) - printer.write( - "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes);" + "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);" ) } printer.write("}") @@ -361,10 +359,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_make_js_string\"] = function(ptr, len) {") printer.indent { printer.write( - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len)\(sharedMemory ? ".slice()" : "");" - ) - printer.write( - "return \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).retain(\(JSGlueVariableScope.reservedTextDecoder).decode(bytes));" + "return \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).retain(\(JSGlueVariableScope.reservedDecodeString)(ptr, len));" ) } printer.write("}") @@ -413,10 +408,7 @@ public struct BridgeJSLink { printer.write("}") printer.write("bjs[\"swift_js_push_string\"] = function(ptr, len) {") printer.indent { - printer.write( - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len)\(sharedMemory ? ".slice()" : "");" - ) - printer.write("const value = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes);") + printer.write("const value = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);") printer.write("\(JSGlueVariableScope.reservedStringStack).push(value);") } printer.write("}") @@ -529,8 +521,7 @@ public struct BridgeJSLink { printer.write("} else {") printer.indent { printer.write(lines: [ - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len);", - "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes);", + "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);" ]) } printer.write("}") @@ -1039,6 +1030,16 @@ public struct BridgeJSLink { "\(JSGlueVariableScope.reservedMemory) = \(JSGlueVariableScope.reservedInstance).exports.memory;", ]) printer.nextLine() + if sharedMemory { + printer.write( + "\(JSGlueVariableScope.reservedDecodeString) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0).slice(); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" + ) + } else { + printer.write( + "\(JSGlueVariableScope.reservedDecodeString) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" + ) + } + printer.nextLine() // Error handling printer.write("\(JSGlueVariableScope.reservedSetException) = (error) => {") printer.indent { diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index ba0d0d86c..bec5ce3e9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -13,6 +13,7 @@ final class JSGlueVariableScope { static let reservedInstance = "instance" static let reservedMemory = "memory" static let reservedSetException = "setException" + static let reservedDecodeString = "decodeString" static let reservedStorageToReturnString = "tmpRetString" static let reservedStorageToReturnBytes = "tmpRetBytes" static let reservedStorageToReturnException = "tmpRetException" @@ -40,6 +41,7 @@ final class JSGlueVariableScope { reservedInstance, reservedMemory, reservedSetException, + reservedDecodeString, reservedStorageToReturnString, reservedStorageToReturnBytes, reservedStorageToReturnException, @@ -261,17 +263,16 @@ struct IntrinsicJSFragment: Sendable { } ) static let stringLiftParameter = IntrinsicJSFragment( - parameters: ["objectId"], + parameters: ["bytes", "count"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) - let objectId = arguments[0] - let objectLabel = scope.variable("\(objectId)Object") - // TODO: Implement "take" operation + let bytesExpr = arguments[0] + let countExpr = arguments[1] + let stringLabel = scope.variable("string") printer.write( - "const \(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));" + "const \(stringLabel) = \(JSGlueVariableScope.reservedDecodeString)(\(bytesExpr), \(countExpr));" ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(objectId));") - return [objectLabel] + return [stringLabel] } ) static let stringLowerReturn = IntrinsicJSFragment( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index c3c3d5e7f..4511ed1df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -453,19 +453,20 @@ public func _bjs_validateSession(_ session: Int32) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_takesFeatureFlag") -fileprivate func bjs_takesFeatureFlag_extern(_ flag: Int32) -> Void +fileprivate func bjs_takesFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Void #else -fileprivate func bjs_takesFeatureFlag_extern(_ flag: Int32) -> Void { +fileprivate func bjs_takesFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_takesFeatureFlag(_ flag: Int32) -> Void { - return bjs_takesFeatureFlag_extern(flag) +@inline(never) fileprivate func bjs_takesFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Void { + return bjs_takesFeatureFlag_extern(flagBytes, flagLength) } func _$takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void { - let flagValue = flag.bridgeJSLowerParameter() - bjs_takesFeatureFlag(flagValue) + flag.bridgeJSWithLoweredParameter { (flagBytes, flagLength) in + bjs_takesFeatureFlag(flagBytes, flagLength) + } 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 b42f71563..5e7088db8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift @@ -20,20 +20,21 @@ func _$console_get() throws(JSException) -> JSConsole { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void #else -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { - return bjs_JSConsole_log_extern(self, message) +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { + return bjs_JSConsole_log_extern(self, messageBytes, messageLength) } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let messageValue = message.bridgeJSLowerParameter() - bjs_JSConsole_log(selfValue, messageValue) + message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + bjs_JSConsole_log(selfValue, messageBytes, messageLength) + } if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift index 58d69eed1..35b1c6281 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift @@ -20,19 +20,22 @@ func _$console_get() throws(JSException) -> JSConsole { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_parseInt") -fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 +fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 #else -fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 { +fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { - return bjs_parseInt_extern(string) +@inline(never) fileprivate func bjs_parseInt(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { + return bjs_parseInt_extern(stringBytes, stringLength) } func _$parseInt(_ string: String) throws(JSException) -> Double { - let stringValue = string.bridgeJSLowerParameter() - let ret = bjs_parseInt(stringValue) + let ret0 = string.bridgeJSWithLoweredParameter { (stringBytes, stringLength) in + let ret = bjs_parseInt(stringBytes, stringLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -41,20 +44,21 @@ func _$parseInt(_ string: String) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void #else -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { - return bjs_JSConsole_log_extern(self, message) +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { + return bjs_JSConsole_log_extern(self, messageBytes, messageLength) } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let messageValue = message.bridgeJSLowerParameter() - bjs_JSConsole_log(selfValue, messageValue) + message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + bjs_JSConsole_log(selfValue, messageBytes, messageLength) + } if let error = _swift_js_take_exception() { throw error } @@ -62,14 +66,14 @@ func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WebSocket_init") -fileprivate func bjs_WebSocket_init_extern(_ url: Int32) -> Int32 +fileprivate func bjs_WebSocket_init_extern(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 #else -fileprivate func bjs_WebSocket_init_extern(_ url: Int32) -> Int32 { +fileprivate func bjs_WebSocket_init_extern(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WebSocket_init(_ url: Int32) -> Int32 { - return bjs_WebSocket_init_extern(url) +@inline(never) fileprivate func bjs_WebSocket_init(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 { + return bjs_WebSocket_init_extern(urlBytes, urlLength) } #if arch(wasm32) @@ -85,8 +89,11 @@ fileprivate func bjs_WebSocket_close_extern(_ self: Int32) -> Void { } func _$WebSocket_init(_ url: String) throws(JSException) -> JSObject { - let urlValue = url.bridgeJSLowerParameter() - let ret = bjs_WebSocket_init(urlValue) + let ret0 = url.bridgeJSWithLoweredParameter { (urlBytes, urlLength) in + let ret = bjs_WebSocket_init(urlBytes, urlLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift index 2ff17ea24..7f7fa8685 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift @@ -136,14 +136,14 @@ fileprivate func bjs_WeirdNaming_Any_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_normalProperty_set") -fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_WeirdNaming_normalProperty_set_extern(self, newValue) +@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeirdNaming_normalProperty_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -172,14 +172,14 @@ fileprivate func bjs_WeirdNaming__123invalidStart_set_extern(_ self: Int32, _ ne #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_spaces_set") -fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_WeirdNaming_property_with_spaces_set_extern(self, newValue) +@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeirdNaming_property_with_spaces_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -196,38 +196,38 @@ fileprivate func bjs_WeirdNaming__specialChar_set_extern(_ self: Int32, _ newVal #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_constructor_set") -fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_WeirdNaming_constructor_set_extern(self, newValue) +@inline(never) fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeirdNaming_constructor_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_for_set") -fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_WeirdNaming_for_set_extern(self, newValue) +@inline(never) fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeirdNaming_for_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_any_set") -fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_WeirdNaming_any_set_extern(self, newValue) +@inline(never) fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeirdNaming_any_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -328,8 +328,9 @@ func _$WeirdNaming_Any_get(_ self: JSObject) throws(JSException) -> String { func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_normalProperty_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeirdNaming_normalProperty_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -355,8 +356,9 @@ 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() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -373,8 +375,9 @@ func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_constructor_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeirdNaming_constructor_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -382,8 +385,9 @@ func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws( func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_for_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeirdNaming_for_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -391,8 +395,9 @@ 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() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_any_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeirdNaming_any_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift index 11a644759..3e1de0030 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift @@ -20,14 +20,14 @@ func _$returnAnimatable() throws(JSException) -> Animatable { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_init") -fileprivate func bjs_Greeter_init_extern(_ name: Int32) -> Int32 +fileprivate func bjs_Greeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 #else -fileprivate func bjs_Greeter_init_extern(_ name: Int32) -> Int32 { +fileprivate func bjs_Greeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_init(_ name: Int32) -> Int32 { - return bjs_Greeter_init_extern(name) +@inline(never) fileprivate func bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 { + return bjs_Greeter_init_extern(nameBytes, nameLength) } #if arch(wasm32) @@ -56,14 +56,14 @@ fileprivate func bjs_Greeter_age_get_extern(_ self: Int32) -> Float64 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_name_set") -fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_Greeter_name_set_extern(self, newValue) +@inline(never) fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_Greeter_name_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -80,19 +80,22 @@ fileprivate func bjs_Greeter_greet_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_changeName") -fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void #else -fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void { +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_changeName(_ self: Int32, _ name: Int32) -> Void { - return bjs_Greeter_changeName_extern(self, name) +@inline(never) fileprivate func bjs_Greeter_changeName(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + return bjs_Greeter_changeName_extern(self, nameBytes, nameLength) } func _$Greeter_init(_ name: String) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let ret = bjs_Greeter_init(nameValue) + let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let ret = bjs_Greeter_init(nameBytes, nameLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -119,8 +122,9 @@ func _$Greeter_age_get(_ self: JSObject) throws(JSException) -> Double { func _$Greeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Greeter_name_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_Greeter_name_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -137,8 +141,9 @@ func _$Greeter_greet(_ self: JSObject) throws(JSException) -> String { func _$Greeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let nameValue = name.bridgeJSLowerParameter() - bjs_Greeter_changeName(selfValue, nameValue) + name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + bjs_Greeter_changeName(selfValue, nameBytes, nameLength) + } 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 eafbd3253..ca1078836 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -348,14 +348,14 @@ fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutabl #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_init") -fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 #else -fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 { +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_init(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 { - return bjs_WithOptionalJSClass_init_extern(valueOrNullIsSome, valueOrNullValue, valueOrUndefinedIsSome, valueOrUndefinedValue) +@inline(never) fileprivate func bjs_WithOptionalJSClass_init(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 { + return bjs_WithOptionalJSClass_init_extern(valueOrNullIsSome, valueOrNullBytes, valueOrNullLength, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) } #if arch(wasm32) @@ -456,26 +456,26 @@ fileprivate func bjs_WithOptionalJSClass_intOrUndefined_get_extern(_ self: Int32 #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrNull_set") -fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_WithOptionalJSClass_stringOrNull_set_extern(self, newValueIsSome, newValueValue) +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrNull_set_extern(self, newValueIsSome, newValueBytes, newValueLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrUndefined_set") -fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_WithOptionalJSClass_stringOrUndefined_set_extern(self, newValueIsSome, newValueValue) +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrUndefined_set_extern(self, newValueIsSome, newValueBytes, newValueLength) } #if arch(wasm32) @@ -552,26 +552,26 @@ fileprivate func bjs_WithOptionalJSClass_intOrUndefined_set_extern(_ self: Int32 #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrNull") -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - return bjs_WithOptionalJSClass_roundTripStringOrNull_extern(self, valueIsSome, valueValue) +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrNull_extern(self, valueIsSome, valueBytes, valueLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrUndefined") -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - return bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(self, valueIsSome, valueValue) +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(self, valueIsSome, valueBytes, valueLength) } #if arch(wasm32) @@ -647,9 +647,14 @@ fileprivate func bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(_ self: } func _$WithOptionalJSClass_init(_ valueOrNull: Optional, _ valueOrUndefined: JSUndefinedOr) throws(JSException) -> JSObject { - let (valueOrNullIsSome, valueOrNullValue) = valueOrNull.bridgeJSLowerParameter() - let (valueOrUndefinedIsSome, valueOrUndefinedValue) = valueOrUndefined.bridgeJSLowerParameter() - let ret = bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullValue, valueOrUndefinedIsSome, valueOrUndefinedValue) + let ret0 = valueOrNull.bridgeJSWithLoweredParameter { (valueOrNullIsSome, valueOrNullBytes, valueOrNullLength) in + let ret1 = valueOrUndefined.bridgeJSWithLoweredParameter { (valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) in + let ret = bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullBytes, valueOrNullLength, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) + return ret + } + return ret1 + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -730,8 +735,9 @@ func _$WithOptionalJSClass_intOrUndefined_get(_ self: JSObject) throws(JSExcepti func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -739,8 +745,9 @@ func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Option func _$WithOptionalJSClass_stringOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -802,8 +809,9 @@ func _$WithOptionalJSClass_intOrUndefined_set(_ self: JSObject, _ newValue: JSUn func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { let selfValue = self.bridgeJSLowerParameter() - let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueValue) + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueBytes, valueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -812,8 +820,9 @@ func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Opti func _$WithOptionalJSClass_roundTripStringOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { let selfValue = self.bridgeJSLowerParameter() - let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueValue) + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueBytes, valueLength) + } 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 785cb997a..d9cd22836 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -8,8 +8,9 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto func onValueChanged(_ value: String) -> Void { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - _extern_onValueChanged(jsObjectValue, valueValue) + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + _extern_onValueChanged(jsObjectValue, valueBytes, valueLength) + } } func onCountUpdated(count: Int) -> Bool { @@ -21,9 +22,11 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto func onLabelUpdated(_ prefix: String, _ suffix: String) -> Void { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let prefixValue = prefix.bridgeJSLowerParameter() - let suffixValue = suffix.bridgeJSLowerParameter() - _extern_onLabelUpdated(jsObjectValue, prefixValue, suffixValue) + prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in + suffix.bridgeJSWithLoweredParameter { (suffixBytes, suffixLength) in + _extern_onLabelUpdated(jsObjectValue, prefixBytes, prefixLength, suffixBytes, suffixLength) + } + } } func isCountEven() -> Bool { @@ -103,8 +106,9 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } set { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_optionalName_set(jsObjectValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_MyViewControllerDelegate_optionalName_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } } } @@ -116,8 +120,9 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } set { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_optionalRawEnum_set(jsObjectValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_MyViewControllerDelegate_optionalRawEnum_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } } } @@ -129,8 +134,9 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } set { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_rawStringEnum_set(jsObjectValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_MyViewControllerDelegate_rawStringEnum_set(jsObjectValue, newValueBytes, newValueLength) + } } } @@ -231,14 +237,14 @@ fileprivate func _extern_onSomethingHappened_extern(_ jsObject: Int32) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onValueChanged") -fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ value: Int32) -> Void +fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void #else -fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ value: Int32) -> Void { +fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onValueChanged(_ jsObject: Int32, _ value: Int32) -> Void { - return _extern_onValueChanged_extern(jsObject, value) +@inline(never) fileprivate func _extern_onValueChanged(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return _extern_onValueChanged_extern(jsObject, valueBytes, valueLength) } #if arch(wasm32) @@ -255,14 +261,14 @@ fileprivate func _extern_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32 #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onLabelUpdated") -fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void +fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void #else -fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void { +fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onLabelUpdated(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void { - return _extern_onLabelUpdated_extern(jsObject, prefix, suffix) +@inline(never) fileprivate func _extern_onLabelUpdated(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { + return _extern_onLabelUpdated_extern(jsObject, prefixBytes, prefixLength, suffixBytes, suffixLength) } #if arch(wasm32) @@ -411,14 +417,14 @@ fileprivate func bjs_MyViewControllerDelegate_optionalName_get_extern(_ jsObject #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalName_set") -fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_MyViewControllerDelegate_optionalName_set_extern(jsObject, newValueIsSome, newValueValue) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalName_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) } #if arch(wasm32) @@ -435,14 +441,14 @@ fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get_extern(_ jsObj #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalRawEnum_set") -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(jsObject, newValueIsSome, newValueValue) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) } #if arch(wasm32) @@ -459,14 +465,14 @@ fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get_extern(_ jsObjec #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_rawStringEnum_set") -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValue: Int32) -> Void { - return bjs_MyViewControllerDelegate_rawStringEnum_set_extern(jsObject, newValue) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_MyViewControllerDelegate_rawStringEnum_set_extern(jsObject, newValueBytes, newValueLength) } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift index 427c2b576..0760df764 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift @@ -21,19 +21,20 @@ public func _bjs_roundtripString(_ aBytes: Int32, _ aLength: Int32) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_checkString") -fileprivate func bjs_checkString_extern(_ a: Int32) -> Void +fileprivate func bjs_checkString_extern(_ aBytes: Int32, _ aLength: Int32) -> Void #else -fileprivate func bjs_checkString_extern(_ a: Int32) -> Void { +fileprivate func bjs_checkString_extern(_ aBytes: Int32, _ aLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_checkString(_ a: Int32) -> Void { - return bjs_checkString_extern(a) +@inline(never) fileprivate func bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { + return bjs_checkString_extern(aBytes, aLength) } func _$checkString(_ a: String) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - bjs_checkString(aValue) + a.bridgeJSWithLoweredParameter { (aBytes, aLength) in + bjs_checkString(aBytes, aLength) + } if let error = _swift_js_take_exception() { throw error } @@ -41,20 +42,21 @@ func _$checkString(_ a: String) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_checkStringWithLength") -fileprivate func bjs_checkStringWithLength_extern(_ a: Int32, _ b: Float64) -> Void +fileprivate func bjs_checkStringWithLength_extern(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void #else -fileprivate func bjs_checkStringWithLength_extern(_ a: Int32, _ b: Float64) -> Void { +fileprivate func bjs_checkStringWithLength_extern(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_checkStringWithLength(_ a: Int32, _ b: Float64) -> Void { - return bjs_checkStringWithLength_extern(a, b) +@inline(never) fileprivate func bjs_checkStringWithLength(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void { + return bjs_checkStringWithLength_extern(aBytes, aLength, b) } func _$checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - let bValue = b.bridgeJSLowerParameter() - bjs_checkStringWithLength(aValue, bValue) + a.bridgeJSWithLoweredParameter { (aBytes, aLength) in + let bValue = b.bridgeJSLowerParameter() + bjs_checkStringWithLength(aBytes, aLength, bValue) + } 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 d4bdc4a58..e2cf9e09b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -63,14 +63,14 @@ public func _invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpSta #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO") -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(_ callback: Int32, _ param0: Int32) -> Int32 { - return invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -91,8 +91,11 @@ private enum _BJS_Closure_10TestModule5ThemeO_5ThemeO { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return Theme.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -315,14 +318,14 @@ public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO #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, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - return invoke_js_callback_TestModule_10TestModuleSS_SS_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSS_SS_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -343,8 +346,11 @@ private enum _BJS_Closure_10TestModuleSS_SS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -693,14 +699,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10Htt #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { - return invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) @@ -721,8 +727,9 @@ private enum _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Value) + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Bytes, param0Length) + } return Optional.bridgeJSLiftReturnFromSideChannel() #else fatalError("Only available on WebAssembly") @@ -945,14 +952,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9Direct #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSS_SqSS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { - return invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) @@ -973,8 +980,9 @@ private enum _BJS_Closure_10TestModuleSqSS_SqSS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Value) + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Bytes, param0Length) + } return Optional.bridgeJSLiftReturnFromSideChannel() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 81b432012..fcd29e31a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -21,6 +21,7 @@ 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; @@ -62,8 +63,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -72,8 +72,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -99,8 +98,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -157,8 +155,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -330,6 +327,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 6e7e810ca..d274e5606 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -189,6 +186,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index b514a50f8..67e73fb33 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -14,6 +14,7 @@ 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; @@ -79,8 +80,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -89,8 +89,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -116,8 +115,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -181,8 +179,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -261,6 +258,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 8627b2c80..7c31ce220 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -223,6 +220,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 8e9dfa65f..18cc2c945 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -89,6 +89,7 @@ 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; @@ -770,8 +771,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -780,8 +780,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -807,8 +806,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -865,8 +863,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -937,6 +934,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 0ea2b0a53..a79d508a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -32,6 +32,7 @@ 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; @@ -61,8 +62,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -71,8 +71,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -98,8 +97,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -149,8 +147,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -213,6 +210,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 7c3166d36..e52cf02d5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -52,6 +52,7 @@ 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; @@ -81,8 +82,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -91,8 +91,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -118,8 +117,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -169,8 +167,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -253,6 +250,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 6eea84ffa..2d05a7a2d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -33,6 +33,7 @@ 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; @@ -62,8 +63,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -72,8 +72,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -99,8 +98,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -150,8 +148,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -234,6 +231,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index efd75f1fa..5d28ce60b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -83,6 +83,7 @@ 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; @@ -113,8 +114,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -123,8 +123,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -150,8 +149,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -201,8 +199,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -261,11 +258,10 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flag) { + TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flagBytes, flagCount) { try { - const flagObject = swift.memory.getObject(flag); - swift.memory.release(flag); - imports.takesFeatureFlag(flagObject); + const string = decodeString(flagBytes, flagCount); + imports.takesFeatureFlag(string); } catch (error) { setException(error); } @@ -284,6 +280,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 21613733e..4d1e7abdf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -195,11 +192,10 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, message) { + TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageBytes, messageCount) { try { - const messageObject = swift.memory.getObject(message); - swift.memory.release(message); - swift.memory.getObject(self).log(messageObject); + const string = decodeString(messageBytes, messageCount); + swift.memory.getObject(self).log(string); } catch (error) { setException(error); } @@ -209,6 +205,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 21296b88a..e4a17ebd0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -194,31 +191,28 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_parseInt"] = function bjs_parseInt(string) { + TestModule["bjs_parseInt"] = function bjs_parseInt(stringBytes, stringCount) { try { - const stringObject = swift.memory.getObject(string); - swift.memory.release(string); - let ret = globalThis.parseInt(stringObject); + const string = decodeString(stringBytes, stringCount); + let ret = globalThis.parseInt(string); return ret; } catch (error) { setException(error); return 0 } } - TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, message) { + TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageBytes, messageCount) { try { - const messageObject = swift.memory.getObject(message); - swift.memory.release(message); - swift.memory.getObject(self).log(messageObject); + const string = decodeString(messageBytes, messageCount); + swift.memory.getObject(self).log(string); } catch (error) { setException(error); } } - TestModule["bjs_WebSocket_init"] = function bjs_WebSocket_init(url) { + TestModule["bjs_WebSocket_init"] = function bjs_WebSocket_init(urlBytes, urlCount) { try { - const urlObject = swift.memory.getObject(url); - swift.memory.release(url); - return swift.memory.retain(new globalThis.WebSocket(urlObject)); + const string = decodeString(urlBytes, urlCount); + return swift.memory.retain(new globalThis.WebSocket(string)); } catch (error) { setException(error); return 0 @@ -236,6 +230,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 2a2fd3d50..7a97a47ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -223,6 +220,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 8b938f75a..cfb0f75e7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -8,6 +8,7 @@ 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; @@ -76,8 +77,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -86,8 +86,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -113,8 +112,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -171,8 +169,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -244,6 +241,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index eabfe8c13..ca54d8f16 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -276,11 +273,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_normalProperty_set"] = function bjs_WeirdNaming_normalProperty_set(self, newValue) { + TestModule["bjs_WeirdNaming_normalProperty_set"] = function bjs_WeirdNaming_normalProperty_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self).normalProperty = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self).normalProperty = string; } catch (error) { setException(error); } @@ -299,11 +295,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_property_with_spaces_set"] = function bjs_WeirdNaming_property_with_spaces_set(self, newValue) { + TestModule["bjs_WeirdNaming_property_with_spaces_set"] = function bjs_WeirdNaming_property_with_spaces_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self)["property with spaces"] = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self)["property with spaces"] = string; } catch (error) { setException(error); } @@ -315,29 +310,26 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_constructor_set"] = function bjs_WeirdNaming_constructor_set(self, newValue) { + TestModule["bjs_WeirdNaming_constructor_set"] = function bjs_WeirdNaming_constructor_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self).constructor = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self).constructor = string; } catch (error) { setException(error); } } - TestModule["bjs_WeirdNaming_for_set"] = function bjs_WeirdNaming_for_set(self, newValue) { + TestModule["bjs_WeirdNaming_for_set"] = function bjs_WeirdNaming_for_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self).for = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self).for = string; } catch (error) { setException(error); } } - TestModule["bjs_WeirdNaming_any_set"] = function bjs_WeirdNaming_any_set(self, newValue) { + TestModule["bjs_WeirdNaming_any_set"] = function bjs_WeirdNaming_any_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self).Any = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self).Any = string; } catch (error) { setException(error); } @@ -376,6 +368,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index d84c77d45..7e97170e9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -195,11 +192,10 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_Greeter_init"] = function bjs_Greeter_init(name) { + TestModule["bjs_Greeter_init"] = function bjs_Greeter_init(nameBytes, nameCount) { try { - const nameObject = swift.memory.getObject(name); - swift.memory.release(name); - return swift.memory.retain(new imports.Greeter(nameObject)); + const string = decodeString(nameBytes, nameCount); + return swift.memory.retain(new imports.Greeter(string)); } catch (error) { setException(error); return 0 @@ -223,11 +219,10 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_Greeter_name_set"] = function bjs_Greeter_name_set(self, newValue) { + TestModule["bjs_Greeter_name_set"] = function bjs_Greeter_name_set(self, newValueBytes, newValueCount) { try { - const newValueObject = swift.memory.getObject(newValue); - swift.memory.release(newValue); - swift.memory.getObject(self).name = newValueObject; + const string = decodeString(newValueBytes, newValueCount); + swift.memory.getObject(self).name = string; } catch (error) { setException(error); } @@ -241,11 +236,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_Greeter_changeName"] = function bjs_Greeter_changeName(self, name) { + TestModule["bjs_Greeter_changeName"] = function bjs_Greeter_changeName(self, nameBytes, nameCount) { try { - const nameObject = swift.memory.getObject(name); - swift.memory.release(name); - swift.memory.getObject(self).changeName(nameObject); + const string = decodeString(nameBytes, nameCount); + swift.memory.getObject(self).changeName(string); } catch (error) { setException(error); } @@ -273,6 +267,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index 6912af0f3..39a859e4a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -253,6 +250,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 8571bbd6c..9ed0b93f2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -8,6 +8,7 @@ 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; @@ -127,8 +128,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -137,8 +137,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -164,8 +163,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -215,8 +213,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -324,6 +321,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index dd0e0c55e..1b5651765 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -197,6 +194,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 523df73cd..840a7a107 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -205,6 +202,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 4d08957d0..672d5ef7b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -197,6 +194,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index ac55ae750..8401e96b4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -209,6 +206,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 1fb247cbe..9efb38ffa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -209,6 +206,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 941d66ea9..f247c8efc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -198,21 +195,19 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(obj); }; const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_WithOptionalJSClass_init"] = function bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullObjectId, valueOrUndefinedIsSome, valueOrUndefinedObjectId) { + TestModule["bjs_WithOptionalJSClass_init"] = function bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullBytes, valueOrNullCount, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedCount) { try { let optResult; if (valueOrNullIsSome) { - const valueOrNullObjectIdObject = swift.memory.getObject(valueOrNullObjectId); - swift.memory.release(valueOrNullObjectId); - optResult = valueOrNullObjectIdObject; + const string = decodeString(valueOrNullBytes, valueOrNullCount); + optResult = string; } else { optResult = null; } let optResult1; if (valueOrUndefinedIsSome) { - const valueOrUndefinedObjectIdObject = swift.memory.getObject(valueOrUndefinedObjectId); - swift.memory.release(valueOrUndefinedObjectId); - optResult1 = valueOrUndefinedObjectIdObject; + const string1 = decodeString(valueOrUndefinedBytes, valueOrUndefinedCount); + optResult1 = string1; } else { optResult1 = undefined; } @@ -294,13 +289,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueObjectId) { + TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueBytes, newValueCount) { try { let optResult; if (newValueIsSome) { - const newValueObjectIdObject = swift.memory.getObject(newValueObjectId); - swift.memory.release(newValueObjectId); - optResult = newValueObjectIdObject; + const string = decodeString(newValueBytes, newValueCount); + optResult = string; } else { optResult = null; } @@ -309,13 +303,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_stringOrUndefined_set"] = function bjs_WithOptionalJSClass_stringOrUndefined_set(self, newValueIsSome, newValueObjectId) { + TestModule["bjs_WithOptionalJSClass_stringOrUndefined_set"] = function bjs_WithOptionalJSClass_stringOrUndefined_set(self, newValueIsSome, newValueBytes, newValueCount) { try { let optResult; if (newValueIsSome) { - const newValueObjectIdObject = swift.memory.getObject(newValueObjectId); - swift.memory.release(newValueObjectId); - optResult = newValueObjectIdObject; + const string = decodeString(newValueBytes, newValueCount); + optResult = string; } else { optResult = undefined; } @@ -366,13 +359,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueObjectId) { + TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueBytes, valueCount) { try { let optResult; if (valueIsSome) { - const valueObjectIdObject = swift.memory.getObject(valueObjectId); - swift.memory.release(valueObjectId); - optResult = valueObjectIdObject; + const string = decodeString(valueBytes, valueCount); + optResult = string; } else { optResult = null; } @@ -383,13 +375,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_roundTripStringOrUndefined"] = function bjs_WithOptionalJSClass_roundTripStringOrUndefined(self, valueIsSome, valueObjectId) { + TestModule["bjs_WithOptionalJSClass_roundTripStringOrUndefined"] = function bjs_WithOptionalJSClass_roundTripStringOrUndefined(self, valueIsSome, valueBytes, valueCount) { try { let optResult; if (valueIsSome) { - const valueObjectIdObject = swift.memory.getObject(valueObjectId); - swift.memory.release(valueObjectId); - optResult = valueObjectIdObject; + const string = decodeString(valueBytes, valueCount); + optResult = string; } else { optResult = undefined; } @@ -459,6 +450,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 8999ae8b6..770212417 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -198,6 +195,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index c8372362d..0efb2d2b5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -209,6 +206,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index dbdd030b6..338e87f9a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -197,6 +194,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 6e95d2ddf..79711d878 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -32,6 +32,7 @@ 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; @@ -94,8 +95,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -104,8 +104,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -131,8 +130,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -182,8 +180,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -291,13 +288,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueObjectId) { + TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueBytes, valueCount) { try { let optResult; if (valueIsSome) { - const valueObjectIdObject = swift.memory.getObject(valueObjectId); - swift.memory.release(valueObjectId); - optResult = valueObjectIdObject; + const string = decodeString(valueBytes, valueCount); + optResult = string; } else { optResult = null; } @@ -314,13 +310,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueObjectId) { + TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueBytes, valueCount) { try { let optResult; if (valueIsSome) { - const valueObjectIdObject = swift.memory.getObject(valueObjectId); - swift.memory.release(valueObjectId); - optResult = valueObjectIdObject; + const string = decodeString(valueBytes, valueCount); + optResult = string; } else { optResult = null; } @@ -338,11 +333,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_rawStringEnum_set"] = function bjs_MyViewControllerDelegate_rawStringEnum_set(self, value) { + TestModule["bjs_MyViewControllerDelegate_rawStringEnum_set"] = function bjs_MyViewControllerDelegate_rawStringEnum_set(self, valueBytes, valueCount) { try { - const valueObject = swift.memory.getObject(value); - swift.memory.release(value); - swift.memory.getObject(self).rawStringEnum = valueObject; + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(self).rawStringEnum = string; } catch (error) { setException(error); } @@ -462,11 +456,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_onValueChanged"] = function bjs_MyViewControllerDelegate_onValueChanged(self, value) { + TestModule["bjs_MyViewControllerDelegate_onValueChanged"] = function bjs_MyViewControllerDelegate_onValueChanged(self, valueBytes, valueCount) { try { - const valueObject = swift.memory.getObject(value); - swift.memory.release(value); - swift.memory.getObject(self).onValueChanged(valueObject); + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(self).onValueChanged(string); } catch (error) { setException(error); } @@ -480,13 +473,11 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_MyViewControllerDelegate_onLabelUpdated"] = function bjs_MyViewControllerDelegate_onLabelUpdated(self, prefix, suffix) { + TestModule["bjs_MyViewControllerDelegate_onLabelUpdated"] = function bjs_MyViewControllerDelegate_onLabelUpdated(self, prefixBytes, prefixCount, suffixBytes, suffixCount) { try { - const prefixObject = swift.memory.getObject(prefix); - swift.memory.release(prefix); - const suffixObject = swift.memory.getObject(suffix); - swift.memory.release(suffix); - swift.memory.getObject(self).onLabelUpdated(prefixObject, suffixObject); + const string = decodeString(prefixBytes, prefixCount); + const string1 = decodeString(suffixBytes, suffixCount); + swift.memory.getObject(self).onLabelUpdated(string, string1); } catch (error) { setException(error); } @@ -563,6 +554,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 0e8a5a7bb..800b07107 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -19,6 +19,7 @@ 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; @@ -81,8 +82,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -91,8 +91,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -118,8 +117,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -169,8 +167,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -241,6 +238,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 2eea1f12f..a4290f828 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -19,6 +19,7 @@ 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; @@ -81,8 +82,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -91,8 +91,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -118,8 +117,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -169,8 +167,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -241,6 +238,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 16bf8ba0c..056293ff7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -13,6 +13,7 @@ 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; @@ -42,8 +43,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -52,8 +52,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -79,8 +78,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -130,8 +128,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -202,6 +199,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index ea6c448ed..06f032555 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -13,6 +13,7 @@ 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; @@ -42,8 +43,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -52,8 +52,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -79,8 +78,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -130,8 +128,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -202,6 +199,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 480f40f92..d602d4e5a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -186,20 +183,18 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_checkString"] = function bjs_checkString(a) { + TestModule["bjs_checkString"] = function bjs_checkString(aBytes, aCount) { try { - const aObject = swift.memory.getObject(a); - swift.memory.release(a); - imports.checkString(aObject); + const string = decodeString(aBytes, aCount); + imports.checkString(string); } catch (error) { setException(error); } } - TestModule["bjs_checkStringWithLength"] = function bjs_checkStringWithLength(a, b) { + TestModule["bjs_checkStringWithLength"] = function bjs_checkStringWithLength(aBytes, aCount, b) { try { - const aObject = swift.memory.getObject(a); - swift.memory.release(a); - imports.checkStringWithLength(aObject, b); + const string = decodeString(aBytes, aCount); + imports.checkStringWithLength(string, b); } catch (error) { setException(error); } @@ -209,6 +204,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index 49f07b5ef..b2241d6ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -200,6 +197,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index a74d49327..9acf70de2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -225,6 +222,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 023a2fab0..09eb39050 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -38,6 +38,7 @@ 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; @@ -153,8 +154,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -163,8 +163,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -190,8 +189,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -241,8 +239,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -327,12 +324,11 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO); } - bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO"] = function(callbackId, param0) { + bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO"] = function(callbackId, param0Bytes, param0Count) { try { const callback = swift.memory.getObject(callbackId); - const param0Object = swift.memory.getObject(param0); - swift.memory.release(param0); - let ret = callback(param0Object); + const string = decodeString(param0Bytes, param0Count); + let ret = callback(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; } catch (error) { @@ -428,12 +424,11 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule9DirectionO_9DirectionO); } - bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0) { + bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0Bytes, param0Count) { try { const callback = swift.memory.getObject(callbackId); - const param0Object = swift.memory.getObject(param0); - swift.memory.release(param0); - let ret = callback(param0Object); + const string = decodeString(param0Bytes, param0Count); + let ret = callback(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; } catch (error) { @@ -575,14 +570,13 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO); } - bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(callbackId, param0IsSome, param0ObjectId) { + bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(callbackId, param0IsSome, param0Bytes, param0Count) { try { const callback = swift.memory.getObject(callbackId); let optResult; if (param0IsSome) { - const param0ObjectIdObject = swift.memory.getObject(param0ObjectId); - swift.memory.release(param0ObjectId); - optResult = param0ObjectIdObject; + const string = decodeString(param0Bytes, param0Count); + optResult = string; } else { optResult = null; } @@ -723,14 +717,13 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO); } - bjs["invoke_js_callback_TestModule_10TestModuleSqSS_SqSS"] = function(callbackId, param0IsSome, param0ObjectId) { + bjs["invoke_js_callback_TestModule_10TestModuleSqSS_SqSS"] = function(callbackId, param0IsSome, param0Bytes, param0Count) { try { const callback = swift.memory.getObject(callbackId); let optResult; if (param0IsSome) { - const param0ObjectIdObject = swift.memory.getObject(param0ObjectId); - swift.memory.release(param0ObjectId); - optResult = param0ObjectIdObject; + const string = decodeString(param0Bytes, param0Count); + optResult = string; } else { optResult = null; } @@ -888,6 +881,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index b5efd2150..21e382395 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -8,6 +8,7 @@ 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; @@ -63,8 +64,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +73,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -100,8 +99,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -151,8 +149,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -264,6 +261,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 617bda36b..cd2d396df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -13,6 +13,7 @@ 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; @@ -227,8 +228,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -237,8 +237,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -264,8 +263,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -364,8 +362,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -436,6 +433,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index d00b7450d..cb161707a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -8,6 +8,7 @@ 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; @@ -49,8 +50,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -59,8 +59,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -86,8 +85,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -144,8 +142,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -219,6 +216,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 2c415fc31..ae9625f00 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -8,6 +8,7 @@ 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; @@ -37,8 +38,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -47,8 +47,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -74,8 +73,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -125,8 +123,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -189,6 +186,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index c141a7926..169b001cf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -8,6 +8,7 @@ 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; @@ -54,8 +55,7 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -64,8 +64,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -91,8 +90,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -149,8 +147,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -213,6 +210,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index f8737237e..cc6c0359b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -8,6 +8,7 @@ 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; @@ -38,8 +39,7 @@ export async function createInstantiator(options, swift) { importObject["bjs"] = bjs; const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +48,7 @@ export async function createInstantiator(options, swift) { bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); + 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); @@ -75,8 +74,7 @@ export async function createInstantiator(options, swift) { f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); + const value = decodeString(ptr, len); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -126,8 +124,7 @@ export async function createInstantiator(options, swift) { if (isSome === 0) { tmpRetString = null; } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); + tmpRetString = decodeString(ptr, len); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -198,6 +195,8 @@ export async function createInstantiator(options, swift) { 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) } diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index c0de9413e..f2b2b6c34 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -348,9 +348,9 @@ extension String: _BridgedSwiftStackType { // MARK: ImportTS - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { return self.withUTF8 { b in - _swift_js_make_js_string(b.baseAddress.unsafelyUnwrapped, Int32(b.count)) + body(Int32(bitPattern: UInt32(UInt(bitPattern: b.baseAddress))), Int32(b.count)) } } @@ -737,7 +737,9 @@ extension _BridgedSwiftStruct { extension _BridgedSwiftEnumNoPayload where Self: RawRepresentable, RawValue == String { // MARK: ImportTS - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { rawValue.bridgeJSLowerParameter() } + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { + rawValue.bridgeJSWithLoweredParameter(body) + } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ id: Int32) -> Self { Self(rawValue: .bridgeJSLiftReturn(id))! @@ -1507,10 +1509,17 @@ extension _BridgedAsOptional where Wrapped == Bool { } extension _BridgedAsOptional where Wrapped == String { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Int32 - ) { - asOptional._bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSWithLoweredParameter( + _ body: (Int32, Int32, Int32) -> T + ) -> T { + switch asOptional { + case .none: + return body(0, 0, 0) + case .some(let value): + return value.bridgeJSWithLoweredParameter { bytes, count in + return body(1, bytes, count) + } + } } @_spi(BridgeJS) public static func bridgeJSLiftParameter( @@ -1683,14 +1692,16 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { extension _BridgedAsOptional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Int32 - ) { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSWithLoweredParameter( + _ body: (Int32, Int32, Int32) -> T + ) -> T { switch asOptional { case .none: - return (isSome: 0, value: 0) + return body(0, 0, 0) case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) + return wrapped.bridgeJSWithLoweredParameter { bytes, count in + return body(1, bytes, count) + } } } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 07c065be1..13aab1455 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -72,14 +72,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10H #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -100,8 +100,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -135,14 +138,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5Th #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -163,8 +166,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return Bool.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -513,14 +519,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9Di #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, _ param0: Int32) -> UnsafeMutableRawPointer +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -541,8 +547,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return Greeter.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -576,14 +585,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) @@ -604,8 +613,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(callbackValue, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -702,14 +714,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(callback, param0, param1, param2) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(callback, param0, param1Bytes, param1Length, param2) } #if arch(wasm32) @@ -731,9 +743,12 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() - let param1Value = param1.bridgeJSLowerParameter() - let param2Value = param2.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Value, param2Value) + let ret0 = param1.bridgeJSWithLoweredParameter { (param1Bytes, param1Length) in + let param2Value = param2.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Bytes, param1Length, param2Value) + return ret + } + let ret = ret0 return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -1020,14 +1035,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) @@ -1048,8 +1063,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Value) + let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Bytes, param0Length) + return ret + } + let ret = ret0 return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -1335,14 +1353,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9 #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) @@ -1363,8 +1381,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Value) + 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") @@ -1705,9 +1726,11 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { func setLabelElements(_ labelPrefix: String, _ labelSuffix: String) -> Void { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let labelPrefixValue = labelPrefix.bridgeJSLowerParameter() - let labelSuffixValue = labelSuffix.bridgeJSLowerParameter() - _extern_setLabelElements(jsObjectValue, labelPrefixValue, labelSuffixValue) + labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in + labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in + _extern_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) + } + } } func getLabel() -> String { @@ -1789,8 +1812,9 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } set { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } } } @@ -1828,8 +1852,9 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } set { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } } } @@ -1916,14 +1941,14 @@ fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_setLabelElements") -fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void +fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void #else -fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void { +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, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void { - return _extern_setLabelElements_extern(jsObject, labelPrefix, labelSuffix) +@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) @@ -2072,14 +2097,14 @@ fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_set") -fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +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, _ newValueValue: Int32) -> Void { +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, _ newValueValue: Int32) -> Void { - return bjs_DataProcessor_optionalTag_set_extern(jsObject, newValueIsSome, newValueValue) +@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) @@ -2144,14 +2169,14 @@ fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_set") -fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +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, _ newValueValue: Int32) -> Void { +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, _ newValueValue: Int32) -> Void { - return bjs_DataProcessor_optionalTheme_set_extern(jsObject, newValueIsSome, newValueValue) +@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) @@ -9223,14 +9248,14 @@ fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementObject_init") -fileprivate func bjs_ArrayElementObject_init_extern(_ id: Int32) -> Int32 +fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 #else -fileprivate func bjs_ArrayElementObject_init_extern(_ id: Int32) -> Int32 { +fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ArrayElementObject_init(_ id: Int32) -> Int32 { - return bjs_ArrayElementObject_init_extern(id) +@inline(never) fileprivate func bjs_ArrayElementObject_init(_ idBytes: Int32, _ idLength: Int32) -> Int32 { + return bjs_ArrayElementObject_init_extern(idBytes, idLength) } #if arch(wasm32) @@ -9246,8 +9271,11 @@ fileprivate func bjs_ArrayElementObject_id_get_extern(_ self: Int32) -> Int32 { } func _$ArrayElementObject_init(_ id: String) throws(JSException) -> JSObject { - let idValue = id.bridgeJSLowerParameter() - let ret = bjs_ArrayElementObject_init(idValue) + let ret0 = id.bridgeJSWithLoweredParameter { (idBytes, idLength) in + let ret = bjs_ArrayElementObject_init(idBytes, idLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -9667,14 +9695,14 @@ fileprivate func bjs_ClosureSupportImports_jsApplyDouble_static_extern(_ value: #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyString_static") -fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ value: Int32, _ transform: Int32) -> Int32 +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 #else -fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ value: Int32, _ transform: Int32) -> Int32 { +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyString_static(_ value: Int32, _ transform: Int32) -> Int32 { - return bjs_ClosureSupportImports_jsApplyString_static_extern(value, transform) +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyString_static(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyString_static_extern(valueBytes, valueLength, transform) } #if arch(wasm32) @@ -9715,14 +9743,14 @@ fileprivate func bjs_ClosureSupportImports_jsMakeDoubleToDouble_static_extern(_ #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeStringToString_static") -fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefix: Int32) -> Int32 +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 #else -fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefix: Int32) -> Int32 { +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static(_ prefix: Int32) -> Int32 { - return bjs_ClosureSupportImports_jsMakeStringToString_static_extern(prefix) +@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsMakeStringToString_static_extern(prefixBytes, prefixLength) } #if arch(wasm32) @@ -9871,9 +9899,12 @@ func _$ClosureSupportImports_jsApplyDouble(_ value: Double, _ transform: JSTyped } func _$ClosureSupportImports_jsApplyString(_ value: String, _ transform: JSTypedClosure<(String) -> String>) throws(JSException) -> String { - let valueValue = value.bridgeJSLowerParameter() - let transformFuncRef = transform.bridgeJSLowerParameter() - let ret = bjs_ClosureSupportImports_jsApplyString_static(valueValue, transformFuncRef) + let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyString_static(valueBytes, valueLength, transformFuncRef) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -9909,8 +9940,11 @@ func _$ClosureSupportImports_jsMakeDoubleToDouble(_ base: Double) throws(JSExcep } func _$ClosureSupportImports_jsMakeStringToString(_ prefix: String) throws(JSException) -> (String) -> String { - let prefixValue = prefix.bridgeJSLowerParameter() - let ret = bjs_ClosureSupportImports_jsMakeStringToString_static(prefixValue) + let ret0 = prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in + let ret = bjs_ClosureSupportImports_jsMakeStringToString_static(prefixBytes, prefixLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10140,14 +10174,14 @@ func _$DictionarySupportImports_jsRoundTripDictionaryDoubleArray(_ values: [Stri #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_init") -fileprivate func bjs_Foo_init_extern(_ value: Int32) -> Int32 +fileprivate func bjs_Foo_init_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 #else -fileprivate func bjs_Foo_init_extern(_ value: Int32) -> Int32 { +fileprivate func bjs_Foo_init_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Foo_init(_ value: Int32) -> Int32 { - return bjs_Foo_init_extern(value) +@inline(never) fileprivate func bjs_Foo_init(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { + return bjs_Foo_init_extern(valueBytes, valueLength) } #if arch(wasm32) @@ -10163,8 +10197,11 @@ fileprivate func bjs_Foo_value_get_extern(_ self: Int32) -> Int32 { } func _$Foo_init(_ value: String) throws(JSException) -> JSObject { - let valueValue = value.bridgeJSLowerParameter() - let ret = bjs_Foo_init(valueValue) + let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let ret = bjs_Foo_init(valueBytes, valueLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10263,19 +10300,22 @@ func _$jsRoundTripBool(_ v: Bool) throws(JSException) -> Bool { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripString") -fileprivate func bjs_jsRoundTripString_extern(_ v: Int32) -> Int32 +fileprivate func bjs_jsRoundTripString_extern(_ vBytes: Int32, _ vLength: Int32) -> Int32 #else -fileprivate func bjs_jsRoundTripString_extern(_ v: Int32) -> Int32 { +fileprivate func bjs_jsRoundTripString_extern(_ vBytes: Int32, _ vLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripString(_ v: Int32) -> Int32 { - return bjs_jsRoundTripString_extern(v) +@inline(never) fileprivate func bjs_jsRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { + return bjs_jsRoundTripString_extern(vBytes, vLength) } func _$jsRoundTripString(_ v: String) throws(JSException) -> String { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripString(vValue) + let ret0 = v.bridgeJSWithLoweredParameter { (vBytes, vLength) in + let ret = bjs_jsRoundTripString(vBytes, vLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10388,19 +10428,22 @@ func _$jsThrowOrString(_ shouldThrow: Bool) throws(JSException) -> String { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripFeatureFlag") -fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flag: Int32) -> Int32 +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 #else -fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flag: Int32) -> Int32 { +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripFeatureFlag(_ flag: Int32) -> Int32 { - return bjs_jsRoundTripFeatureFlag_extern(flag) +@inline(never) fileprivate func bjs_jsRoundTripFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 { + return bjs_jsRoundTripFeatureFlag_extern(flagBytes, flagLength) } func _$jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> FeatureFlag { - let flagValue = flag.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripFeatureFlag(flagValue) + let ret0 = flag.bridgeJSWithLoweredParameter { (flagBytes, flagLength) in + let ret = bjs_jsRoundTripFeatureFlag(flagBytes, flagLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10449,19 +10492,22 @@ func _$_jsWeirdFunction() throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_parseInt") -fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 +fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 #else -fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 { +fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { - return bjs_parseInt_extern(string) +@inline(never) fileprivate func bjs_parseInt(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { + return bjs_parseInt_extern(stringBytes, stringLength) } func _$parseInt(_ string: String) throws(JSException) -> Double { - let stringValue = string.bridgeJSLowerParameter() - let ret = bjs_parseInt(stringValue) + let ret0 = string.bridgeJSWithLoweredParameter { (stringBytes, stringLength) in + let ret = bjs_parseInt(stringBytes, stringLength) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10470,14 +10516,14 @@ func _$parseInt(_ string: String) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_init") -fileprivate func bjs_JsGreeter_init_extern(_ name: Int32, _ prefix: Int32) -> Int32 +fileprivate func bjs_JsGreeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 #else -fileprivate func bjs_JsGreeter_init_extern(_ name: Int32, _ prefix: Int32) -> Int32 { +fileprivate func bjs_JsGreeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_init(_ name: Int32, _ prefix: Int32) -> Int32 { - return bjs_JsGreeter_init_extern(name, prefix) +@inline(never) fileprivate func bjs_JsGreeter_init(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + return bjs_JsGreeter_init_extern(nameBytes, nameLength, prefixBytes, prefixLength) } #if arch(wasm32) @@ -10506,14 +10552,14 @@ fileprivate func bjs_JsGreeter_prefix_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_set") -fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_JsGreeter_name_set_extern(self, newValue) +@inline(never) fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_JsGreeter_name_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -10530,20 +10576,25 @@ fileprivate func bjs_JsGreeter_greet_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_changeName") -fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void #else -fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void { +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ name: Int32) -> Void { - return bjs_JsGreeter_changeName_extern(self, name) +@inline(never) fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + return bjs_JsGreeter_changeName_extern(self, nameBytes, nameLength) } func _$JsGreeter_init(_ name: String, _ prefix: String) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let prefixValue = prefix.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_init(nameValue, prefixValue) + let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let ret1 = prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in + let ret = bjs_JsGreeter_init(nameBytes, nameLength, prefixBytes, prefixLength) + return ret + } + return ret1 + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10570,8 +10621,9 @@ func _$JsGreeter_prefix_get(_ self: JSObject) throws(JSException) -> String { func _$JsGreeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_JsGreeter_name_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_JsGreeter_name_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -10588,8 +10640,9 @@ func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let nameValue = name.bridgeJSLowerParameter() - bjs_JsGreeter_changeName(selfValue, nameValue) + name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + bjs_JsGreeter_changeName(selfValue, nameBytes, nameLength) + } if let error = _swift_js_take_exception() { throw error } @@ -10761,14 +10814,14 @@ func _$StaticBox_value(_ self: JSObject) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_init") -fileprivate func bjs_Animal_init_extern(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 +fileprivate func bjs_Animal_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 #else -fileprivate func bjs_Animal_init_extern(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { +fileprivate func bjs_Animal_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Animal_init(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { - return bjs_Animal_init_extern(name, age, isCat) +@inline(never) fileprivate func bjs_Animal_init(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { + return bjs_Animal_init_extern(nameBytes, nameLength, age, isCat) } #if arch(wasm32) @@ -10809,14 +10862,14 @@ fileprivate func bjs_Animal_isCat_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_set") -fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void #else -fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValue: Int32) -> Void { - return bjs_Animal_name_set_extern(self, newValue) +@inline(never) fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_Animal_name_set_extern(self, newValueBytes, newValueLength) } #if arch(wasm32) @@ -10868,10 +10921,13 @@ fileprivate func bjs_Animal_getIsCat_extern(_ self: Int32) -> Int32 { } func _$Animal_init(_ name: String, _ age: Double, _ isCat: Bool) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let ageValue = age.bridgeJSLowerParameter() - let isCatValue = isCat.bridgeJSLowerParameter() - let ret = bjs_Animal_init(nameValue, ageValue, isCatValue) + let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let ageValue = age.bridgeJSLowerParameter() + let isCatValue = isCat.bridgeJSLowerParameter() + let ret = bjs_Animal_init(nameBytes, nameLength, ageValue, isCatValue) + return ret + } + let ret = ret0 if let error = _swift_js_take_exception() { throw error } @@ -10907,8 +10963,9 @@ func _$Animal_isCat_get(_ self: JSObject) throws(JSException) -> Bool { func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Animal_name_set(selfValue, newValueValue) + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_Animal_name_set(selfValue, newValueBytes, newValueLength) + } if let error = _swift_js_take_exception() { throw error } @@ -11348,26 +11405,26 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_s #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(nameIsSome, nameValue) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(nameIsSome, nameBytes, nameLength) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameValue) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameBytes, nameLength) } #if arch(wasm32) @@ -11449,8 +11506,9 @@ func _$OptionalSupportImports_jsRoundTripOptionalNumberUndefined(_ value: JSUnde } func _$OptionalSupportImports_jsRoundTripOptionalStringNull(_ name: Optional) throws(JSException) -> Optional { - let (nameIsSome, nameValue) = name.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(nameIsSome, nameValue) + name.bridgeJSWithLoweredParameter { (nameIsSome, nameBytes, nameLength) in + bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(nameIsSome, nameBytes, nameLength) + } if let error = _swift_js_take_exception() { throw error } @@ -11458,8 +11516,9 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringNull(_ name: Optional) throws(JSException) -> JSUndefinedOr { - let (nameIsSome, nameValue) = name.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(nameIsSome, nameValue) + name.bridgeJSWithLoweredParameter { (nameIsSome, nameBytes, nameLength) in + bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(nameIsSome, nameBytes, nameLength) + } if let error = _swift_js_take_exception() { throw error } From 40fa074ba407857c98b5fd7ef97fe6f1f235e04a Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 5 Mar 2026 22:01:18 +0800 Subject: [PATCH 017/140] BridgeJS: Include properties and release() in declare global class stubs --- .../BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 10 ++++++++++ .../BridgeJSLinkTests/EnumNamespace.Global.d.ts | 5 +++++ .../__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts | 1 + .../BridgeJSLinkTests/Namespaces.Global.d.ts | 4 ++++ 4 files changed, 20 insertions(+) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index af2456f81..fd907e8db 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -2947,6 +2947,16 @@ extension BridgeJSLink { "\(method.name)\(renderTSSignatureCallback(method.parameters, method.returnType, method.effects));" printer.write(methodSignature) } + + let sortedProperties = klass.properties.filter { !$0.isStatic }.sorted { + $0.name < $1.name + } + for property in sortedProperties { + let readonly = property.isReadonly ? "readonly " : "" + printer.write("\(readonly)\(property.name): \(property.type.tsType);") + } + + printer.write("release(): void;") } printer.write("}") } 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 936ae6b3a..b78f0cecd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -34,6 +34,7 @@ declare global { class Converter { constructor(); format(value: number): string; + release(): void; } } namespace Networking { @@ -41,6 +42,7 @@ declare global { class HTTPServer { constructor(); call(method: Networking.API.MethodTag): void; + release(): void; } const MethodValues: { readonly Get: 0; @@ -55,6 +57,7 @@ declare global { class TestServer { constructor(); call(method: Networking.APIV2.Internal.SupportedMethodTag): void; + release(): void; } const SupportedMethodValues: { readonly Get: 0; @@ -77,6 +80,8 @@ declare global { class Converter { constructor(); toString(value: number): string; + precision: number; + release(): void; } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts index 6f18e53ed..88485232e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts @@ -11,6 +11,7 @@ declare global { class GlobalClass { constructor(); greet(): string; + release(): void; } function globalFunction(): string; } 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 25ac1ac6d..4b7851c3e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -12,6 +12,7 @@ declare global { constructor(); addItem(item: Greeter): void; getItems(): Greeter[]; + release(): void; } } namespace MyModule { @@ -24,6 +25,7 @@ declare global { class Converter { constructor(); toString(value: number): string; + release(): void; } } } @@ -32,9 +34,11 @@ declare global { class Greeter { constructor(name: string); greet(): string; + release(): void; } class UUID { uuidString(): string; + release(): void; } } } From 757f2a07ee434f59466b856ee4d1a72b1f66e40f Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 5 Mar 2026 22:21:34 +0800 Subject: [PATCH 018/140] BridgeJS: Add E2E test for instance property access via globalThis --- .../Generated/BridgeJS.swift | 21 +++++++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 12 +++++++++++ .../BridgeJSGlobalTests/GlobalAPITests.swift | 2 ++ Tests/prelude.mjs | 3 +++ 4 files changed, 38 insertions(+) diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index ca9968838..a892720ce 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -296,6 +296,27 @@ public func _bjs_GlobalUtils_PublicConverter_toString(_ _self: UnsafeMutableRawP #endif } +@_expose(wasm, "bjs_GlobalUtils_PublicConverter_precision_get") +@_cdecl("bjs_GlobalUtils_PublicConverter_precision_get") +public func _bjs_GlobalUtils_PublicConverter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).precision + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_GlobalUtils_PublicConverter_precision_set") +@_cdecl("bjs_GlobalUtils_PublicConverter_precision_set") +public func _bjs_GlobalUtils_PublicConverter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_GlobalUtils_PublicConverter_deinit") @_cdecl("bjs_GlobalUtils_PublicConverter_deinit") public func _bjs_GlobalUtils_PublicConverter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index 2eeb8ed2d..9403e3b0c 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -156,7 +156,19 @@ "GlobalUtils" ], "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "precision", + "namespace" : [ + "GlobalUtils" + ], + "type" : { + "int" : { + } + } + } ], "swiftCallName" : "GlobalUtils.PublicConverter" } diff --git a/Tests/BridgeJSGlobalTests/GlobalAPITests.swift b/Tests/BridgeJSGlobalTests/GlobalAPITests.swift index 19087ff55..9bdb5c5e9 100644 --- a/Tests/BridgeJSGlobalTests/GlobalAPITests.swift +++ b/Tests/BridgeJSGlobalTests/GlobalAPITests.swift @@ -63,6 +63,8 @@ enum Internal { @JS enum GlobalUtils { @JS class PublicConverter { + @JS var precision: Int = 2 + @JS init() {} @JS func toString(value: Int) -> String { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 3aeb10a8b..0170da3bc 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -1032,6 +1032,9 @@ function BridgeJSGlobalTests_runJsWorksGlobal() { const globalConverter = new globalThis.GlobalUtils.PublicConverter(); assert.equal(globalConverter.toString(99), "99"); + assert.equal(globalConverter.precision, 2); + globalConverter.precision = 5; + assert.equal(globalConverter.precision, 5); globalConverter.release(); const globalHttpServer = new globalThis.GlobalNetworking.API.TestHTTPServer(); From 86f07ab426383d4661c0897b2c560391f8a7c7e5 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Fri, 6 Mar 2026 14:03:33 +1100 Subject: [PATCH 019/140] BridgeJS: Correctly emit @JS methods in extensions --- .../BridgeJSCore/SwiftToSkeleton.swift | 60 +++++++++++++- .../BridgeJSCodegenTests.swift | 18 ++++ .../Multifile/CrossFileExtension.swift | 5 ++ .../Multifile/CrossFileExtensionClass.swift | 4 + .../Inputs/MacroSwift/StaticFunctions.swift | 12 +++ .../Inputs/MacroSwift/SwiftClass.swift | 6 ++ .../Inputs/MacroSwift/SwiftStruct.swift | 6 ++ .../CrossFileExtension.json | 82 +++++++++++++++++++ .../CrossFileExtension.swift | 60 ++++++++++++++ .../StaticFunctions.Global.json | 69 ++++++++++++++++ .../StaticFunctions.Global.swift | 22 +++++ .../BridgeJSCodegenTests/StaticFunctions.json | 69 ++++++++++++++++ .../StaticFunctions.swift | 22 +++++ .../BridgeJSCodegenTests/SwiftClass.json | 17 ++++ .../BridgeJSCodegenTests/SwiftClass.swift | 11 +++ .../BridgeJSCodegenTests/SwiftStruct.json | 16 ++++ .../BridgeJSCodegenTests/SwiftStruct.swift | 11 +++ .../BridgeJSLinkTests/SwiftClass.d.ts | 1 + .../BridgeJSLinkTests/SwiftClass.js | 6 ++ 19 files changed, 496 insertions(+), 1 deletion(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 8f1b3fa35..2ff5cecba 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -43,12 +43,14 @@ public final class SwiftToSkeleton { var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = [] var importedFiles: [ImportedFileSkeleton] = [] var exported = ExportedSkeleton(functions: [], classes: [], enums: [], exposeToGlobal: exposeToGlobal) + var exportCollectors: [ExportSwiftAPICollector] = [] for (sourceFile, inputFilePath) in sourceFiles { progress.print("Processing \(inputFilePath)") let exportCollector = ExportSwiftAPICollector(parent: self) exportCollector.walk(sourceFile) + exportCollectors.append(exportCollector) let typeNameCollector = ImportSwiftMacrosJSImportTypeNameCollector(viewMode: .sourceAccurate) typeNameCollector.walk(sourceFile) @@ -74,7 +76,15 @@ public final class SwiftToSkeleton { if !importedFile.isEmpty { importedFiles.append(importedFile) } - exportCollector.finalize(&exported) + } + + // 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) + } + + for collector in exportCollectors { + collector.finalize(&exported) } if !perSourceErrors.isEmpty { @@ -486,6 +496,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { var exportedStructNames: [String] = [] var exportedStructByName: [String: ExportedStruct] = [:] var errors: [DiagnosticError] = [] + /// Extensions collected during the walk, to be resolved after all files have been walked + var deferredExtensions: [ExtensionDeclSyntax] = [] func finalize(_ result: inout ExportedSkeleton) { result.functions.append(contentsOf: exportedFunctions) @@ -1388,6 +1400,52 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } + override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { + // Defer until all type declarations in the module have been collected. + deferredExtensions.append(node) + 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 { + diagnose( + node: ext.extendedType, + message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", + hint: "You can only extend `@JS` annotated types defined in the same module" + ) + } + } + } + + /// Walks extension members under the matching type’s state, returning whether the type was found + func resolveExtension(_ ext: ExtensionDeclSyntax) -> Bool { + let name = ext.extendedType.trimmedDescription + 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 { + return false + } + stateStack.push(state: state) + for member in ext.memberBlock.members { + walk(member) + } + stateStack.pop() + return true + } + override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 9754fbced..1b1f95f76 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -167,6 +167,24 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileFunctionTypes.ReverseOrder") } + @Test + func codegenCrossFileExtension() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let classURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionClass.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classURL, encoding: .utf8)), + inputFilePath: "CrossFileExtensionClass.swift" + ) + let extensionURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtension.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: extensionURL, encoding: .utf8)), + inputFilePath: "CrossFileExtension.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtension") + } + + @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift new file mode 100644 index 000000000..ce9e8e2b0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift @@ -0,0 +1,5 @@ +extension Greeter { + @JS func greetFormally() -> String { + return "Good day, " + self.name + "." + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift new file mode 100644 index 000000000..48625d42a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift @@ -0,0 +1,4 @@ +@JS class Greeter { + @JS init(name: String) {} + @JS func greet() -> String { return "" } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift index 1d42cf415..25196d773 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift @@ -38,3 +38,15 @@ enum APIResult { } } } + +extension MathUtils { + @JS static func divide(a: Int, b: Int) -> Int { + return a / b + } +} + +extension Calculator { + @JS static func cube(value: Int) -> Int { + return value * value * value + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift index d7b5a5b8e..12004ffa8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift @@ -12,6 +12,12 @@ } } +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, " + self.name + "!!!" + } +} + @JS func takeGreeter(greeter: Greeter) { print(greeter.greet()) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 0d84f4736..d42b2e202 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -60,3 +60,9 @@ } @JS func roundtripContainer(_ container: Container) -> Container + +extension DataPoint { + @JS func distanceFromOrigin() -> Double { + return (x * x + y * y).squareRoot() + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json new file mode 100644 index 000000000..f77d39ad9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json @@ -0,0 +1,82 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_greetFormally", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetFormally", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + + ], + "swiftCallName" : "Greeter" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift new file mode 100644 index 000000000..ab73df508 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift @@ -0,0 +1,60 @@ +@_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_greetFormally") +@_cdecl("bjs_Greeter_greetFormally") +public func _bjs_Greeter_greetFormally(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetFormally() + return ret.bridgeJSLowerReturn() + #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 { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _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/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index b0eac3313..a5fc4e7e1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -125,6 +125,45 @@ } } + }, + { + "abiName" : "bjs_MathUtils_static_divide", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "divide", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } } ], "name" : "MathUtils", @@ -182,6 +221,36 @@ "_0" : "Calculator" } } + }, + { + "abiName" : "bjs_Calculator_static_cube", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "cube", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } } ], "staticProperties" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index b6d35a215..3478eb883 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -44,6 +44,17 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_cube") +@_cdecl("bjs_Calculator_static_cube") +public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -134,6 +145,17 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } +@_expose(wasm, "bjs_MathUtils_static_divide") +@_cdecl("bjs_MathUtils_static_divide") +public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index e4ec22855..b620fb0e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -125,6 +125,45 @@ } } + }, + { + "abiName" : "bjs_MathUtils_static_divide", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "divide", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } } ], "name" : "MathUtils", @@ -182,6 +221,36 @@ "_0" : "Calculator" } } + }, + { + "abiName" : "bjs_Calculator_static_cube", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "cube", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } } ], "staticProperties" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index b6d35a215..3478eb883 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -44,6 +44,17 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_cube") +@_cdecl("bjs_Calculator_static_cube") +public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -134,6 +145,17 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } +@_expose(wasm, "bjs_MathUtils_static_divide") +@_cdecl("bjs_MathUtils_static_divide") +public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index 7cebdd5e6..0245bf208 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -61,6 +61,23 @@ "returnType" : { "void" : { + } + } + }, + { + "abiName" : "bjs_Greeter_greetEnthusiastically", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetEnthusiastically", + "parameters" : [ + + ], + "returnType" : { + "string" : { + } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index 0e9434832..9f927da13 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -40,6 +40,17 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameByte #endif } +@_expose(wasm, "bjs_Greeter_greetEnthusiastically") +@_cdecl("bjs_Greeter_greetEnthusiastically") +public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 00c6af5cb..d216f10c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -211,7 +211,23 @@ ] }, "methods" : [ + { + "abiName" : "bjs_DataPoint_distanceFromOrigin", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "distanceFromOrigin", + "parameters" : [ + ], + "returnType" : { + "double" : { + + } + } + } ], "name" : "DataPoint", "properties" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 6fccb3280..5e867f179 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -66,6 +66,17 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #endif } +@_expose(wasm, "bjs_DataPoint_distanceFromOrigin") +@_cdecl("bjs_DataPoint_distanceFromOrigin") +public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { + #if arch(wasm32) + let ret = DataPoint.bridgeJSLiftParameter().distanceFromOrigin() + 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() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 05fc97fee..72f816bd5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -14,6 +14,7 @@ export interface SwiftHeapObject { export interface Greeter extends SwiftHeapObject { greet(): string; changeName(name: string): void; + greetEnthusiastically(): string; name: string; } export interface PublicGreeter extends SwiftHeapObject { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 9acf70de2..2596b539a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -282,6 +282,12 @@ export async function createInstantiator(options, swift) { const nameId = swift.memory.retain(nameBytes); instance.exports.bjs_Greeter_changeName(this.pointer, nameId, nameBytes.length); } + greetEnthusiastically() { + instance.exports.bjs_Greeter_greetEnthusiastically(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } get name() { instance.exports.bjs_Greeter_name_get(this.pointer); const ret = tmpRetString; From 6762c6b030795956d229544035c554ffec6dc877 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 10 Mar 2026 13:57:04 +1100 Subject: [PATCH 020/140] BridgeJS: Improve test coverage for @JS methods and properties in extensions --- .../Inputs/MacroSwift/StaticFunctions.swift | 4 + .../Inputs/MacroSwift/SwiftClass.swift | 8 + .../Inputs/MacroSwift/SwiftStruct.swift | 6 + .../StaticFunctions.Global.json | 28 +++ .../StaticFunctions.Global.swift | 22 +++ .../BridgeJSCodegenTests/StaticFunctions.json | 28 +++ .../StaticFunctions.swift | 22 +++ .../BridgeJSCodegenTests/SwiftClass.json | 47 +++++ .../BridgeJSCodegenTests/SwiftClass.swift | 33 ++++ .../BridgeJSCodegenTests/SwiftStruct.json | 37 ++++ .../BridgeJSCodegenTests/SwiftStruct.swift | 22 +++ .../StaticFunctions.Global.d.ts | 4 + .../StaticFunctions.Global.js | 18 ++ .../BridgeJSLinkTests/StaticFunctions.d.ts | 4 + .../BridgeJSLinkTests/StaticFunctions.js | 18 ++ .../BridgeJSLinkTests/SwiftClass.d.ts | 3 + .../BridgeJSLinkTests/SwiftClass.js | 16 ++ .../BridgeJSLinkTests/SwiftStruct.d.ts | 3 + .../BridgeJSLinkTests/SwiftStruct.js | 17 +- .../BridgeJSRuntimeTests/ExportAPITests.swift | 22 +++ .../Generated/BridgeJS.swift | 99 +++++++++++ .../Generated/JavaScript/BridgeJS.json | 161 ++++++++++++++++++ Tests/BridgeJSRuntimeTests/StructAPIs.swift | 12 ++ Tests/prelude.mjs | 19 +++ 24 files changed, 652 insertions(+), 1 deletion(-) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift index 25196d773..4f6296d2e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift @@ -43,10 +43,14 @@ extension MathUtils { @JS static func divide(a: Int, b: Int) -> Int { return a / b } + + @JS static var pi: Double { 3.14159 } } extension Calculator { @JS static func cube(value: Int) -> Int { return value * value * value } + + @JS static var version: String { "1.0" } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift index 12004ffa8..2fb050eeb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift @@ -16,6 +16,14 @@ extension Greeter { @JS func greetEnthusiastically() -> String { return "Hey, " + self.name + "!!!" } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } } @JS func takeGreeter(greeter: Greeter) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index d42b2e202..4ec6525e3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -65,4 +65,10 @@ extension DataPoint { @JS func distanceFromOrigin() -> Double { return (x * x + y * y).squareRoot() } + + @JS static func origin() -> DataPoint { + return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) + } + + @JS static var dimensions: Int { 2 } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index a5fc4e7e1..3e07317ac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -168,7 +168,21 @@ ], "name" : "MathUtils", "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "pi", + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + }, + "type" : { + "double" : { + } + } + } ], "swiftCallName" : "MathUtils" } @@ -254,7 +268,21 @@ } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 3478eb883..aa7af111f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -55,6 +55,17 @@ public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_version_get") +@_cdecl("bjs_Calculator_static_version_get") +public func _bjs_Calculator_static_version_get() -> Void { + #if arch(wasm32) + let ret = Calculator.version + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -156,6 +167,17 @@ public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_MathUtils_static_pi_get") +@_cdecl("bjs_MathUtils_static_pi_get") +public func _bjs_MathUtils_static_pi_get() -> Float64 { + #if arch(wasm32) + let ret = MathUtils.pi + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index b620fb0e2..a6540015f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -168,7 +168,21 @@ ], "name" : "MathUtils", "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "pi", + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + }, + "type" : { + "double" : { + } + } + } ], "swiftCallName" : "MathUtils" } @@ -254,7 +268,21 @@ } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 3478eb883..aa7af111f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -55,6 +55,17 @@ public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_version_get") +@_cdecl("bjs_Calculator_static_version_get") +public func _bjs_Calculator_static_version_get() -> Void { + #if arch(wasm32) + let ret = Calculator.version + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -156,6 +167,17 @@ public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_MathUtils_static_pi_get") +@_cdecl("bjs_MathUtils_static_pi_get") +public func _bjs_MathUtils_static_pi_get() -> Float64 { + #if arch(wasm32) + let ret = MathUtils.pi + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index 0245bf208..cf5156d8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -80,6 +80,28 @@ } } + }, + { + "abiName" : "bjs_Greeter_static_greetAnonymously", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "greetAnonymously", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + } } ], "name" : "Greeter", @@ -91,6 +113,31 @@ "type" : { "string" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "nameCount", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + }, + "type" : { + "string" : { + } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index 9f927da13..cb61e263d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -51,6 +51,17 @@ public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) #endif } +@_expose(wasm, "bjs_Greeter_static_greetAnonymously") +@_cdecl("bjs_Greeter_static_greetAnonymously") +public func _bjs_Greeter_static_greetAnonymously() -> Void { + #if arch(wasm32) + let ret = Greeter.greetAnonymously() + 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 { @@ -72,6 +83,28 @@ public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes #endif } +@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount + 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 { + #if arch(wasm32) + let ret = Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index d216f10c6..7a6421668 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -227,6 +227,28 @@ } } + }, + { + "abiName" : "bjs_DataPoint_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + } } ], "name" : "DataPoint", @@ -290,6 +312,21 @@ "_1" : "null" } } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "dimensions", + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + }, + "type" : { + "int" : { + + } + } } ], "swiftCallName" : "DataPoint" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 5e867f179..5e17b6db2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -66,6 +66,17 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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_distanceFromOrigin") @_cdecl("bjs_DataPoint_distanceFromOrigin") public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { @@ -77,6 +88,17 @@ public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { #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 +} + extension Address: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { let zipCode = Optional.bridgeJSStackPop() 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 a2f1c7d6d..5916e1648 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -22,6 +22,8 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; + cube(value: number): number; + readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -53,6 +55,8 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 800b07107..df2a34ff1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -297,6 +297,14 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } + static divide(a, b) { + const ret = instance.exports.bjs_MathUtils_static_divide(a, b); + return ret; + } + static get pi() { + const ret = instance.exports.bjs_MathUtils_static_pi_get(); + return ret; + } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -314,6 +322,16 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; + }, + cube: function(value) { + const ret = instance.exports.bjs_Calculator_static_cube(value); + return ret; + }, + get version() { + instance.exports.bjs_Calculator_static_version_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index e938ddb9a..c9cb26910 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -22,6 +22,8 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; + cube(value: number): number; + readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -43,6 +45,8 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index a4290f828..2e5b6e7f1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -297,6 +297,14 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } + static divide(a, b) { + const ret = instance.exports.bjs_MathUtils_static_divide(a, b); + return ret; + } + static get pi() { + const ret = instance.exports.bjs_MathUtils_static_pi_get(); + return ret; + } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -308,6 +316,16 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; + }, + cube: function(value) { + const ret = instance.exports.bjs_Calculator_static_cube(value); + return ret; + }, + get version() { + instance.exports.bjs_Calculator_static_version_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 72f816bd5..6d590950c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -16,6 +16,7 @@ export interface Greeter extends SwiftHeapObject { changeName(name: string): void; greetEnthusiastically(): string; name: string; + readonly nameCount: number; } export interface PublicGreeter extends SwiftHeapObject { } @@ -24,6 +25,8 @@ export interface PackageGreeter extends SwiftHeapObject { export type Exports = { Greeter: { new(name: string): Greeter; + greetAnonymously(): string; + readonly defaultGreeting: string; } PublicGreeter: { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 2596b539a..f6293f12a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -288,6 +288,12 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; } + static greetAnonymously() { + instance.exports.bjs_Greeter_static_greetAnonymously(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } get name() { instance.exports.bjs_Greeter_name_get(this.pointer); const ret = tmpRetString; @@ -299,6 +305,16 @@ export async function createInstantiator(options, swift) { const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); } + get nameCount() { + const ret = instance.exports.bjs_Greeter_nameCount_get(this.pointer); + return ret; + } + static get defaultGreeting() { + instance.exports.bjs_Greeter_static_defaultGreeting_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } } class PublicGreeter extends SwiftHeapObject { static __construct(ptr) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 4a61a26e3..211661d5f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -16,6 +16,7 @@ export interface DataPoint { label: string; optCount: number | null; optFlag: boolean | null; + distanceFromOrigin(): number; } export interface Address { street: string; @@ -65,6 +66,8 @@ export type Exports = { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index cd2d396df..099f4ccc3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -73,7 +73,13 @@ export async function createInstantiator(options, swift) { const string = strStack.pop(); const f64 = f64Stack.pop(); const f641 = f64Stack.pop(); - return { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; + const instance1 = { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; + instance1.distanceFromOrigin = function() { + structHelpers.DataPoint.lower(this); + const ret = instance.exports.bjs_DataPoint_distanceFromOrigin(); + return ret; + }.bind(instance1); + return instance1; } }); const __bjs_createAddressHelpers = () => ({ @@ -546,6 +552,15 @@ export async function createInstantiator(options, swift) { 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() { diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c8ebbc8ce..6997cfd3b 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -150,6 +150,20 @@ struct TestError: Error { } } +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, \(name)!!!" + } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } +} + @JS func takeGreeter(g: Greeter, name: String) { g.changeName(name: name) } @@ -250,6 +264,14 @@ struct TestError: Error { case auto = "auto" } +extension StaticCalculator { + @JS static func doubleValue(_ value: Int) -> Int { + return value * 2 + } + + @JS static var version: String { "1.0" } +} + @JS func setDirection(_ direction: Direction) -> Direction { return direction } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 13aab1455..cde1afc59 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3418,6 +3418,28 @@ public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { #endif } +@_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 = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) + 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 { + #if arch(wasm32) + 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 { @@ -4233,6 +4255,39 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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_distanceFromOrigin") +@_cdecl("bjs_DataPoint_distanceFromOrigin") +public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { + #if arch(wasm32) + let ret = DataPoint.bridgeJSLiftParameter().distanceFromOrigin() + 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 +} + extension PublicPoint: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { let y = Int.bridgeJSStackPop() @@ -6934,6 +6989,28 @@ public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> #endif } +@_expose(wasm, "bjs_Greeter_greetEnthusiastically") +@_cdecl("bjs_Greeter_greetEnthusiastically") +public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + 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 { + #if arch(wasm32) + let ret = Greeter.greetAnonymously() + 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 { @@ -6966,6 +7043,28 @@ public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { #endif } +@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount + 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 { + #if arch(wasm32) + let ret = Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 746e0cd3c..137fb6087 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -705,6 +705,45 @@ "useJSTypedClosure" : false } } + }, + { + "abiName" : "bjs_Greeter_greetEnthusiastically", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetEnthusiastically", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_static_greetAnonymously", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "greetAnonymously", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + } } ], "name" : "Greeter", @@ -726,6 +765,31 @@ "type" : { "string" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "nameCount", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + }, + "type" : { + "string" : { + } } } @@ -7620,10 +7684,54 @@ "_0" : "StaticCalculator" } } + }, + { + "abiName" : "bjs_StaticCalculator_static_doubleValue", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "doubleValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" + } + } } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "StaticCalculator", "tsFullPath" : "StaticCalculator" @@ -13342,7 +13450,45 @@ ] }, "methods" : [ + { + "abiName" : "bjs_DataPoint_distanceFromOrigin", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "distanceFromOrigin", + "parameters" : [ + + ], + "returnType" : { + "double" : { + } + } + }, + { + "abiName" : "bjs_DataPoint_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + } + } ], "name" : "DataPoint", "properties" : [ @@ -13405,6 +13551,21 @@ "_1" : "null" } } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "dimensions", + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + }, + "type" : { + "int" : { + + } + } } ], "swiftCallName" : "DataPoint" diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index 0a05a517d..af925cb77 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -174,6 +174,18 @@ import JavaScriptKit } } +extension DataPoint { + @JS func distanceFromOrigin() -> Double { + return (x * x + y * y).squareRoot() + } + + @JS static func origin() -> DataPoint { + return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) + } + + @JS static var dimensions: Int { 2 } +} + @JS func roundTripDataPoint(_ data: DataPoint) -> DataPoint { return data } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 4c211e91c..94d33057d 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -269,6 +269,12 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(g.name, "Bob"); assert.equal(g.greet(), "Hello, Bob!"); + // Test class extension members + assert.equal(g.greetEnthusiastically(), "Hey, Bob!!!"); + assert.equal(g.nameCount, 3); + assert.equal(exports.Greeter.greetAnonymously(), "Hello."); + assert.equal(exports.Greeter.defaultGreeting, "Hello, world!"); + const g2 = exports.roundTripSwiftHeapObject(g) assert.equal(g2.greet(), "Hello, Bob!"); assert.equal(g2.name, "Bob"); @@ -761,6 +767,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(StaticCalculatorValues.Basic, 1); assert.equal(StaticCalculatorValues.Scientific, exports.StaticCalculator.Scientific); assert.equal(StaticCalculatorValues.Basic, exports.StaticCalculator.Basic); + + // Test enum extension static members + assert.equal(exports.StaticCalculator.doubleValue(21), 42); + assert.equal(exports.StaticCalculator.version, "1.0"); assert.equal(exports.StaticUtils.Nested.roundtrip("hello world"), "hello world"); assert.equal(exports.StaticUtils.Nested.roundtrip("test"), "test"); @@ -779,6 +789,15 @@ function testStructSupport(exports) { const data2 = { x: 0.0, y: 0.0, label: "", optCount: null, optFlag: null }; assert.deepEqual(exports.roundTripDataPoint(data2), data2); + // Test struct extension members + const data3 = { x: 3.0, y: 4.0, label: "Test", optCount: null, optFlag: null }; + assert.equal(exports.DataPoint.distanceFromOrigin(data3), 5.0); + const origin = exports.DataPoint.origin(); + assert.equal(origin.x, 0.0); + assert.equal(origin.y, 0.0); + assert.equal(origin.label, "origin"); + assert.equal(exports.DataPoint.dimensions, 2); + const publicPoint = { x: 9, y: -3 }; assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); From 7dd02633cb57d4dc9b43328e2cef8ab1407ff7aa Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Tue, 10 Mar 2026 22:14:28 +0000 Subject: [PATCH 021/140] BridgeJS: Use shared decodeString for JSTypedClosure error path (#696) --- Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 2 +- .../__Snapshots__/BridgeJSLinkTests/SwiftClosure.js | 2 +- .../__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 93814123c..8c18ced4d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -660,7 +660,7 @@ public struct BridgeJSLink { helperPrinter.write("let length = 0;") helperPrinter.write("while (bytes[length] !== 0) { length += 1; }") helperPrinter.write( - "const fileID = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes.subarray(0, length));" + "const fileID = \(JSGlueVariableScope.reservedDecodeString)(state.file, length);" ) helperPrinter.write( "throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`);" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 09eb39050..a0e874907 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -70,7 +70,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = textDecoder.decode(bytes.subarray(0, length)); + const fileID = decodeString(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 21e382395..42ca68e78 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -40,7 +40,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = textDecoder.decode(bytes.subarray(0, length)); + const fileID = decodeString(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); From 825f6950b2ed32de29764f131c306ec75e82f008 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Wed, 11 Mar 2026 10:58:14 +1100 Subject: [PATCH 022/140] Fix formatting --- .../Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift | 1 - Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 1b1f95f76..dd0ce5d03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -184,7 +184,6 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtension") } - @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) 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() From a93a6869918f5610547caf6d924555f5f17dc32f Mon Sep 17 00:00:00 2001 From: William Taylor Date: Wed, 11 Mar 2026 11:53:04 +1100 Subject: [PATCH 023/140] Update test code to avoid accidentally introduced failure --- .../Inputs/MacroSwift/SwiftStruct.swift | 17 ++- .../BridgeJSCodegenTests/SwiftStruct.json | 87 ++++++++++--- .../BridgeJSCodegenTests/SwiftStruct.swift | 81 ++++++++++-- .../Generated/BridgeJS.swift | 92 ++++++++++++-- .../Generated/JavaScript/BridgeJS.json | 115 +++++++++++++++--- Tests/BridgeJSRuntimeTests/StructAPIs.swift | 24 +++- Tests/prelude.mjs | 11 +- 7 files changed, 361 insertions(+), 66 deletions(-) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 4ec6525e3..63bb0ff8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -61,11 +61,22 @@ @JS func roundtripContainer(_ container: Container) -> Container -extension DataPoint { - @JS func distanceFromOrigin() -> Double { - return (x * x + y * y).squareRoot() +@JS struct Vector2D { + var dx: Double + var dy: Double +} + +extension Vector2D { + @JS func magnitude() -> Double { + return (dx * dx + dy * dy).squareRoot() } + @JS func scaled(by factor: Double) -> Vector2D { + return Vector2D(dx: dx * factor, dy: dy * factor) + } +} + +extension DataPoint { @JS static func origin() -> DataPoint { return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 7a6421668..617124701 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -211,23 +211,6 @@ ] }, "methods" : [ - { - "abiName" : "bjs_DataPoint_distanceFromOrigin", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "distanceFromOrigin", - "parameters" : [ - - ], - "returnType" : { - "double" : { - - } - } - }, { "abiName" : "bjs_DataPoint_static_origin", "effects" : { @@ -635,6 +618,76 @@ } ], "swiftCallName" : "Container" + }, + { + "methods" : [ + { + "abiName" : "bjs_Vector2D_magnitude", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "magnitude", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_Vector2D_scaled", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "scaled", + "parameters" : [ + { + "label" : "by", + "name" : "factor", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + } + ], + "name" : "Vector2D", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Vector2D" } ] }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 5e17b6db2..e4cd409ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -77,17 +77,6 @@ public func _bjs_DataPoint_static_dimensions_get() -> Int32 { #endif } -@_expose(wasm, "bjs_DataPoint_distanceFromOrigin") -@_cdecl("bjs_DataPoint_distanceFromOrigin") -public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { - #if arch(wasm32) - let ret = DataPoint.bridgeJSLiftParameter().distanceFromOrigin() - 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 { @@ -466,6 +455,76 @@ fileprivate func _bjs_struct_lift_Container_extern() -> Int32 { return _bjs_struct_lift_Container_extern() } +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_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 +} + +@_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 +} + @_expose(wasm, "bjs_roundtrip") @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index cde1afc59..c85dec679 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4266,17 +4266,6 @@ public func _bjs_DataPoint_static_dimensions_get() -> Int32 { #endif } -@_expose(wasm, "bjs_DataPoint_distanceFromOrigin") -@_cdecl("bjs_DataPoint_distanceFromOrigin") -public func _bjs_DataPoint_distanceFromOrigin() -> Float64 { - #if arch(wasm32) - let ret = DataPoint.bridgeJSLiftParameter().distanceFromOrigin() - 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 { @@ -5089,6 +5078,87 @@ public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { #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 { + #if arch(wasm32) + let ret = Vector2D(dx: Double.bridgeJSLiftParameter(dx), dy: Double.bridgeJSLiftParameter(dy)) + 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 { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().magnitude() + 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 { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + 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 137fb6087..14cdc5dee 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -13450,23 +13450,6 @@ ] }, "methods" : [ - { - "abiName" : "bjs_DataPoint_distanceFromOrigin", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "distanceFromOrigin", - "parameters" : [ - - ], - "returnType" : { - "double" : { - - } - } - }, { "abiName" : "bjs_DataPoint_static_origin", "effects" : { @@ -14500,6 +14483,104 @@ ], "swiftCallName" : "ConfigStruct" }, + { + "constructor" : { + "abiName" : "bjs_Vector2D_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "dx", + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "label" : "dy", + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Vector2D_magnitude", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "magnitude", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_Vector2D_scaled", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "scaled", + "parameters" : [ + { + "label" : "by", + "name" : "factor", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + } + ], + "name" : "Vector2D", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Vector2D" + }, { "methods" : [ diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index af925cb77..daa7ad1e2 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -175,10 +175,6 @@ import JavaScriptKit } extension DataPoint { - @JS func distanceFromOrigin() -> Double { - return (x * x + y * y).squareRoot() - } - @JS static func origin() -> DataPoint { return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) } @@ -186,6 +182,26 @@ extension DataPoint { @JS static var dimensions: Int { 2 } } +@JS struct Vector2D { + var dx: Double + var dy: Double + + @JS init(dx: Double, dy: Double) { + self.dx = dx + self.dy = dy + } +} + +extension Vector2D { + @JS func magnitude() -> Double { + return (dx * dx + dy * dy).squareRoot() + } + + @JS func scaled(by factor: Double) -> Vector2D { + return Vector2D(dx: dx * factor, dy: dy * factor) + } +} + @JS func roundTripDataPoint(_ data: DataPoint) -> DataPoint { return data } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 94d33057d..c5da33196 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -789,15 +789,20 @@ function testStructSupport(exports) { const data2 = { x: 0.0, y: 0.0, label: "", optCount: null, optFlag: null }; assert.deepEqual(exports.roundTripDataPoint(data2), data2); - // Test struct extension members - const data3 = { x: 3.0, y: 4.0, label: "Test", optCount: null, optFlag: null }; - assert.equal(exports.DataPoint.distanceFromOrigin(data3), 5.0); + // Test struct extension static members const origin = exports.DataPoint.origin(); assert.equal(origin.x, 0.0); assert.equal(origin.y, 0.0); assert.equal(origin.label, "origin"); assert.equal(exports.DataPoint.dimensions, 2); + // Test struct extension instance methods + const vec = new exports.Vector2D(3.0, 4.0); + assert.equal(vec.magnitude(), 5.0); + const scaled = vec.scaled(2.0); + assert.equal(scaled.dx, 6.0); + assert.equal(scaled.dy, 8.0); + const publicPoint = { x: 9, y: -3 }; assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); From e7b842716fc2382d3f8e4283d0d8a4acbf198af7 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 10 Mar 2026 16:40:28 +0100 Subject: [PATCH 024/140] BridgeJS: Fix protocol existential lowering in Swift-to-JS direction --- Benchmarks/Sources/Generated/BridgeJS.swift | 45 +++- .../PlayBridgeJS/Generated/BridgeJS.swift | 5 +- .../Sources/BridgeJSCore/ExportSwift.swift | 68 +++++- .../BridgeJSCodegenTests/ArrayTypes.swift | 10 +- .../CrossFileFunctionTypes.ReverseOrder.swift | 10 +- .../CrossFileFunctionTypes.swift | 10 +- ...CrossFileTypeResolution.ReverseOrder.swift | 10 +- .../CrossFileTypeResolution.swift | 10 +- .../DefaultParameters.swift | 15 +- .../DictionaryTypes.swift | 5 +- .../EnumAssociatedValue.swift | 5 +- .../EnumNamespace.Global.swift | 20 +- .../BridgeJSCodegenTests/EnumNamespace.swift | 20 +- .../BridgeJSCodegenTests/JSValue.swift | 5 +- .../BridgeJSCodegenTests/MixedGlobal.swift | 5 +- .../BridgeJSCodegenTests/MixedPrivate.swift | 5 +- .../Namespaces.Global.swift | 20 +- .../BridgeJSCodegenTests/Namespaces.swift | 20 +- .../BridgeJSCodegenTests/Optionals.swift | 10 +- .../BridgeJSCodegenTests/PropertyTypes.swift | 5 +- .../BridgeJSCodegenTests/Protocol.swift | 35 ++- .../StaticFunctions.Global.swift | 5 +- .../StaticFunctions.swift | 5 +- .../StaticProperties.Global.swift | 5 +- .../StaticProperties.swift | 5 +- .../BridgeJSCodegenTests/SwiftClass.swift | 15 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 10 +- .../BridgeJSCodegenTests/SwiftStruct.swift | 5 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 19 +- .../Generated/BridgeJS.swift | 15 +- .../BridgeJSRuntimeTests/ExportAPITests.swift | 30 +++ .../Generated/BridgeJS.swift | 225 +++++++++++++++--- .../Generated/JavaScript/BridgeJS.json | 137 +++++++++++ Tests/prelude.mjs | 34 +++ 34 files changed, 740 insertions(+), 108 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 7b7c6e690..c9adb2b1a 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -491,10 +491,13 @@ public func _bjs_EnumRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension EnumRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension EnumRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_EnumRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_EnumRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -628,10 +631,13 @@ public func _bjs_ComplexResultRoundtrip_deinit(_ pointer: UnsafeMutableRawPointe #endif } -extension ComplexResultRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ComplexResultRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ComplexResultRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ComplexResultRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -688,10 +694,13 @@ public func _bjs_StringRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension StringRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension StringRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_StringRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_StringRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -815,10 +824,13 @@ public func _bjs_OptionalReturnRoundtrip_deinit(_ pointer: UnsafeMutableRawPoint #endif } -extension OptionalReturnRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension OptionalReturnRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalReturnRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_OptionalReturnRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -982,10 +994,13 @@ public func _bjs_StructRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension StructRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension StructRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_StructRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_StructRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -1126,10 +1141,13 @@ public func _bjs_SimpleClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void #endif } -extension SimpleClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension SimpleClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_SimpleClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_SimpleClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -1228,10 +1246,13 @@ public func _bjs_AddressClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void #endif } -extension AddressClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension AddressClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_AddressClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_AddressClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -1331,10 +1352,13 @@ public func _bjs_ClassRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension ClassRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClassRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -1691,10 +1715,13 @@ public func _bjs_ArrayRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension ArrayRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ArrayRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ArrayRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ArrayRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index f1baf3aa1..056c1c27d 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -209,10 +209,13 @@ public func _bjs_PlayBridgeJS_deinit(_ pointer: UnsafeMutableRawPointer) -> Void #endif } -extension PlayBridgeJS: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension PlayBridgeJS: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_PlayBridgeJS_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PlayBridgeJS_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index dbe4a1312..8ccbbee76 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -167,12 +167,7 @@ public class ExportSwift { private func protocolCastSuffix(for returnType: BridgeType) -> (prefix: String, suffix: String) { switch returnType { case .swiftProtocol: - return ("", " as! \(returnType.swiftType)") - case .nullable(let wrappedType, _): - if case .swiftProtocol = wrappedType { - return ("(", ").flatMap { $0 as? \(wrappedType.swiftType) }") - } - return ("", "") + return ("", " as! _BridgedSwiftProtocolExportable") default: return ("", "") } @@ -311,6 +306,23 @@ public class ExportSwift { 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: "ret", varPrefix: "ret") { + append(stmt) + } + case .swiftProtocol: + append("return ret.bridgeJSLowerAsProtocolReturn()") + case .nullable(.swiftProtocol, _): + append( + """ + if let ret { + _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } else { + _swift_js_return_optional_object(0, 0) + } + """ + ) default: append("return ret.bridgeJSLowerReturn()") } @@ -703,10 +715,13 @@ public class ExportSwift { // If the class has an explicit access control, we need to add it to the extension declaration. let accessControl = klass.explicitAccessControl.map { "\($0) " } ?? "" let extensionDecl: DeclSyntax = """ - extension \(raw: klass.swiftCallName): ConvertibleToJSValue, _BridgedSwiftHeapObject { + extension \(raw: klass.swiftCallName): ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { \(raw: accessControl)var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: \(raw: wrapFunctionName)(Unmanaged.passRetained(self).toOpaque())))) } + \(raw: accessControl)consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + \(raw: wrapFunctionName)(Unmanaged.passRetained(self).toOpaque()) + } } """ // Build common function signature @@ -781,7 +796,9 @@ struct StackCodegen { case .jsObject(_?): return ["\(raw: accessor).jsObject.bridgeJSStackPush()"] case .swiftProtocol: - return ["(\(raw: accessor) as! \(raw: type.swiftType)).bridgeJSStackPush()"] + return [ + "_swift_js_push_i32((\(raw: accessor) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + ] case .void, .namespaceEnum: return [] case .array(let elementType): @@ -798,7 +815,7 @@ struct StackCodegen { ) -> [CodeBlockItemSyntax] { switch elementType { case .swiftProtocol: - return ["\(raw: accessor).map { $0 as! \(raw: elementType.swiftType) }.bridgeJSStackPush()"] + return lowerProtocolArrayStatements(accessor: accessor, varPrefix: varPrefix) case .void, .namespaceEnum: fatalError("Invalid array element type: \(elementType)") default: @@ -806,6 +823,21 @@ struct StackCodegen { } } + private func lowerProtocolArrayStatements( + accessor: String, + varPrefix: String + ) -> [CodeBlockItemSyntax] { + var statements: [CodeBlockItemSyntax] = [] + let elemVar = "__bjs_elem_\(varPrefix)" + statements.append("for \(raw: elemVar) in \(raw: accessor) {") + statements.append( + " _swift_js_push_i32((\(raw: elemVar) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + ) + statements.append("}") + statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") + return statements + } + private func lowerDictionaryStatements( valueType: BridgeType, accessor: String, @@ -815,7 +847,7 @@ struct StackCodegen { case .jsObject(let className?) where className != "JSObject": return ["\(raw: accessor).mapValues { $0.jsObject }.bridgeJSStackPush()"] case .swiftProtocol: - return ["\(raw: accessor).mapValues { $0 as! \(raw: valueType.swiftType) }.bridgeJSStackPush()"] + return lowerProtocolDictionaryStatements(accessor: accessor, varPrefix: varPrefix) case .nullable, .closure: return lowerDictionaryStatementsInline( valueType: valueType, @@ -862,6 +894,22 @@ struct StackCodegen { statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") return statements } + + private func lowerProtocolDictionaryStatements( + accessor: String, + varPrefix: String + ) -> [CodeBlockItemSyntax] { + var statements: [CodeBlockItemSyntax] = [] + let pairVar = "__bjs_kv_\(varPrefix)" + statements.append("for \(raw: pairVar) in \(raw: accessor) {") + statements.append(" \(raw: pairVar).key.bridgeJSStackPush()") + statements.append( + " _swift_js_push_i32((\(raw: pairVar).value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + ) + statements.append("}") + statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") + return statements + } } // MARK: - EnumCodegen diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index 0d95a5b7f..cf65635d9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -414,10 +414,13 @@ public func _bjs_Item_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Item: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Item: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Item_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Item_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -477,10 +480,13 @@ public func _bjs_MultiArrayContainer_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension MultiArrayContainer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension MultiArrayContainer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_MultiArrayContainer_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_MultiArrayContainer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift index 4dda325bf..d12d48eef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift @@ -52,10 +52,13 @@ public func _bjs_FunctionA_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_FunctionA_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_FunctionA_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -112,10 +115,13 @@ public func _bjs_FunctionB_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_FunctionB_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_FunctionB_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift index fcf84a88f..bf720af76 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift @@ -51,10 +51,13 @@ public func _bjs_FunctionB_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_FunctionB_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_FunctionB_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -112,10 +115,13 @@ public func _bjs_FunctionA_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_FunctionA_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_FunctionA_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift index 2868156a4..7c43c393f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift @@ -29,10 +29,13 @@ public func _bjs_ClassA_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassA_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassA_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -68,10 +71,13 @@ public func _bjs_ClassB_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassB_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassB_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift index 09070a16f..c381c7cab 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift @@ -19,10 +19,13 @@ public func _bjs_ClassB_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassB_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassB_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -68,10 +71,13 @@ public func _bjs_ClassA_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassA_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassA_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index df4969fa6..4c527315b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -428,10 +428,13 @@ public func _bjs_DefaultGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension DefaultGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension DefaultGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_DefaultGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_DefaultGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -467,10 +470,13 @@ public func _bjs_EmptyGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void #endif } -extension EmptyGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension EmptyGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_EmptyGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_EmptyGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -611,10 +617,13 @@ public func _bjs_ConstructorDefaults_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension ConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index 742619f39..dc0a54bcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -63,10 +63,13 @@ public func _bjs_Box_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Box: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Box: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Box_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Box_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index fc3a18453..1112fb5a4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -612,10 +612,13 @@ public func _bjs_User_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension User: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension User: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_User_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_User_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index d4dfa57a9..1a8608246 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -182,10 +182,13 @@ public func _bjs_Utils_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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()) + } } #if arch(wasm32) @@ -231,10 +234,13 @@ public func _bjs_Networking_API_HTTPServer_deinit(_ pointer: UnsafeMutableRawPoi #endif } -extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -280,10 +286,13 @@ public func _bjs_Networking_APIV2_Internal_TestServer_deinit(_ pointer: UnsafeMu #endif } -extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -330,10 +339,13 @@ public func _bjs_Formatting_Converter_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index d4dfa57a9..1a8608246 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -182,10 +182,13 @@ public func _bjs_Utils_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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()) + } } #if arch(wasm32) @@ -231,10 +234,13 @@ public func _bjs_Networking_API_HTTPServer_deinit(_ pointer: UnsafeMutableRawPoi #endif } -extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -280,10 +286,13 @@ public func _bjs_Networking_APIV2_Internal_TestServer_deinit(_ pointer: UnsafeMu #endif } -extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -330,10 +339,13 @@ public func _bjs_Formatting_Converter_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Formatting.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Formatting_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift index ba7fee7af..1ce288202 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift @@ -137,10 +137,13 @@ public func _bjs_JSValueHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension JSValueHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension JSValueHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_JSValueHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_JSValueHolder_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift index 802a09638..feaa7012c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift @@ -41,10 +41,13 @@ public func _bjs_GlobalAPI_GlobalClass_deinit(_ pointer: UnsafeMutableRawPointer #endif } -extension GlobalClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension GlobalClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalAPI_GlobalClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GlobalAPI_GlobalClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift index 50dc9e778..184096f29 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift @@ -41,10 +41,13 @@ public func _bjs_PrivateAPI_PrivateClass_deinit(_ pointer: UnsafeMutableRawPoint #endif } -extension PrivateClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension PrivateClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_PrivateAPI_PrivateClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PrivateAPI_PrivateClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index d376a2a54..86f0b8478 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -52,10 +52,13 @@ public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPo #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs___Swift_Foundation_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -102,10 +105,13 @@ public func _bjs_Utils_Converters_Converter_deinit(_ pointer: UnsafeMutableRawPo #endif } -extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -141,10 +147,13 @@ public func _bjs___Swift_Foundation_UUID_deinit(_ pointer: UnsafeMutableRawPoint #endif } -extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -201,10 +210,13 @@ public func _bjs_Collections_Container_deinit(_ pointer: UnsafeMutableRawPointer #endif } -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index d376a2a54..86f0b8478 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -52,10 +52,13 @@ public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPo #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs___Swift_Foundation_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -102,10 +105,13 @@ public func _bjs_Utils_Converters_Converter_deinit(_ pointer: UnsafeMutableRawPo #endif } -extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Utils_Converters_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -141,10 +147,13 @@ public func _bjs___Swift_Foundation_UUID_deinit(_ pointer: UnsafeMutableRawPoint #endif } -extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -201,10 +210,13 @@ public func _bjs_Collections_Container_deinit(_ pointer: UnsafeMutableRawPointer #endif } -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Collections_Container_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index ca1078836..8207bd488 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -226,10 +226,13 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -328,10 +331,13 @@ public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointe #endif } -extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift index de59f5166..1c7c8350f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift @@ -328,10 +328,13 @@ public func _bjs_PropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index d9cd22836..cf7464cc3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -697,7 +697,9 @@ extension Priority: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { public func _bjs_processDelegates() -> Void { #if arch(wasm32) let ret = processDelegates(_: [AnyMyViewControllerDelegate].bridgeJSStackPop()) - ret.map { $0 as! AnyMyViewControllerDelegate }.bridgeJSStackPush() + 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 @@ -755,10 +757,13 @@ public func _bjs_Helper_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Helper: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Helper: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Helper_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Helper_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -850,8 +855,8 @@ public func _bjs_MyViewController_sendHelper(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_MyViewController_delegate_get") public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).delegate as! AnyMyViewControllerDelegate - return ret.bridgeJSLowerReturn() + let ret = MyViewController.bridgeJSLiftParameter(_self).delegate as! _BridgedSwiftProtocolExportable + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -871,8 +876,12 @@ public func _bjs_MyViewController_delegate_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_secondDelegate_get") public func _bjs_MyViewController_secondDelegate_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = (MyViewController.bridgeJSLiftParameter(_self).secondDelegate).flatMap { $0 as? AnyMyViewControllerDelegate } - return ret.bridgeJSLowerReturn() + let ret = MyViewController.bridgeJSLiftParameter(_self).secondDelegate + 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 @@ -898,10 +907,13 @@ public func _bjs_MyViewController_deinit(_ pointer: UnsafeMutableRawPointer) -> #endif } -extension MyViewController: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension MyViewController: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_MyViewController_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_MyViewController_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -942,7 +954,9 @@ public func _bjs_DelegateManager_notifyAll(_ _self: UnsafeMutableRawPointer) -> public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = DelegateManager.bridgeJSLiftParameter(_self).delegates - ret.map { $0 as! AnyMyViewControllerDelegate }.bridgeJSStackPush() + 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 @@ -968,10 +982,13 @@ public func _bjs_DelegateManager_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension DelegateManager: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension DelegateManager: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_DelegateManager_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_DelegateManager_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index b6d35a215..60d7fa83c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -144,10 +144,13 @@ public func _bjs_MathUtils_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index b6d35a215..60d7fa83c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -144,10 +144,13 @@ public func _bjs_MathUtils_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index 43b1861ca..faec8821b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -319,10 +319,13 @@ public func _bjs_PropertyClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_PropertyClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PropertyClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index 43b1861ca..faec8821b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -319,10 +319,13 @@ public func _bjs_PropertyClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_PropertyClass_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PropertyClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index 0e9434832..aab0eb308 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -71,10 +71,13 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -99,10 +102,13 @@ public func _bjs_PublicGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -127,10 +133,13 @@ public func _bjs_PackageGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index e2cf9e09b..472987fee 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -1610,10 +1610,13 @@ public func _bjs_Person_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Person: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Person: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { public var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Person_wrap(Unmanaged.passRetained(self).toOpaque())))) } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Person_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -1649,10 +1652,13 @@ public func _bjs_TestProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension TestProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension TestProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_TestProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TestProcessor_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 6fccb3280..236937db9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -508,10 +508,13 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index f2b2b6c34..9ef28f844 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -567,7 +567,7 @@ extension _JSBridgedClass { /// A protocol that Swift protocol wrappers exposed from JavaScript must conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftProtocolWrapper: _BridgedSwiftStackType { +public protocol _BridgedSwiftProtocolWrapper: _BridgedSwiftStackType, _BridgedSwiftProtocolExportable { var jsObject: JSObject { get } static func bridgeJSLiftParameter(_ value: Int32) -> Self } @@ -595,6 +595,21 @@ extension _BridgedSwiftProtocolWrapper { } } +/// A protocol that allows any BridgeJS-exported type to be lowered to a JSObject ID +/// for protocol existential bridging in the Swift-to-JS direction. +/// +/// Both `_BridgedSwiftProtocolWrapper` (JS-originated protocol objects) and `@JS class` +/// types conform to this, enabling runtime dispatch when a protocol existential is returned. +public protocol _BridgedSwiftProtocolExportable { + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 +} + +extension _BridgedSwiftProtocolExportable where Self: _BridgedSwiftProtocolWrapper { + @_spi(BridgeJS) public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + jsObject.bridgeJSLowerReturn() + } +} + /// A protocol that Swift enum types that do not have a payload can conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. @@ -1023,7 +1038,7 @@ private func _swift_js_return_optional_object_extern(_ isSome: Int32, _ objectId _onlyAvailableOnWasm() } #endif -@inline(never) func _swift_js_return_optional_object(_ isSome: Int32, _ objectId: Int32) { +@_spi(BridgeJS) @inline(never) public func _swift_js_return_optional_object(_ isSome: Int32, _ objectId: Int32) { _swift_js_return_optional_object_extern(isSome, objectId) } diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index a892720ce..7816681da 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -207,10 +207,13 @@ public func _bjs_GlobalNetworking_API_TestHTTPServer_deinit(_ pointer: UnsafeMut #endif } -extension GlobalNetworking.API.TestHTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension GlobalNetworking.API.TestHTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalNetworking_API_TestHTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GlobalNetworking_API_TestHTTPServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -256,10 +259,13 @@ public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_deinit(_ poi #endif } -extension Internal.TestInternalServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Internal.TestInternalServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -327,10 +333,13 @@ public func _bjs_GlobalUtils_PublicConverter_deinit(_ pointer: UnsafeMutableRawP #endif } -extension GlobalUtils.PublicConverter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension GlobalUtils.PublicConverter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_GlobalUtils_PublicConverter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GlobalUtils_PublicConverter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c8ebbc8ce..6407a175b 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1026,6 +1026,36 @@ enum GraphOperations { } } +@JS class ProtocolReturnTests { + @JS static func createNativeProcessor() -> DataProcessor { + return SwiftDataProcessor() + } + + @JS static func createNativeProcessorOptional() -> DataProcessor? { + return SwiftDataProcessor() + } + + @JS static func createNativeProcessorNil() -> DataProcessor? { + return nil + } + + @JS static func createNativeProcessorArray() -> [DataProcessor] { + let p1 = SwiftDataProcessor() + p1.count = 10 + let p2 = SwiftDataProcessor() + p2.count = 20 + return [p1, p2] + } + + @JS static func createNativeProcessorDictionary() -> [String: DataProcessor] { + let p1 = SwiftDataProcessor() + p1.count = 10 + let p2 = SwiftDataProcessor() + p2.count = 20 + return ["first": p1, "second": p2] + } +} + // MARK: - Closure Tests // @JS func makeFormatter(prefix: String) -> (String) -> String { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 13aab1455..db3132c37 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -2467,7 +2467,9 @@ public func _bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray() public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { #if arch(wasm32) let ret = ArraySupportExports.roundTripProtocolArray(_: [AnyArrayElementProtocol].bridgeJSStackPop()) - ret.map { $0 as! AnyArrayElementProtocol }.bridgeJSStackPush() + 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 @@ -6685,10 +6687,13 @@ public func _bjs_ClosureSupportExports_deinit(_ pointer: UnsafeMutableRawPointer #endif } -extension ClosureSupportExports: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension ClosureSupportExports: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -6840,10 +6845,13 @@ public func _bjs_DefaultArgumentConstructorDefaults_deinit(_ pointer: UnsafeMuta #endif } -extension DefaultArgumentConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension DefaultArgumentConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -6976,10 +6984,13 @@ public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { public var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -7026,10 +7037,13 @@ public func _bjs_Calculator_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Calculator: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7054,10 +7068,13 @@ public func _bjs_InternalGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension InternalGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7082,10 +7099,13 @@ public func _bjs_PublicGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7110,10 +7130,13 @@ public func _bjs_PackageGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7181,10 +7204,13 @@ public func _bjs_Utils_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> V #endif } -extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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()) + } } #if arch(wasm32) @@ -7230,10 +7256,13 @@ public func _bjs_Networking_API_HTTPServer_deinit(_ pointer: UnsafeMutableRawPoi #endif } -extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7280,10 +7309,13 @@ public func _bjs___Swift_Foundation_UUID_deinit(_ pointer: UnsafeMutableRawPoint #endif } -extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7329,10 +7361,13 @@ public func _bjs_Networking_APIV2_Internal_TestServer_deinit(_ pointer: UnsafeMu #endif } -extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -7389,10 +7424,13 @@ public func _bjs_SimplePropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension SimplePropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +extension SimplePropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { return .object(JSObject(id: UInt32(bitPattern: _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) + } } #if arch(wasm32) @@ -7715,10 +7753,13 @@ public func _bjs_PropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -7765,10 +7806,13 @@ public func _bjs_MathUtils_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -8015,10 +8059,13 @@ public func _bjs_StaticPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension StaticPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -8259,8 +8306,8 @@ public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_processor_get") public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).processor as! AnyDataProcessor - return ret.bridgeJSLowerReturn() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).processor as! _BridgedSwiftProtocolExportable + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8280,8 +8327,12 @@ public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_DataProcessorManager_backupProcessor_get") public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = (DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor).flatMap { $0 as? AnyDataProcessor } - 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 @@ -8307,10 +8358,13 @@ public func _bjs_DataProcessorManager_deinit(_ pointer: UnsafeMutableRawPointer) #endif } -extension DataProcessorManager: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -8664,10 +8718,13 @@ public func _bjs_SwiftDataProcessor_deinit(_ pointer: UnsafeMutableRawPointer) - #endif } -extension SwiftDataProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -8682,6 +8739,105 @@ fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRaw 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_ProtocolReturnTests_static_createNativeProcessorOptional") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorOptional") +public func _bjs_ProtocolReturnTests_static_createNativeProcessorOptional() -> 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) + } + #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 { + #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) + } + #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 { + #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) + 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_ProtocolReturnTests_deinit") +@_cdecl("bjs_ProtocolReturnTests_deinit") +public func _bjs_ProtocolReturnTests_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ProtocolReturnTests: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ProtocolReturnTests_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ProtocolReturnTests_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 +#else +fileprivate func _bjs_ProtocolReturnTests_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) +} + @_expose(wasm, "bjs_TextProcessor_init") @_cdecl("bjs_TextProcessor_init") public func _bjs_TextProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { @@ -8923,10 +9079,13 @@ public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Voi #endif } -extension TextProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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()) + } } #if arch(wasm32) @@ -9004,10 +9163,13 @@ public func _bjs_OptionalHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Vo #endif } -extension OptionalHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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()) + } } #if arch(wasm32) @@ -9106,10 +9268,13 @@ public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointe #endif } -extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -9189,10 +9354,13 @@ public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) @@ -9228,10 +9396,13 @@ public func _bjs_LeakCheck_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #endif } -extension LeakCheck: ConvertibleToJSValue, _BridgedSwiftHeapObject { +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) diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 746e0cd3c..da05bc5ae 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -2577,6 +2577,143 @@ ], "swiftCallName" : "SwiftDataProcessor" }, + { + "methods" : [ + { + "abiName" : "bjs_ProtocolReturnTests_static_createNativeProcessor", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createNativeProcessor", + "parameters" : [ + + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + }, + "staticContext" : { + "className" : { + "_0" : "ProtocolReturnTests" + } + } + }, + { + "abiName" : "bjs_ProtocolReturnTests_static_createNativeProcessorOptional", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createNativeProcessorOptional", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "className" : { + "_0" : "ProtocolReturnTests" + } + } + }, + { + "abiName" : "bjs_ProtocolReturnTests_static_createNativeProcessorNil", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createNativeProcessorNil", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "className" : { + "_0" : "ProtocolReturnTests" + } + } + }, + { + "abiName" : "bjs_ProtocolReturnTests_static_createNativeProcessorArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createNativeProcessorArray", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "ProtocolReturnTests" + } + } + }, + { + "abiName" : "bjs_ProtocolReturnTests_static_createNativeProcessorDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createNativeProcessorDictionary", + "parameters" : [ + + ], + "returnType" : { + "dictionary" : { + "_0" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "ProtocolReturnTests" + } + } + } + ], + "name" : "ProtocolReturnTests", + "properties" : [ + + ], + "swiftCallName" : "ProtocolReturnTests" + }, { "constructor" : { "abiName" : "bjs_TextProcessor_init", diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 4c211e91c..ca2da4324 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -1409,4 +1409,38 @@ function testProtocolSupport(exports) { managerWithOptional.release(); swiftBackup.release(); + + const nativeProcessor = exports.ProtocolReturnTests.createNativeProcessor(); + assert.notEqual(nativeProcessor, undefined, "createNativeProcessor should return a value"); + assert.equal(typeof nativeProcessor.increment, "function", "should have increment method"); + nativeProcessor.increment(1); + assert.equal(nativeProcessor.count, 1, "count should be 1 after increment"); + nativeProcessor.release(); + + const optProcessor = exports.ProtocolReturnTests.createNativeProcessorOptional(); + assert.notEqual(optProcessor, null, "optional processor should not be null"); + optProcessor.increment(1); + assert.equal(optProcessor.count, 1, "optional processor count should be 1 after increment"); + optProcessor.release(); + + const nilProcessor = exports.ProtocolReturnTests.createNativeProcessorNil(); + assert.equal(nilProcessor, null, "nil processor should be null"); + + const nativeArray = exports.ProtocolReturnTests.createNativeProcessorArray(); + assert.equal(nativeArray.length, 2, "array should have 2 elements"); + assert.equal(nativeArray[0].count, 10, "first element count should be 10"); + assert.equal(nativeArray[1].count, 20, "second element count should be 20"); + nativeArray[0].increment(1); + assert.equal(nativeArray[0].count, 11, "first element count should be 11 after increment"); + nativeArray[0].release(); + nativeArray[1].release(); + + const nativeDict = exports.ProtocolReturnTests.createNativeProcessorDictionary(); + assert.notEqual(nativeDict, undefined, "dictionary should not be undefined"); + assert.equal(nativeDict["first"].count, 10, "first entry count should be 10"); + assert.equal(nativeDict["second"].count, 20, "second entry count should be 20"); + nativeDict["first"].increment(5); + assert.equal(nativeDict["first"].count, 15, "first entry count should be 15 after increment"); + nativeDict["first"].release(); + nativeDict["second"].release(); } From 4c1c32caa352f512142ef62b1015d506acf726fb Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 11 Mar 2026 19:52:52 +0800 Subject: [PATCH 025/140] Fix CI: update snapshots, formatting, runtime test, add docs and review feedback --- .../BridgeJSCore/SwiftToSkeleton.swift | 14 +++++- .../BridgeJSLinkTests/SwiftStruct.d.ts | 7 ++- .../BridgeJSLinkTests/SwiftStruct.js | 41 +++++++++++++--- .../Exporting-Swift/Exporting-Swift-Class.md | 48 +++++++++++++++++++ .../Exporting-Swift/Exporting-Swift-Enum.md | 1 + .../Exporting-Swift/Exporting-Swift-Struct.md | 1 + .../JSClosure+AsyncTests.swift | 6 +-- Tests/prelude.mjs | 2 +- 8 files changed, 107 insertions(+), 13 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 2ff5cecba..a28192d4b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1425,7 +1425,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } - /// Walks extension members under the matching type’s state, returning whether the type was 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 + /// 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 let state: State @@ -1435,6 +1440,13 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { 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 }) { + diagnose( + node: ext.extendedType, + message: "Protocol extensions are not supported by BridgeJS.", + hint: "You cannot extend `@JS` protocol '\(name)' with additional members" + ) + return true } else { return false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 211661d5f..bf4ebc71f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -16,7 +16,6 @@ export interface DataPoint { label: string; optCount: number | null; optFlag: boolean | null; - distanceFromOrigin(): number; } export interface Address { street: string; @@ -44,6 +43,12 @@ export interface Container { object: any; optionalObject: any | null; } +export interface Vector2D { + dx: number; + dy: number; + magnitude(): number; + scaled(factor: number): Vector2D; +} export type PrecisionObject = typeof PrecisionValues; /// Represents a Swift heap object like a class instance or an actor instance. diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 099f4ccc3..b9889f156 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -73,13 +73,7 @@ export async function createInstantiator(options, swift) { const string = strStack.pop(); const f64 = f64Stack.pop(); const f641 = f64Stack.pop(); - const instance1 = { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; - instance1.distanceFromOrigin = function() { - structHelpers.DataPoint.lower(this); - const ret = instance.exports.bjs_DataPoint_distanceFromOrigin(); - return ret; - }.bind(instance1); - return instance1; + return { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; } }); const __bjs_createAddressHelpers = () => ({ @@ -225,6 +219,29 @@ export async function createInstantiator(options, swift) { return { object: value, optionalObject: optValue }; } }); + const __bjs_createVector2DHelpers = () => ({ + 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.Vector2D.lower(this); + const ret = instance.exports.bjs_Vector2D_magnitude(); + return ret; + }.bind(instance1); + instance1.scaled = function(factor) { + structHelpers.Vector2D.lower(this); + const ret = instance.exports.bjs_Vector2D_scaled(factor); + const structValue = structHelpers.Vector2D.lift(); + return structValue; + }.bind(instance1); + return instance1; + } + }); return { /** @@ -336,6 +353,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Container.lift(); return swift.memory.retain(value); } + bjs["swift_js_struct_lower_Vector2D"] = function(objectId) { + structHelpers.Vector2D.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Vector2D"] = function() { + const value = structHelpers.Vector2D.lift(); + return swift.memory.retain(value); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -527,6 +551,9 @@ export async function createInstantiator(options, swift) { const ContainerHelpers = __bjs_createContainerHelpers(); structHelpers.Container = ContainerHelpers; + const Vector2DHelpers = __bjs_createVector2DHelpers(); + structHelpers.Vector2D = Vector2DHelpers; + const exports = { Greeter, roundtrip: function bjs_roundtrip(session) { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md index 9cd4a2224..a16c81286 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -77,6 +77,53 @@ export type Exports = { } ``` +## Adding Members via Extensions + +You can add exported methods, computed properties, and static members to a `@JS` class using extensions. The extension block itself does not need `@JS` - only the individual members do: + +```swift +@JS class Greeter { + @JS var name: String + + @JS init(name: String) { + self.name = name + } + + @JS func greet() -> String { + return "Hello, " + self.name + "!" + } +} + +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, " + self.name + "!!!" + } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } +} +``` + +This also works across files within the same module: + +```swift +// GreeterExtension.swift +extension Greeter { + @JS func greetFormally() -> String { + return "Good day, " + self.name + "." + } +} +``` + +All `@JS`-annotated members in extensions are merged into the same generated TypeScript interface as the original class declaration. + +> Note: Extensions must target `@JS`-annotated types from the same module. + ## How It Works Classes use **reference semantics** when crossing the Swift/JavaScript boundary: @@ -103,5 +150,6 @@ This differs from structs, which use copy semantics and transfer data by value. | Static / class properties: `static var`, `class let` | ✅ (See )| | Methods: `func` | ✅ (See ) | | Static/class methods: `static func`, `class func` | ✅ (See ) | +| Extension methods/properties | ✅ | | Subscripts: `subscript()` | ❌ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md index 2220d457c..68996b27b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md @@ -514,4 +514,5 @@ This differs from classes, which use reference semantics and share state across | Associated values: `JSObject` | ✅ | | Associated values: Arrays | ✅ | | Associated values: Optionals of all supported types | ✅ | +| Extension static functions/properties | ✅ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md index 32bb79ed3..c4a9524d9 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md @@ -165,6 +165,7 @@ This differs from classes, which use reference semantics and share state across | Instance methods | ✅ | | Static methods | ✅ | | Static properties | ✅ | +| Extension methods/properties | ✅ | | Property observers (`willSet`, `didSet`) | ❌ | | Generics | ❌ | | Conformances | ❌ | diff --git a/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift b/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift index e3c19a8e4..db093e549 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/prelude.mjs b/Tests/prelude.mjs index c5da33196..bed4ac02f 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -797,7 +797,7 @@ function testStructSupport(exports) { assert.equal(exports.DataPoint.dimensions, 2); // Test struct extension instance methods - const vec = new exports.Vector2D(3.0, 4.0); + const vec = exports.Vector2D.init(3.0, 4.0); assert.equal(vec.magnitude(), 5.0); const scaled = vec.scaled(2.0); assert.equal(scaled.dx, 6.0); From 3398ff7f622b0e5326e4eb5bdd05dfac24b8a014 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 11 Mar 2026 22:06:03 +0800 Subject: [PATCH 026/140] BridgeJS: Support protocol types in closure parameters and returns --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 25 +- .../Sources/BridgeJSCore/ExportSwift.swift | 10 + .../Sources/BridgeJSCore/ImportTS.swift | 36 +- .../Inputs/MacroSwift/ProtocolInClosure.swift | 18 + .../ProtocolInClosure.json | 281 +++++++++++ .../ProtocolInClosure.swift | 388 ++++++++++++++++ .../BridgeJSLinkTests/ProtocolInClosure.d.ts | 38 ++ .../BridgeJSLinkTests/ProtocolInClosure.js | 436 ++++++++++++++++++ .../JavaScriptKit/BridgeJSIntrinsics.swift | 4 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 28 ++ .../Generated/BridgeJS.swift | 300 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 183 ++++++++ .../JavaScript/ClosureSupportTests.mjs | 126 +++-- 13 files changed, 1841 insertions(+), 32 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index e5648ccf7..142050f56 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -12,9 +12,9 @@ public struct ClosureCodegen { public init() {} private func swiftClosureType(for signature: ClosureSignature) -> String { - let closureParams = signature.parameters.map { "\($0.swiftType)" }.joined(separator: ", ") + let closureParams = signature.parameters.map { "\($0.closureSwiftType)" }.joined(separator: ", ") let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") - let swiftReturnType = signature.returnType.swiftType + let swiftReturnType = signature.returnType.closureSwiftType return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" } @@ -158,7 +158,26 @@ public struct ClosureCodegen { printer.write(closureCallExpr.description) } else { printer.write("let result = \(closureCallExpr)") - printer.write("return result.bridgeJSLowerReturn()") + switch signature.returnType { + case .swiftProtocol: + printer.write( + "return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" + ) + case .nullable(.swiftProtocol, _): + printer.write("if let result {") + printer.indent { + printer.write( + "_swift_js_return_optional_object(1, (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + ) + } + printer.write("} else {") + printer.indent { + printer.write("_swift_js_return_optional_object(0, 0)") + } + printer.write("}") + default: + printer.write("return result.bridgeJSLowerReturn()") + } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 8ccbbee76..eab3a0831 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -1454,6 +1454,16 @@ extension BridgeType { } } + var closureSwiftType: String { + switch self { + case .swiftProtocol(let name): return "any \(name)" + case .nullable(let wrappedType, let kind): + let wrappedClosureType = wrappedType.closureSwiftType + return kind == .null ? "Optional<\(wrappedClosureType)>" : "JSUndefinedOr<\(wrappedClosureType)>" + default: return swiftType + } + } + var isClosureType: Bool { if case .closure = self { return true } return false diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 1b7dce434..7d9a6f087 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -163,8 +163,28 @@ public struct ImportTS { } ) ) + } else if case .nullable(.swiftProtocol, _) = param.type, context == .exportSwift { + body.write("let \(pattern): (Int32, Int32)") + body.write("if let \(param.name) {") + body.indent { + body.write( + "\(pattern) = (1, (\(param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + ) + } + body.write("} else {") + body.indent { + body.write("\(pattern) = (0, 0)") + } + body.write("}") } else { - let initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + let initializerExpr: ExprSyntax + if case .swiftProtocol = param.type, context == .exportSwift { + initializerExpr = ExprSyntax( + "(\(raw: param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" + ) + } else { + initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + } if loweringInfo.loweredParameters.isEmpty { stackLoweringStmts.insert("let _ = \(initializerExpr)", at: 0) @@ -817,7 +837,12 @@ extension BridgeType { case .swiftHeapObject: return LoweringParameterInfo(loweredParameters: [("pointer", .pointer)]) case .swiftProtocol: - throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") + switch context { + case .importTS: + throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") + case .exportSwift: + return LoweringParameterInfo(loweredParameters: [("objectId", .i32)]) + } case .caseEnum: switch context { case .importTS: @@ -891,7 +916,12 @@ extension BridgeType { case .swiftHeapObject: return LiftingReturnInfo(valueToLift: .pointer) case .swiftProtocol: - throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") + switch context { + case .importTS: + throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") + case .exportSwift: + return LiftingReturnInfo(valueToLift: .i32) + } case .caseEnum: switch context { case .importTS: diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift new file mode 100644 index 000000000..cb814adf2 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift @@ -0,0 +1,18 @@ +import JavaScriptKit + +@JS protocol Renderable { + func render() -> String +} + +@JS class Widget { + @JS var name: String + + @JS init(name: String) { + self.name = name + } +} + +@JS func processRenderable(_ item: Renderable, transform: (Renderable) -> String) -> String +@JS func makeRenderableFactory(defaultName: String) -> () -> Renderable +@JS func roundtripRenderable(_ callback: (Renderable) -> Renderable) -> (Renderable) -> Renderable +@JS func processOptionalRenderable(_ callback: (Renderable?) -> String) -> String diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json new file mode 100644 index 000000000..4ba7ba9a5 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json @@ -0,0 +1,281 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Widget_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Widget", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Widget" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_processRenderable", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processRenderable", + "parameters" : [ + { + "label" : "_", + "name" : "item", + "type" : { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + }, + { + "label" : "transform", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule10RenderableP_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeRenderableFactory", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeRenderableFactory", + "parameters" : [ + { + "label" : "defaultName", + "name" : "defaultName", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuley_10RenderableP", + "moduleName" : "TestModule", + "parameters" : [ + + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripRenderable", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripRenderable", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule10RenderableP_10RenderableP", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule10RenderableP_10RenderableP", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "Renderable" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_processOptionalRenderable", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalRenderable", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq10RenderableP_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftProtocol" : { + "_0" : "Renderable" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + { + "methods" : [ + { + "abiName" : "bjs_Renderable_render", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "render", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Renderable", + "properties" : [ + + ] + } + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift new file mode 100644 index 000000000..26c3d1db0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift @@ -0,0 +1,388 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP") +fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP") +fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule10RenderableP_10RenderableP { + static func bridgeJSLift(_ callbackId: Int32) -> (any Renderable) -> any Renderable { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP(callbackValue, param0ObjectId) + return AnyRenderable.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (any Renderable) -> any Renderable { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (any Renderable) -> any Renderable) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP") +@_cdecl("invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP") +public func _invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(any Renderable) -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(AnyRenderable.bridgeJSLiftParameter(param0)) + return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule10RenderableP_SS") +fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule10RenderableP_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule10RenderableP_SS_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule10RenderableP_SS") +fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule10RenderableP_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule10RenderableP_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule10RenderableP_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (any Renderable) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_SS(callbackValue, param0ObjectId) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (any Renderable) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (any Renderable) -> String) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule10RenderableP_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule10RenderableP_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModule10RenderableP_SS") +public func _invoke_swift_closure_TestModule_10TestModule10RenderableP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(any Renderable) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(AnyRenderable.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS_extern(callback, param0IsSome, param0ObjectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS") +fileprivate func make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq10RenderableP_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, param0ObjectId): (Int32, Int32) + if let param0 { + (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } else { + (param0IsSome, param0ObjectId) = (0, 0) + } + let ret = invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS(callbackValue, param0IsSome, param0ObjectId) + 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_TestModule_10TestModuleSq10RenderableP_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS") +public func _invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_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_TestModule_10TestModuley_10RenderableP") +fileprivate func invoke_js_callback_TestModule_10TestModuley_10RenderableP_extern(_ callback: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_10RenderableP_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_10RenderableP(_ callback: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuley_10RenderableP_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_10RenderableP") +fileprivate func make_swift_closure_TestModule_10TestModuley_10RenderableP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_10RenderableP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_10RenderableP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_10RenderableP_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_10RenderableP { + static func bridgeJSLift(_ callbackId: Int32) -> () -> any Renderable { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuley_10RenderableP(callbackValue) + return AnyRenderable.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> any Renderable { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> any Renderable) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_10RenderableP, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_10RenderableP") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_10RenderableP") +public func _invoke_swift_closure_TestModule_10TestModuley_10RenderableP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +struct AnyRenderable: Renderable, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + func render() -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_render(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyRenderable(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Renderable_render") +fileprivate func _extern_render_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_render_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_render(_ jsObject: Int32) -> Int32 { + return _extern_render_extern(jsObject) +} + +@_expose(wasm, "bjs_processRenderable") +@_cdecl("bjs_processRenderable") +public func _bjs_processRenderable(_ item: Int32, _ transform: Int32) -> Void { + #if arch(wasm32) + let ret = processRenderable(_: AnyRenderable.bridgeJSLiftParameter(item), transform: _BJS_Closure_10TestModule10RenderableP_SS.bridgeJSLift(transform)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeRenderableFactory") +@_cdecl("bjs_makeRenderableFactory") +public func _bjs_makeRenderableFactory(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = makeRenderableFactory(defaultName: String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripRenderable") +@_cdecl("bjs_roundtripRenderable") +public func _bjs_roundtripRenderable(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripRenderable(_: _BJS_Closure_10TestModule10RenderableP_10RenderableP.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalRenderable") +@_cdecl("bjs_processOptionalRenderable") +public func _bjs_processOptionalRenderable(_ callback: Int32) -> Void { + #if arch(wasm32) + let ret = processOptionalRenderable(_: _BJS_Closure_10TestModuleSq10RenderableP_SS.bridgeJSLift(callback)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_init") +@_cdecl("bjs_Widget_init") +public func _bjs_Widget_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Widget(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_name_get") +@_cdecl("bjs_Widget_name_get") +public func _bjs_Widget_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Widget.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_name_set") +@_cdecl("bjs_Widget_name_set") +public func _bjs_Widget_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Widget.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_deinit") +@_cdecl("bjs_Widget_deinit") +public func _bjs_Widget_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Widget: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Widget_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Widget_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Widget_wrap") +fileprivate func _bjs_Widget_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Widget_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Widget_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Widget_wrap_extern(pointer) +} \ 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 new file mode 100644 index 000000000..6b7a9d28d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.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 interface Renderable { + render(): 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 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; +} +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/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js new file mode 100644 index 000000000..ffdac6fa6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -0,0 +1,436 @@ +// 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 f32Stack = []; + let f64Stack = []; + let ptrStack = []; + 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_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_10TestModule10RenderableP_10RenderableP"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(swift.memory.getObject(param0)); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule10RenderableP_10RenderableP = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP(boxPtr, swift.memory.retain(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_10TestModule10RenderableP_10RenderableP); + } + bjs["invoke_js_callback_TestModule_10TestModule10RenderableP_SS"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(swift.memory.getObject(param0)); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule10RenderableP_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule10RenderableP_SS = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModule10RenderableP_SS(boxPtr, swift.memory.retain(param0)); + const ret = tmpRetString; + tmpRetString = undefined; + 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_10TestModule10RenderableP_SS); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS"] = function(callbackId, param0IsSome, param0ObjectId) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? swift.memory.getObject(param0ObjectId) : null); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq10RenderableP_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSq10RenderableP_SS = function(param0) { + const isSome = param0 != null; + let result; + if (isSome) { + result = swift.memory.retain(param0); + } else { + result = 0; + } + instance.exports.invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS(boxPtr, +isSome, result); + const ret = tmpRetString; + tmpRetString = undefined; + 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_10TestModuleSq10RenderableP_SS); + } + bjs["invoke_js_callback_TestModule_10TestModuley_10RenderableP"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuley_10RenderableP"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_10RenderableP = function() { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuley_10RenderableP(boxPtr); + 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_10TestModuley_10RenderableP); + } + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Widget_wrap"] = function(pointer) { + const obj = _exports['Widget'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_Renderable_render"] = function bjs_Renderable_render(self) { + try { + let ret = swift.memory.getObject(self).render(); + 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 swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class Widget extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Widget_deinit, Widget.prototype); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_Widget_init(nameId, nameBytes.length); + return Widget.__construct(ret); + } + get name() { + instance.exports.bjs_Widget_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_Widget_name_set(this.pointer, valueId, valueBytes.length); + } + } + const exports = { + Widget, + processRenderable: function bjs_processRenderable(item, transform) { + const callbackId = swift.memory.retain(transform); + instance.exports.bjs_processRenderable(swift.memory.retain(item), callbackId); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + makeRenderableFactory: function bjs_makeRenderableFactory(defaultName) { + const defaultNameBytes = textEncoder.encode(defaultName); + const defaultNameId = swift.memory.retain(defaultNameBytes); + const ret = instance.exports.bjs_makeRenderableFactory(defaultNameId, defaultNameBytes.length); + return swift.memory.getObject(ret); + }, + roundtripRenderable: function bjs_roundtripRenderable(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripRenderable(callbackId); + return swift.memory.getObject(ret); + }, + processOptionalRenderable: function bjs_processOptionalRenderable(callback) { + const callbackId = swift.memory.retain(callback); + instance.exports.bjs_processOptionalRenderable(callbackId); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 9ef28f844..c2d1c4cd8 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -578,6 +578,10 @@ extension _BridgedSwiftProtocolWrapper { bridgeJSStackPop() } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { + bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { jsObject.bridgeJSLowerReturn() } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 6407a175b..d2fe49db2 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1206,6 +1206,34 @@ enum GraphOperations { } } } + + @JS func processDataProcessor(_ callback: (DataProcessor) -> String) -> String { + let processor = SwiftDataProcessor() + processor.increment(by: 42) + return callback(processor) + } + + @JS func makeDataProcessorFactory() -> () -> DataProcessor { + var count = 0 + return { + count += 1 + let p = SwiftDataProcessor() + p.increment(by: count * 10) + return p + } + } + + @JS func roundtripDataProcessor( + _ callback: @escaping (DataProcessor) -> DataProcessor + ) -> (DataProcessor) -> DataProcessor { + return callback + } + + @JS func processOptionalDataProcessor(_ callback: (DataProcessor?) -> String) -> String { + let processor = SwiftDataProcessor() + processor.increment(by: 7) + return callback(processor) + " | " + callback(nil) + } } class ExportAPITests: XCTestCase { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index db3132c37..e9c0e7653 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -70,6 +70,132 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10H #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP { + static func bridgeJSLift(_ callbackId: Int32) -> (any DataProcessor) -> any DataProcessor { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(callbackValue, param0ObjectId) + return AnyDataProcessor.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (any DataProcessor) -> any DataProcessor { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (any DataProcessor) -> any DataProcessor) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(any DataProcessor) -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(AnyDataProcessor.bridgeJSLiftParameter(param0)) + return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (any DataProcessor) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(callbackValue, param0ObjectId) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (any DataProcessor) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (any DataProcessor) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(any DataProcessor) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(AnyDataProcessor.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 @@ -1033,6 +1159,74 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_ #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0ObjectId: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(callback, param0IsSome, param0ObjectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_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, param0ObjectId): (Int32, Int32) + if let param0 { + (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } else { + (param0IsSome, param0ObjectId) = (0, 0) + } + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS(callbackValue, param0IsSome, param0ObjectId) + 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_20BridgeJSRuntimeTestsSq13DataProcessorP_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_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_20BridgeJSRuntimeTestsSq5ThemeO_SS") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 @@ -1480,6 +1674,68 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS #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 @@ -9069,6 +9325,50 @@ public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMut #endif } +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_TextProcessor_deinit") @_cdecl("bjs_TextProcessor_deinit") public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index da05bc5ae..8a3656b65 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -3595,6 +3595,189 @@ "useJSTypedClosure" : false } } + }, + { + "abiName" : "bjs_TextProcessor_processDataProcessor", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDataProcessor", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests13DataProcessorP_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_TextProcessor_makeDataProcessorFactory", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeDataProcessorFactory", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_13DataProcessorP", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_TextProcessor_roundtripDataProcessor", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripDataProcessor", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_TextProcessor_processOptionalDataProcessor", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalDataProcessor", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSq13DataProcessorP_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } } ], "name" : "TextProcessor", diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs index 0d5560fae..ebe00548b 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs @@ -77,15 +77,23 @@ export function getImports(importsContext) { } }, jsOptionalInvoke: (fn) => { - if (fn == null) { return false; } + if (fn == null) { + return false; + } return fn(); }, - jsStoreClosure: (fn) => { globalThis.__storedClosure = fn; }, - jsCallStoredClosure: () => { return globalThis.__storedClosure?.(); }, + jsStoreClosure: (fn) => { + globalThis.__storedClosure = fn; + }, + jsCallStoredClosure: () => { + return globalThis.__storedClosure?.(); + }, runJsClosureSupportTests: () => { const exports = importsContext.getExports(); - if (!exports) { throw new Error("No exports!?"); } + if (!exports) { + throw new Error("No exports!?"); + } runJsClosureSupportTests(exports); }, }; @@ -103,19 +111,32 @@ export function runJsClosureSupportTests(exports) { const multiParamTransform = (count, text, ratio) => { return `${text.toUpperCase()}-${count}-${ratio.toFixed(2)}`; }; - assert.equal(processor.processWithCustom("world", multiParamTransform), "WORLD-42-3.14"); + assert.equal( + processor.processWithCustom("world", multiParamTransform), + "WORLD-42-3.14", + ); assert.equal(processor.process("test"), "TEST"); const greeterForClosure = new exports.Greeter("World"); const greeterCaller = new exports.Greeter("Caller"); - const customGreeting = (greeter) => `Custom greeting for ${greeter.name}: ${greeter.greet()}`; - const greetResult = greeterCaller.greetWith(greeterForClosure, customGreeting); + const customGreeting = (greeter) => + `Custom greeting for ${greeter.name}: ${greeter.greet()}`; + const greetResult = greeterCaller.greetWith( + greeterForClosure, + customGreeting, + ); assert.equal(greetResult, "Custom greeting for World: Hello, World!"); greeterForClosure.release(); greeterCaller.release(); - assert.equal(exports.formatName("ada", (name) => name.toUpperCase()), "ADA"); - assert.equal(exports.formatName("grace", (name) => `Dr. ${name}`), "Dr. grace"); + assert.equal( + exports.formatName("ada", (name) => name.toUpperCase()), + "ADA", + ); + assert.equal( + exports.formatName("grace", (name) => `Dr. ${name}`), + "Dr. grace", + ); const addDr = exports.makeFormatter("Dr."); assert.equal(addDr("Ada"), "Dr. Ada"); @@ -137,8 +158,14 @@ export function runJsClosureSupportTests(exports) { const greeterForFormatter = new exports.Greeter("Formatter"); const greeterFormatter = greeterForFormatter.makeFormatter(" [suffix]"); - assert.equal(greeterFormatter("test"), "Hello, Formatter! - test - [suffix]"); - assert.equal(greeterFormatter("data"), "Hello, Formatter! - data - [suffix]"); + assert.equal( + greeterFormatter("test"), + "Hello, Formatter! - test - [suffix]", + ); + assert.equal( + greeterFormatter("data"), + "Hello, Formatter! - data - [suffix]", + ); greeterForFormatter.release(); const greeterCreator = exports.Greeter.makeCreator("Default"); @@ -206,11 +233,16 @@ export function runJsClosureSupportTests(exports) { const dirResult = processor.processDirection((dir) => { switch (dir) { - case exports.Direction.North: return "Going North"; - case exports.Direction.South: return "Going South"; - case exports.Direction.East: return "Going East"; - case exports.Direction.West: return "Going West"; - default: return "Unknown"; + case exports.Direction.North: + return "Going North"; + case exports.Direction.South: + return "Going South"; + case exports.Direction.East: + return "Going East"; + case exports.Direction.West: + return "Going West"; + default: + return "Unknown"; } }); assert.equal(dirResult, "Going North"); @@ -251,12 +283,27 @@ export function runJsClosureSupportTests(exports) { assert.equal(statusExtractor(exports.HttpStatus.Unknown), -1); const apiHandler = processor.makeAPIResultHandler(); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Success, param0: "done" }), "Success: done"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Failure, param0: 500 }), "Failure: 500"); + assert.equal( + apiHandler({ tag: exports.APIResult.Tag.Success, param0: "done" }), + "Success: done", + ); + assert.equal( + apiHandler({ tag: exports.APIResult.Tag.Failure, param0: 500 }), + "Failure: 500", + ); assert.equal(apiHandler({ tag: exports.APIResult.Tag.Info }), "Info"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Flag, param0: true }), "Flag: true"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Rate, param0: 1.5 }), "Rate: 1.5"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Precise, param0: 3.14159 }), "Precise: 3.14159"); + assert.equal( + apiHandler({ tag: exports.APIResult.Tag.Flag, param0: true }), + "Flag: true", + ); + assert.equal( + apiHandler({ tag: exports.APIResult.Tag.Rate, param0: 1.5 }), + "Rate: 1.5", + ); + assert.equal( + apiHandler({ tag: exports.APIResult.Tag.Precise, param0: 3.14159 }), + "Precise: 3.14159", + ); const optDirResult = processor.processOptionalDirection((dir) => { return dir !== null ? `Dir: ${dir}` : "Dir: null"; @@ -284,28 +331,55 @@ export function runJsClosureSupportTests(exports) { assert.equal(optDirFormatter(exports.Direction.West), "W"); assert.equal(optDirFormatter(null), "nil"); - processor.release(); + const dpResult = processor.processDataProcessor((dp) => { + return `Value: ${dp.getValue()}`; + }); + assert.equal(dpResult, "Value: 42"); + const dpFactory = processor.makeDataProcessorFactory(); + const dp1 = dpFactory(); + assert.equal(dp1.getValue(), 10); + const dp2 = dpFactory(); + assert.equal(dp2.getValue(), 20); + + const dpRoundtrip = processor.roundtripDataProcessor((dp) => { + dp.increment(100); + return dp; + }); + const testDp = new exports.SwiftDataProcessor(); + const roundtrippedDp = dpRoundtrip(testDp); + assert.equal(roundtrippedDp.getValue(), 100); + + const optDpResult = processor.processOptionalDataProcessor((dp) => { + return dp !== null ? `DP: ${dp.getValue()}` : "DP: null"; + }); + assert.equal(optDpResult, "DP: 7 | DP: null"); + + processor.release(); const intToInt = exports.ClosureSupportExports.makeIntToInt(10); assert.equal(intToInt(0), 10); assert.equal(intToInt(32), 42); - const doubleToDouble = exports.ClosureSupportExports.makeDoubleToDouble(10.0); + const doubleToDouble = + exports.ClosureSupportExports.makeDoubleToDouble(10.0); assert.equal(doubleToDouble(0.0), 10.0); assert.equal(doubleToDouble(32.0), 42.0); - const stringToString = exports.ClosureSupportExports.makeStringToString("Hello, "); + const stringToString = + exports.ClosureSupportExports.makeStringToString("Hello, "); assert.equal(stringToString("world!"), "Hello, world!"); const jsIntToInt = exports.ClosureSupportExports.makeJSIntToInt(10); assert.equal(jsIntToInt(0), 10); assert.equal(jsIntToInt(32), 42); - const jsDoubleToDouble = exports.ClosureSupportExports.makeJSDoubleToDouble(10.0); + const jsDoubleToDouble = + exports.ClosureSupportExports.makeJSDoubleToDouble(10.0); assert.equal(jsDoubleToDouble(0.0), 10.0); assert.equal(jsDoubleToDouble(32.0), 42.0); - const jsStringToString = exports.ClosureSupportExports.makeJSStringToString("Hello, "); + const jsStringToString = + exports.ClosureSupportExports.makeJSStringToString("Hello, "); assert.equal(jsStringToString("world!"), "Hello, world!"); } From bd36090d8c9e578500f89c324d4a1f415a864a07 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Thu, 12 Mar 2026 16:27:19 +0000 Subject: [PATCH 027/140] BridgeJS: expand integer type support --- .../Generated/JavaScript/BridgeJS.json | 231 +- .../Generated/JavaScript/BridgeJS.json | 28 +- .../Sources/BridgeJSCore/ExportSwift.swift | 19 +- .../Sources/BridgeJSCore/ImportTS.swift | 4 +- .../BridgeJSCore/SwiftToSkeleton.swift | 8 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 15 +- .../Sources/BridgeJSLink/JSGlueGen.swift | 123 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 192 +- .../MacroSwift/FixedWidthIntegers.swift | 19 + .../Inputs/MacroSwift/Optionals.swift | 30 + .../BridgeJSCodegenTests/ArrayTypes.json | 112 +- .../BridgeJSCodegenTests/Async.json | 14 +- .../CrossFileSkipsEmptySkeletons.json | 7 +- .../DefaultParameters.json | 77 +- .../BridgeJSCodegenTests/DictionaryTypes.json | 28 +- .../EnumAssociatedValue.json | 84 +- .../EnumNamespace.Global.json | 56 +- .../BridgeJSCodegenTests/EnumNamespace.json | 56 +- .../BridgeJSCodegenTests/EnumRawType.swift | 14 +- .../FixedWidthIntegers.json | 471 +++ .../FixedWidthIntegers.swift | 255 ++ .../BridgeJSCodegenTests/ImportArray.json | 14 +- .../Namespaces.Global.json | 7 +- .../BridgeJSCodegenTests/Namespaces.json | 7 +- .../BridgeJSCodegenTests/Optionals.json | 344 ++- .../BridgeJSCodegenTests/Optionals.swift | 66 + .../PrimitiveParameters.json | 14 +- .../BridgeJSCodegenTests/PrimitiveReturn.json | 14 +- .../BridgeJSCodegenTests/PropertyTypes.json | 42 +- .../BridgeJSCodegenTests/Protocol.json | 42 +- .../StaticFunctions.Global.json | 84 +- .../BridgeJSCodegenTests/StaticFunctions.json | 84 +- .../StaticProperties.Global.json | 28 +- .../StaticProperties.json | 28 +- .../BridgeJSCodegenTests/SwiftClosure.json | 63 +- .../SwiftClosureImports.json | 49 +- .../BridgeJSCodegenTests/SwiftStruct.json | 42 +- .../SwiftStructImports.json | 28 +- .../BridgeJSLinkTests/ArrayTypes.js | 7 + .../__Snapshots__/BridgeJSLinkTests/Async.js | 7 + .../BridgeJSLinkTests/DefaultParameters.js | 7 + .../BridgeJSLinkTests/DictionaryTypes.js | 7 + .../BridgeJSLinkTests/EnumAssociatedValue.js | 7 + .../BridgeJSLinkTests/EnumCase.js | 7 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 7 + .../BridgeJSLinkTests/EnumNamespace.js | 7 + .../BridgeJSLinkTests/EnumRawType.d.ts | 14 +- .../BridgeJSLinkTests/EnumRawType.js | 47 +- .../BridgeJSLinkTests/FixedWidthIntegers.d.ts | 33 + .../BridgeJSLinkTests/FixedWidthIntegers.js | 317 ++ .../BridgeJSLinkTests/GlobalGetter.js | 7 + .../BridgeJSLinkTests/GlobalThisImports.js | 7 + .../BridgeJSLinkTests/ImportArray.js | 7 + .../ImportedTypeInExportedInterface.js | 7 + .../BridgeJSLinkTests/InvalidPropertyNames.js | 7 + .../BridgeJSLinkTests/JSClass.js | 7 + .../JSClassStaticFunctions.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/Optionals.d.ts | 6 + .../BridgeJSLinkTests/Optionals.js | 49 + .../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 + .../__Snapshots__/BridgeJSLinkTests/Throws.js | 7 + .../BridgeJSLinkTests/UnsafePointer.js | 7 + .../VoidParameterVoidReturn.js | 7 + Plugins/PackageToJS/Templates/instantiate.js | 2 + .../JavaScriptKit/BridgeJSIntrinsics.swift | 266 +- .../Generated/JavaScript/BridgeJS.json | 21 +- .../ArraySupportTests.swift | 4 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 35 +- .../Generated/BridgeJS.swift | 477 ++- .../Generated/JavaScript/BridgeJS.json | 2551 ++++++++++++++--- .../IntegerTypesSupportTests.swift | 73 + .../JavaScript/ArraySupportTests.mjs | 8 +- .../JavaScript/IntegerTypesSupportTests.mjs | 175 ++ .../JavaScript/OptionalSupportTests.mjs | 6 +- .../OptionalSupportTests.swift | 2 + Tests/prelude.mjs | 18 +- 97 files changed, 6088 insertions(+), 1095 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/FixedWidthIntegers.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js create mode 100644 Tests/BridgeJSRuntimeTests/IntegerTypesSupportTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index eacd18cb3..95c4ac18e 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -451,8 +451,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -473,8 +476,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -930,8 +936,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -984,8 +993,11 @@ "isStatic" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1053,8 +1065,11 @@ "label" : "zipCode", "name" : "zipCode", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1090,8 +1105,11 @@ "isStatic" : false, "name" : "zipCode", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1280,8 +1298,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1308,8 +1329,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1330,8 +1354,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1341,8 +1368,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1362,8 +1392,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1656,8 +1689,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1688,8 +1724,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1714,8 +1753,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1729,8 +1771,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1854,8 +1899,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1887,8 +1935,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1914,8 +1965,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1930,8 +1984,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -2060,8 +2117,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2093,8 +2153,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2119,8 +2182,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2146,8 +2212,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2162,8 +2231,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2199,8 +2271,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2286,8 +2361,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2331,8 +2409,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2390,15 +2471,21 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2504,8 +2591,11 @@ "isStatic" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2573,8 +2663,11 @@ "isStatic" : false, "name" : "zipCode", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2602,8 +2695,11 @@ "isStatic" : false, "name" : "age", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2646,8 +2742,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 3046e1f01..60eb694ff 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -147,8 +147,11 @@ "isStatic" : false, "name" : "startLine", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -157,8 +160,11 @@ "isStatic" : false, "name" : "startColumn", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -167,8 +173,11 @@ "isStatic" : false, "name" : "endLine", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -177,8 +186,11 @@ "isStatic" : false, "name" : "endColumn", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index eab3a0831..5b6c7d1ff 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -748,7 +748,7 @@ struct StackCodegen { /// - Returns: An ExprSyntax representing the lift expression func liftExpression(for type: BridgeType) -> ExprSyntax { switch type { - case .string, .int, .uint, .bool, .float, .double, + case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary: return "\(raw: type.swiftType).bridgeJSStackPop()" @@ -766,7 +766,7 @@ struct StackCodegen { private func liftNullableExpression(wrappedType: BridgeType, kind: JSOptionalKind) -> ExprSyntax { let typeName = kind == .null ? "Optional" : "JSUndefinedOr" switch wrappedType { - case .string, .int, .uint, .bool, .float, .double, .jsObject(nil), .jsValue, + case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary: return "\(raw: typeName)<\(raw: wrappedType.swiftType)>.bridgeJSStackPop()" @@ -789,7 +789,7 @@ struct StackCodegen { varPrefix: String ) -> [CodeBlockItemSyntax] { switch type { - case .string, .int, .uint, .bool, .float, .double, .jsValue, + case .string, .integer, .bool, .float, .double, .jsValue, .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, .nullable: return ["\(raw: accessor).bridgeJSStackPush()"] @@ -1425,8 +1425,7 @@ extension BridgeType { var swiftType: String { switch self { case .bool: return "Bool" - case .int: return "Int" - case .uint: return "UInt" + case .integer(let t): return t.swiftTypeName case .float: return "Float" case .double: return "Double" case .string: return "String" @@ -1502,7 +1501,7 @@ extension BridgeType { func liftParameterInfo() throws -> LiftingIntrinsicInfo { switch self { case .bool: return .bool - case .int, .uint: return .int + case .integer(let t): return LiftingIntrinsicInfo(parameters: [("value", t.wasmCoreType)]) case .float: return .float case .double: return .double case .string: return .string @@ -1560,7 +1559,7 @@ extension BridgeType { func loweringReturnInfo() throws -> LoweringIntrinsicInfo { switch self { case .bool: return .bool - case .int, .uint: return .int + case .integer(let t): return LoweringIntrinsicInfo(returnType: t.wasmCoreType) case .float: return .float case .double: return .double case .string: return .string @@ -1592,7 +1591,8 @@ extension SwiftEnumRawType { var liftingIntrinsicInfo: BridgeType.LiftingIntrinsicInfo { switch self { case .bool: return .bool - case .int, .int32, .int64, .uint, .uint32, .uint64: return .int + case .integer(let integerType): + return .init(parameters: [("value", integerType.wasmCoreType)]) case .float: return .float case .double: return .double case .string: return .string @@ -1602,7 +1602,8 @@ extension SwiftEnumRawType { var loweringIntrinsicInfo: BridgeType.LoweringIntrinsicInfo { switch self { case .bool: return .bool - case .int, .int32, .int64, .uint, .uint32, .uint64: return .int + case .integer(let integerType): + return .init(returnType: integerType.wasmCoreType) case .float: return .float case .double: return .double case .string: return .string diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 7d9a6f087..1d1fe3aa9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -822,7 +822,7 @@ extension BridgeType { func loweringParameterInfo(context: BridgeContext = .importTS) throws -> LoweringParameterInfo { switch self { case .bool: return .bool - case .int, .uint: return .int + case .integer(let t): return LoweringParameterInfo(loweredParameters: [("value", t.wasmCoreType)]) case .float: return .float case .double: return .double case .string: return .string @@ -901,7 +901,7 @@ extension BridgeType { ) throws -> LiftingReturnInfo { switch self { case .bool: return .bool - case .int, .uint: return .int + case .integer(let t): return LiftingReturnInfo(valueToLift: t.wasmCoreType) case .float: return .float case .double: return .double case .string: return .string diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 8f1b3fa35..81ad32813 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -442,7 +442,7 @@ public final class SwiftToSkeleton { } private enum ExportSwiftConstants { - static let supportedRawTypes = SwiftEnumRawType.allCases.map { $0.rawValue } + static let supportedRawTypes = SwiftEnumRawType.supportedTypeNames } extension AttributeSyntax { @@ -828,7 +828,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let intValue = Int(intLiteral.literal.text) { let value = DefaultValue.int(isNegative ? -intValue : intValue) - if let type = type, !type.isCompatibleWith(.int) { + if let type = type, !type.isCompatibleWith(.integer(.int)) { return nil } return value @@ -1489,12 +1489,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { for enumCase in exportedEnum.cases { for associatedValue in enumCase.associatedValues { switch associatedValue.type { - case .string, .int, .float, .double, .bool, .caseEnum, .rawValueEnum, + case .string, .integer, .float, .double, .bool, .caseEnum, .rawValueEnum, .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: break case .nullable(let wrappedType, _): switch wrappedType { - case .string, .int, .float, .double, .bool, .caseEnum, .rawValueEnum, + case .string, .integer, .float, .double, .bool, .caseEnum, .rawValueEnum, .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: break default: diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 8c18ced4d..f69a4b266 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -302,6 +302,7 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject);", "let \(JSGlueVariableScope.reservedStringStack) = [];", "let \(JSGlueVariableScope.reservedI32Stack) = [];", + "let \(JSGlueVariableScope.reservedI64Stack) = [];", "let \(JSGlueVariableScope.reservedF32Stack) = [];", "let \(JSGlueVariableScope.reservedF64Stack) = [];", "let \(JSGlueVariableScope.reservedPointerStack) = [];", @@ -437,6 +438,16 @@ public struct BridgeJSLink { printer.write("return \(JSGlueVariableScope.reservedPointerStack).pop();") } printer.write("}") + printer.write("bjs[\"swift_js_push_i64\"] = function(v) {") + printer.indent { + printer.write("\(JSGlueVariableScope.reservedI64Stack).push(v);") + } + printer.write("}") + printer.write("bjs[\"swift_js_pop_i64\"] = function() {") + printer.indent { + printer.write("return \(JSGlueVariableScope.reservedI64Stack).pop();") + } + printer.write("}") if !allStructs.isEmpty { for structDef in allStructs { printer.write("bjs[\"swift_js_struct_lower_\(structDef.abiName)\"] = function(objectId) {") @@ -3508,8 +3519,8 @@ extension BridgeType { return "void" case .string: return "string" - case .int, .uint: - return "number" + case .integer(let t): + return t.tsTypeName case .float: return "number" case .double: diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index bec5ce3e9..599b6df39 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -26,6 +26,7 @@ final class JSGlueVariableScope { static let reservedTextDecoder = "textDecoder" static let reservedStringStack = "strStack" static let reservedI32Stack = "i32Stack" + static let reservedI64Stack = "i64Stack" static let reservedF32Stack = "f32Stack" static let reservedF64Stack = "f64Stack" static let reservedPointerStack = "ptrStack" @@ -54,6 +55,7 @@ final class JSGlueVariableScope { reservedTextDecoder, reservedStringStack, reservedI32Stack, + reservedI64Stack, reservedF32Stack, reservedF64Stack, reservedPointerStack, @@ -100,6 +102,9 @@ extension JSGlueVariableScope { func emitPushI32Parameter(_ value: String, printer: CodeFragmentPrinter) { printer.write("\(JSGlueVariableScope.reservedI32Stack).push(\(value));") } + func emitPushI64Parameter(_ value: String, printer: CodeFragmentPrinter) { + printer.write("\(JSGlueVariableScope.reservedI64Stack).push(\(value));") + } func emitPushF64Parameter(_ value: String, printer: CodeFragmentPrinter) { printer.write("\(JSGlueVariableScope.reservedF64Stack).push(\(value));") } @@ -117,6 +122,9 @@ extension JSGlueVariableScope { func popI32() -> String { return "\(JSGlueVariableScope.reservedI32Stack).pop()" } + func popI64() -> String { + return "\(JSGlueVariableScope.reservedI64Stack).pop()" + } func popF64() -> String { return "\(JSGlueVariableScope.reservedF64Stack).pop()" } @@ -238,6 +246,14 @@ struct IntrinsicJSFragment: Sendable { ) static let uintLiftParameter = uintLiftReturn + static let uint64LiftReturn = IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, _ in + return ["BigInt.asUintN(64, \(arguments[0]))"] + } + ) + static let uint64LiftParameter = uint64LiftReturn + // MARK: - String Fragments static let stringLowerParameter = IntrinsicJSFragment( @@ -650,7 +666,12 @@ struct IntrinsicJSFragment: Sendable { ) } - let innerFragment = try liftParameter(type: wrappedType, context: bridgeContext) + let innerFragment = + if wrappedType.optionalConvention == .stackABI { + try stackLiftFragment(elementType: wrappedType) + } else { + try liftParameter(type: wrappedType, context: bridgeContext) + } return compositeOptionalLiftParameter( wrappedType: wrappedType, kind: kind, @@ -738,7 +759,12 @@ struct IntrinsicJSFragment: Sendable { ) } - let innerFragment = try lowerParameter(type: wrappedType) + let innerFragment = + if wrappedType.optionalConvention == .stackABI { + try stackLowerFragment(elementType: wrappedType) + } else { + try lowerParameter(type: wrappedType) + } return try compositeOptionalLowerParameter( wrappedType: wrappedType, kind: kind, @@ -832,7 +858,12 @@ struct IntrinsicJSFragment: Sendable { let isSomeVar = scope.variable("isSome") printer.write("const \(isSomeVar) = \(scope.popI32());") - let innerFragment = try liftReturn(type: wrappedType) + let innerFragment = + if wrappedType.optionalConvention == .stackABI { + try stackLiftFragment(elementType: wrappedType) + } else { + try liftReturn(type: wrappedType) + } let innerPrinter = CodeFragmentPrinter() let innerResults = try innerFragment.printCode([], context.with(\.printer, innerPrinter)) @@ -1077,6 +1108,15 @@ struct IntrinsicJSFragment: Sendable { return optionalLowerReturnToSideChannel(mode: mode, kind: kind) } + if wrappedType.optionalConvention == .stackABI { + let innerFragment = try stackLowerFragment(elementType: wrappedType) + return stackOptionalLower( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment + ) + } + if wrappedType.nilSentinel.hasSentinel { let innerFragment = try lowerReturn(type: wrappedType, context: .exportSwift) return sentinelOptionalLowerReturn( @@ -1183,10 +1223,10 @@ struct IntrinsicJSFragment: Sendable { private static func popExpression(for wasmType: WasmCoreType, scope: JSGlueVariableScope) -> String { switch wasmType { case .i32: return scope.popI32() + case .i64: return scope.popI64() case .f32: return scope.popF32() case .f64: return scope.popF64() case .pointer: return scope.popPointer() - case .i64: return scope.popI32() } } @@ -1198,10 +1238,10 @@ struct IntrinsicJSFragment: Sendable { ) { switch wasmType { case .i32: scope.emitPushI32Parameter(value, printer: printer) + case .i64: scope.emitPushI64Parameter(value, printer: printer) case .f32: scope.emitPushF32Parameter(value, printer: printer) case .f64: scope.emitPushF64Parameter(value, printer: printer) case .pointer: scope.emitPushPointerParameter(value, printer: printer) - case .i64: scope.emitPushI32Parameter(value, printer: printer) } } @@ -1243,7 +1283,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 { - case .bool, .int, .uint, .float, .double, .unsafePointer, .caseEnum: + case .bool, .integer, .float, .double, .unsafePointer, .caseEnum: return .identity case .rawValueEnum(_, let rawType) where rawType != .string: return .identity @@ -1291,9 +1331,19 @@ struct IntrinsicJSFragment: Sendable { switch type { case .bool, .rawValueEnum(_, .bool): return .boolLiftReturn - case .uint: + case .integer(let t) where !t.is64Bit && !t.isSigned: + return .uintLiftReturn + case .integer(let t) where t.is64Bit && !t.isSigned: + return .uint64LiftReturn + case .rawValueEnum(_, let rawType) + where rawType.integerType?.is64Bit == false + && rawType.integerType?.isSigned == false: return .uintLiftReturn - case .int, .float, .double, .unsafePointer, .caseEnum: + case .rawValueEnum(_, let rawType) + where rawType.integerType?.is64Bit == true + && rawType.integerType?.isSigned == false: + return .uint64LiftReturn + case .integer, .float, .double, .unsafePointer, .caseEnum: return .identity case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: return .identity @@ -1340,9 +1390,19 @@ struct IntrinsicJSFragment: Sendable { switch type { case .bool, .rawValueEnum(_, .bool): return .boolLiftParameter - case .uint: + case .integer(let t) where !t.is64Bit && !t.isSigned: + return .uintLiftParameter + case .integer(let t) where t.is64Bit && !t.isSigned: + return .uint64LiftParameter + case .rawValueEnum(_, let rawType) + where rawType.integerType?.is64Bit == false + && rawType.integerType?.isSigned == false: return .uintLiftParameter - case .int, .float, .double, .unsafePointer, .caseEnum: + case .rawValueEnum(_, let rawType) + where rawType.integerType?.is64Bit == true + && rawType.integerType?.isSigned == false: + return .uint64LiftParameter + case .integer, .float, .double, .unsafePointer, .caseEnum: return .identity case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: return .identity @@ -1426,7 +1486,7 @@ struct IntrinsicJSFragment: Sendable { switch type { case .bool, .rawValueEnum(_, .bool): return .boolLowerReturn - case .int, .uint, .float, .double, .unsafePointer, .caseEnum: + case .integer, .float, .double, .unsafePointer, .caseEnum: return .identity case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: return .identity @@ -2577,8 +2637,10 @@ private extension BridgeType { switch self { case .bool: return .inlineFlag - case .int, .uint: + case .integer(let t) where !t.is64Bit: return .sideChannelReturn(.none) + case .integer: + return .stackABI case .float: return .sideChannelReturn(.none) case .double: @@ -2605,7 +2667,9 @@ private extension BridgeType { return .sideChannelReturn(.none) case .bool: return .inlineFlag - case .int, .int32, .int64, .uint, .uint32, .uint64: + case .integer(let integerType) where integerType.is64Bit: + return .stackABI + case .integer: return .sideChannelReturn(.none) } case .associatedValueEnum: @@ -2637,9 +2701,10 @@ private extension BridgeType { var optionalScalarKind: OptionalScalarKind? { switch self { case .bool, .rawValueEnum(_, .bool): return .bool - case .int, .uint, .caseEnum, - .rawValueEnum(_, .int), .rawValueEnum(_, .int32), .rawValueEnum(_, .int64), - .rawValueEnum(_, .uint), .rawValueEnum(_, .uint32), .rawValueEnum(_, .uint64): + case .integer(let t) where !t.is64Bit: return .int + case .caseEnum: + return .int + case .rawValueEnum(_, let rawType) where rawType.integerType?.is64Bit == false: return .int case .float, .rawValueEnum(_, .float): return .float case .double, .rawValueEnum(_, .double): return .double @@ -2650,8 +2715,10 @@ private extension BridgeType { var wasmParams: [(name: String, type: WasmCoreType)] { switch self { - case .bool, .int, .uint: + case .bool: return [("value", .i32)] + case .integer(let t): + return [("value", t.wasmCoreType)] case .float: return [("value", .f32)] case .double: @@ -2678,8 +2745,10 @@ private extension BridgeType { return [("value", .f32)] case .double: return [("value", .f64)] - case .bool, .int, .int32, .int64, .uint, .uint32, .uint64: + case .bool: return [("value", .i32)] + case .integer(let integerType): + return [("value", integerType.wasmCoreType)] } case .associatedValueEnum: return [("caseId", .i32)] @@ -2694,7 +2763,7 @@ private extension BridgeType { var isSingleParamScalar: Bool { switch self { - case .bool, .int, .uint, .float, .double, .unsafePointer, .caseEnum: return true + case .bool, .integer, .float, .double, .unsafePointer, .caseEnum: return true case .rawValueEnum(_, let rawType): return rawType != .string default: return false } @@ -2703,9 +2772,11 @@ private extension BridgeType { var stackLowerCoerce: String? { switch self { case .bool, .rawValueEnum(_, .bool): return "$0 ? 1 : 0" - case .int, .uint, .unsafePointer, .caseEnum, - .rawValueEnum(_, .int), .rawValueEnum(_, .int32), .rawValueEnum(_, .int64), - .rawValueEnum(_, .uint), .rawValueEnum(_, .uint32), .rawValueEnum(_, .uint64): + case .integer(let t) where !t.is64Bit: return "($0 | 0)" + case .integer: return nil // 64-bit integers pass through directly + case .unsafePointer, .caseEnum: + return "($0 | 0)" + case .rawValueEnum(_, let rawType) where rawType.integerType?.is64Bit == false: return "($0 | 0)" case .float, .rawValueEnum(_, .float): return "Math.fround($0)" case .double, .rawValueEnum(_, .double): return nil @@ -2716,7 +2787,11 @@ private extension BridgeType { var liftCoerce: String? { switch self { case .bool, .rawValueEnum(_, .bool): return "$0 !== 0" - case .uint: return "$0 >>> 0" + case .integer(let t) where !t.is64Bit && !t.isSigned: return "$0 >>> 0" + case .rawValueEnum(_, let rawType) + where rawType.integerType?.is64Bit == false + && rawType.integerType?.isSigned == false: + return "$0 >>> 0" default: return nil } } @@ -2731,7 +2806,7 @@ private extension BridgeType { var varHint: String { switch self { case .bool: return "bool" - case .int, .uint: return "int" + case .integer: return "int" case .float: return "f32" case .double: return "f64" case .unsafePointer: return "pointer" diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 967215f6c..1f03e09ba 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -164,8 +164,65 @@ public enum JSOptionalKind: String, Codable, Equatable, Hashable, Sendable { } } +public enum IntegerWidth: String, Codable, Equatable, Hashable, Sendable { + case word // Int / UInt (ptr-sized, 32-bit on wasm32) + case w8, w16, w32, w64 +} + +public struct BridgeIntegerType: Codable, Equatable, Hashable, Sendable { + public let width: IntegerWidth + public let isSigned: Bool + + public static let int = BridgeIntegerType(width: .word, isSigned: true) + public static let uint = BridgeIntegerType(width: .word, isSigned: false) + public static let int8 = BridgeIntegerType(width: .w8, isSigned: true) + public static let uint8 = BridgeIntegerType(width: .w8, isSigned: false) + public static let int16 = BridgeIntegerType(width: .w16, isSigned: true) + public static let uint16 = BridgeIntegerType(width: .w16, isSigned: false) + public static let int32 = BridgeIntegerType(width: .w32, isSigned: true) + public static let uint32 = BridgeIntegerType(width: .w32, isSigned: false) + public static let int64 = BridgeIntegerType(width: .w64, isSigned: true) + public static let uint64 = BridgeIntegerType(width: .w64, isSigned: false) + + public var is64Bit: Bool { width == .w64 } + public var wasmCoreType: WasmCoreType { is64Bit ? .i64 : .i32 } + + public var swiftTypeName: String { + switch (width, isSigned) { + case (.word, true): return "Int" + case (.word, false): return "UInt" + case (.w8, true): return "Int8" + case (.w8, false): return "UInt8" + case (.w16, true): return "Int16" + case (.w16, false): return "UInt16" + case (.w32, true): return "Int32" + case (.w32, false): return "UInt32" + case (.w64, true): return "Int64" + case (.w64, false): return "UInt64" + } + } + + public var tsTypeName: String { is64Bit ? "bigint" : "number" } + + public var mangleTypeName: String { + switch (width, isSigned) { + case (.word, true): return "Si" + case (.word, false): return "Su" + case (.w8, true): return "s8" + case (.w8, false): return "u8" + case (.w16, true): return "s16" + case (.w16, false): return "u16" + case (.w32, true): return "s32" + case (.w32, false): return "u32" + case (.w64, true): return "s64" + case (.w64, false): return "u64" + } + } +} + public enum BridgeType: Codable, Equatable, Hashable, Sendable { - case int, uint, float, double, string, bool, jsObject(String?), jsValue, swiftHeapObject(String), void + case integer(BridgeIntegerType), float, double, string, bool, jsObject(String?), jsValue, swiftHeapObject(String), + void case unsafePointer(UnsafePointerType) indirect case nullable(BridgeType, JSOptionalKind) indirect case array(BridgeType) @@ -183,26 +240,53 @@ public enum WasmCoreType: String, Codable, Sendable { case i32, i64, f32, f64, pointer } -public enum SwiftEnumRawType: String, CaseIterable, Codable, Sendable { - case string = "String" - case bool = "Bool" - case int = "Int" - case int32 = "Int32" - case int64 = "Int64" - case uint = "UInt" - case uint32 = "UInt32" - case uint64 = "UInt64" - case float = "Float" - case double = "Double" +public enum SwiftEnumRawType: RawRepresentable, Codable, Equatable, Hashable, Sendable { + case string + case bool + case integer(BridgeIntegerType) + case float + case double + + private static let integerTypeMappings: [(name: String, type: BridgeIntegerType)] = [ + ("Int", .int), + ("Int32", .int32), + ("Int64", .int64), + ("UInt", .uint), + ("UInt32", .uint32), + ("UInt64", .uint64), + ] + + public static let supportedTypeNames = + [ + "String", + "Bool", + "Float", + "Double", + ] + integerTypeMappings.map(\.name) + + public var rawValue: String { + switch self { + case .string: + return "String" + case .bool: + return "Bool" + case .integer(let integerType): + return integerType.swiftTypeName + case .float: + return "Float" + case .double: + return "Double" + } + } public var wasmCoreType: WasmCoreType? { switch self { case .string: return nil - case .bool, .int, .int32, .uint, .uint32: + case .bool: return .i32 - case .int64, .uint64: - return .i64 + case .integer(let integerType): + return integerType.wasmCoreType case .float: return .f32 case .double: @@ -210,13 +294,54 @@ public enum SwiftEnumRawType: String, CaseIterable, Codable, Sendable { } } + public var integerType: BridgeIntegerType? { + guard case .integer(let integerType) = self else { + return nil + } + return integerType + } + + public init?(rawValue: String) { + if let integerType = Self.integerTypeMappings.first(where: { $0.name == rawValue })?.type { + self = .integer(integerType) + return + } + switch rawValue { + case "String": + self = .string + case "Bool": + self = .bool + case "Float": + self = .float + case "Double": + self = .double + default: + return nil + } + } + public init?(_ rawTypeString: String?) { - guard let rawTypeString = rawTypeString, - let match = Self.allCases.first(where: { $0.rawValue == rawTypeString }) - else { + guard let rawTypeString else { return nil } - self = match + self.init(rawValue: rawTypeString) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + let rawValue = try container.decode(String.self) + guard let value = Self(rawValue: rawValue) else { + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Unknown Swift enum raw type: \(rawValue)" + ) + } + self = value + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) } } @@ -495,8 +620,10 @@ extension EnumCase { return "\"\(rawValue)\"" case .bool: return rawValue.lowercased() == "true" ? "true" : "false" - case .float, .double, .int, .int32, .int64, .uint, .uint32, .uint64: + case .float, .double: return rawValue + case .integer(let integerType): + return integerType.is64Bit ? "\(rawValue)n" : rawValue } } } @@ -1056,10 +1183,16 @@ extension BridgeType { /// Maps Swift primitive type names to BridgeType. Returns nil for unknown types. public init?(swiftType: String) { switch swiftType { - case "Int": - self = .int - case "UInt": - self = .uint + case "Int": self = .integer(.int) + case "UInt": self = .integer(.uint) + case "Int8": self = .integer(.int8) + case "UInt8": self = .integer(.uint8) + case "Int16": self = .integer(.int16) + case "UInt16": self = .integer(.uint16) + case "Int32": self = .integer(.int32) + case "UInt32": self = .integer(.uint32) + case "Int64": self = .integer(.int64) + case "UInt64": self = .integer(.uint64) case "Float": self = .float case "Double": @@ -1089,7 +1222,7 @@ extension BridgeType { switch self { case .void: return nil case .bool: return .i32 - case .int, .uint: return .i32 + case .integer(let t): return t.wasmCoreType case .float: return .f32 case .double: return .f64 case .string: return nil @@ -1138,8 +1271,7 @@ extension BridgeType { /// https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst#types public var mangleTypeName: String { switch self { - case .int: return "Si" - case .uint: return "Su" + case .integer(let t): return t.mangleTypeName case .float: return "Sf" case .double: return "Sd" case .string: return "SS" @@ -1206,12 +1338,14 @@ extension BridgeType { } switch wrappedType { - case .string, .int, .float, .double, .jsObject, .swiftProtocol: + case .string, .integer, .float, .double, .jsObject, .swiftProtocol: return true case .rawValueEnum(_, let rawType): switch rawType { - case .string, .int, .float, .double: + case .string, .float, .double: return true + case .integer(let integerType): + return !integerType.is64Bit default: return false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/FixedWidthIntegers.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/FixedWidthIntegers.swift new file mode 100644 index 000000000..8f984acf0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/FixedWidthIntegers.swift @@ -0,0 +1,19 @@ +import JavaScriptKit + +@JS public func roundTripInt8(_ v: Int8) -> Int8 { v } +@JS public func roundTripUInt8(_ v: UInt8) -> UInt8 { v } +@JS public func roundTripInt16(_ v: Int16) -> Int16 { v } +@JS public func roundTripUInt16(_ v: UInt16) -> UInt16 { v } +@JS public func roundTripInt32(_ v: Int32) -> Int32 { v } +@JS public func roundTripUInt32(_ v: UInt32) -> UInt32 { v } +@JS public func roundTripInt64(_ v: Int64) -> Int64 { v } +@JS public func roundTripUInt64(_ v: UInt64) -> UInt64 { v } + +@JSFunction func roundTripInt8(_ v: Int8) throws(JSException) -> Int8 +@JSFunction func roundTripUInt8(_ v: UInt8) throws(JSException) -> UInt8 +@JSFunction func roundTripInt16(_ v: Int16) throws(JSException) -> Int16 +@JSFunction func roundTripUInt16(_ v: UInt16) throws(JSException) -> UInt16 +@JSFunction func roundTripInt32(_ v: Int32) throws(JSException) -> Int32 +@JSFunction func roundTripUInt32(_ v: UInt32) throws(JSException) -> UInt32 +@JSFunction func roundTripInt64(_ v: Int64) throws(JSException) -> Int64 +@JSFunction func roundTripUInt64(_ v: UInt64) throws(JSException) -> UInt64 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift index 57d994519..927fac6a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift @@ -40,6 +40,36 @@ func roundTripInt(value: Int?) -> Int? { return value } +@JS +func roundTripInt8(value: Int8?) -> Int8? { + return value +} + +@JS +func roundTripUInt8(value: UInt8?) -> UInt8? { + return value +} + +@JS +func roundTripInt16(value: Int16?) -> Int16? { + return value +} + +@JS +func roundTripUInt16(value: UInt16?) -> UInt16? { + return value +} + +@JS +func roundTripInt32(value: Int32?) -> Int32? { + return value +} + +@JS +func roundTripUInt32(value: UInt32?) -> UInt32? { + return value +} + @JS func roundTripBool(flag: Bool?) -> Bool? { return flag diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json index 32bdb3374..3664fa339 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -26,8 +26,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -60,8 +63,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -178,8 +184,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -189,8 +198,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -411,8 +423,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -420,8 +435,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -591,8 +609,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -607,8 +628,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -677,8 +701,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -693,8 +720,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -851,8 +881,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -866,8 +899,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1163,8 +1199,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1185,8 +1224,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1207,8 +1249,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1237,8 +1282,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json index a780871ba..a2b95cc24 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -38,15 +38,21 @@ "label" : "_", "name" : "v", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json index 10c079b27..4d7495a7c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json @@ -9,8 +9,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json index 8c088a35e..f8a23c33d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json @@ -92,8 +92,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -167,8 +170,11 @@ "isStatic" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -296,15 +302,21 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -510,8 +522,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -776,8 +791,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -787,8 +805,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -978,8 +999,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -989,8 +1013,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1046,8 +1073,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1100,8 +1130,11 @@ "isStatic" : false, "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index af5b83dc7..c740dc46f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -32,8 +32,11 @@ "type" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -43,8 +46,11 @@ "returnType" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -110,8 +116,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -125,8 +134,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json index 3c624fa12..b92cee954 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json @@ -31,8 +31,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -118,8 +121,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -137,8 +143,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -196,15 +205,21 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -304,8 +319,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -323,8 +341,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -378,8 +399,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -426,8 +450,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -467,8 +494,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -705,8 +735,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -811,8 +844,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json index b519748d4..46dbe8917 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -30,8 +30,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -56,8 +59,11 @@ "Utils" ], "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -201,8 +207,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -509,15 +518,21 @@ "label" : "rootId", "name" : "rootId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -544,15 +559,21 @@ "label" : "graphId", "name" : "graphId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -579,8 +600,11 @@ "label" : "graphId", "name" : "graphId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json index a468b2e2c..a57703b09 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -30,8 +30,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -56,8 +59,11 @@ "Utils" ], "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -201,8 +207,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -509,15 +518,21 @@ "label" : "rootId", "name" : "rootId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -544,15 +559,21 @@ "label" : "graphId", "name" : "graphId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -579,8 +600,11 @@ "label" : "graphId", "name" : "graphId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index 4511ed1df..e70a6b0aa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -228,7 +228,7 @@ public func _bjs_roundTripOptionalPriority(_ inputIsSome: Int32, _ inputValue: I @_expose(wasm, "bjs_setFileSize") @_cdecl("bjs_setFileSize") -public func _bjs_setFileSize(_ size: Int32) -> Void { +public func _bjs_setFileSize(_ size: Int64) -> Void { #if arch(wasm32) setFileSize(_: FileSize.bridgeJSLiftParameter(size)) #else @@ -238,7 +238,7 @@ public func _bjs_setFileSize(_ size: Int32) -> Void { @_expose(wasm, "bjs_getFileSize") @_cdecl("bjs_getFileSize") -public func _bjs_getFileSize() -> Int32 { +public func _bjs_getFileSize() -> Int64 { #if arch(wasm32) let ret = getFileSize() return ret.bridgeJSLowerReturn() @@ -249,7 +249,7 @@ public func _bjs_getFileSize() -> Int32 { @_expose(wasm, "bjs_roundTripOptionalFileSize") @_cdecl("bjs_roundTripOptionalFileSize") -public func _bjs_roundTripOptionalFileSize(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { +public func _bjs_roundTripOptionalFileSize(_ inputIsSome: Int32, _ inputValue: Int64) -> Void { #if arch(wasm32) let ret = roundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) return ret.bridgeJSLowerReturn() @@ -324,7 +324,7 @@ public func _bjs_roundTripOptionalTokenId(_ inputIsSome: Int32, _ inputValue: In @_expose(wasm, "bjs_setSessionId") @_cdecl("bjs_setSessionId") -public func _bjs_setSessionId(_ session: Int32) -> Void { +public func _bjs_setSessionId(_ session: Int64) -> Void { #if arch(wasm32) setSessionId(_: SessionId.bridgeJSLiftParameter(session)) #else @@ -334,7 +334,7 @@ public func _bjs_setSessionId(_ session: Int32) -> Void { @_expose(wasm, "bjs_getSessionId") @_cdecl("bjs_getSessionId") -public func _bjs_getSessionId() -> Int32 { +public func _bjs_getSessionId() -> Int64 { #if arch(wasm32) let ret = getSessionId() return ret.bridgeJSLowerReturn() @@ -345,7 +345,7 @@ public func _bjs_getSessionId() -> Int32 { @_expose(wasm, "bjs_roundTripOptionalSessionId") @_cdecl("bjs_roundTripOptionalSessionId") -public func _bjs_roundTripOptionalSessionId(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { +public func _bjs_roundTripOptionalSessionId(_ inputIsSome: Int32, _ inputValue: Int64) -> Void { #if arch(wasm32) let ret = roundTripOptionalSessionId(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) return ret.bridgeJSLowerReturn() @@ -442,7 +442,7 @@ public func _bjs_convertPriority(_ status: Int32) -> Int32 { @_expose(wasm, "bjs_validateSession") @_cdecl("bjs_validateSession") -public func _bjs_validateSession(_ session: Int32) -> Void { +public func _bjs_validateSession(_ session: Int64) -> Void { #if arch(wasm32) let ret = validateSession(_: SessionId.bridgeJSLiftParameter(session)) return ret.bridgeJSLowerReturn() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json new file mode 100644 index 000000000..bef9cbc88 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json @@ -0,0 +1,471 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundTripInt8", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt8", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + }, + { + "abiName" : "bjs_roundTripUInt8", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt8", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + }, + { + "abiName" : "bjs_roundTripInt16", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt16", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + }, + { + "abiName" : "bjs_roundTripUInt16", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt16", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + }, + { + "abiName" : "bjs_roundTripInt32", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt32", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + }, + { + "abiName" : "bjs_roundTripUInt32", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt32", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + }, + { + "abiName" : "bjs_roundTripInt64", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt64", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + }, + { + "abiName" : "bjs_roundTripUInt64", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt64", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "roundTripInt8", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + }, + { + "name" : "roundTripUInt8", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + }, + { + "name" : "roundTripInt16", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + }, + { + "name" : "roundTripUInt16", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + }, + { + "name" : "roundTripInt32", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + }, + { + "name" : "roundTripUInt32", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + }, + { + "name" : "roundTripInt64", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + }, + { + "name" : "roundTripUInt64", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift new file mode 100644 index 000000000..544a15e7c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift @@ -0,0 +1,255 @@ +@_expose(wasm, "bjs_roundTripInt8") +@_cdecl("bjs_roundTripInt8") +public func _bjs_roundTripInt8(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripInt8(_: Int8.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt8") +@_cdecl("bjs_roundTripUInt8") +public func _bjs_roundTripUInt8(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripUInt8(_: UInt8.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt16") +@_cdecl("bjs_roundTripInt16") +public func _bjs_roundTripInt16(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripInt16(_: Int16.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt16") +@_cdecl("bjs_roundTripUInt16") +public func _bjs_roundTripUInt16(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt32") +@_cdecl("bjs_roundTripInt32") +public func _bjs_roundTripInt32(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt32") +@_cdecl("bjs_roundTripUInt32") +public func _bjs_roundTripUInt32(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt64") +@_cdecl("bjs_roundTripInt64") +public func _bjs_roundTripInt64(_ v: Int64) -> Int64 { + #if arch(wasm32) + let ret = roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt64") +@_cdecl("bjs_roundTripUInt64") +public func _bjs_roundTripUInt64(_ v: Int64) -> Int64 { + #if arch(wasm32) + let ret = roundTripUInt64(_: UInt64.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripInt8") +fileprivate func bjs_roundTripInt8_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripInt8_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripInt8(_ v: Int32) -> Int32 { + return bjs_roundTripInt8_extern(v) +} + +func _$roundTripInt8(_ v: Int8) throws(JSException) -> Int8 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripInt8(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int8.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripUInt8") +fileprivate func bjs_roundTripUInt8_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripUInt8_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripUInt8(_ v: Int32) -> Int32 { + return bjs_roundTripUInt8_extern(v) +} + +func _$roundTripUInt8(_ v: UInt8) throws(JSException) -> UInt8 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripUInt8(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt8.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripInt16") +fileprivate func bjs_roundTripInt16_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripInt16_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripInt16(_ v: Int32) -> Int32 { + return bjs_roundTripInt16_extern(v) +} + +func _$roundTripInt16(_ v: Int16) throws(JSException) -> Int16 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripInt16(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int16.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripUInt16") +fileprivate func bjs_roundTripUInt16_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripUInt16_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripUInt16(_ v: Int32) -> Int32 { + return bjs_roundTripUInt16_extern(v) +} + +func _$roundTripUInt16(_ v: UInt16) throws(JSException) -> UInt16 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripUInt16(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt16.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripInt32") +fileprivate func bjs_roundTripInt32_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripInt32_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripInt32(_ v: Int32) -> Int32 { + return bjs_roundTripInt32_extern(v) +} + +func _$roundTripInt32(_ v: Int32) throws(JSException) -> Int32 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripInt32(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int32.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripUInt32") +fileprivate func bjs_roundTripUInt32_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_roundTripUInt32_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripUInt32(_ v: Int32) -> Int32 { + return bjs_roundTripUInt32_extern(v) +} + +func _$roundTripUInt32(_ v: UInt32) throws(JSException) -> UInt32 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripUInt32(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt32.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripInt64") +fileprivate func bjs_roundTripInt64_extern(_ v: Int64) -> Int64 +#else +fileprivate func bjs_roundTripInt64_extern(_ v: Int64) -> Int64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripInt64(_ v: Int64) -> Int64 { + return bjs_roundTripInt64_extern(v) +} + +func _$roundTripInt64(_ v: Int64) throws(JSException) -> Int64 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripInt64(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int64.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripUInt64") +fileprivate func bjs_roundTripUInt64_extern(_ v: Int64) -> Int64 +#else +fileprivate func bjs_roundTripUInt64_extern(_ v: Int64) -> Int64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripUInt64(_ v: Int64) -> Int64 { + return bjs_roundTripUInt64_extern(v) +} + +func _$roundTripUInt64(_ v: UInt64) throws(JSException) -> UInt64 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_roundTripUInt64(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt64.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json index b884e0cb9..7f79a8146 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -11,8 +11,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -22,8 +25,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json index 29cbddeb7..9ca72009d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -76,8 +76,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index 619fe0689..0713a2f30 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -76,8 +76,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 9c99bb8c4..67d97821c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -134,8 +134,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -286,8 +289,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -298,8 +304,257 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripInt8", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt8", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripUInt8", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt8", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripInt16", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt16", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripUInt16", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt16", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripInt32", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt32", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripUInt32", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt32", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } } }, "_1" : "null" @@ -601,8 +856,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -613,8 +871,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -699,8 +960,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -858,8 +1122,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -871,8 +1138,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" @@ -1057,8 +1327,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1069,8 +1342,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1085,8 +1361,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" @@ -1097,8 +1376,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" @@ -1198,8 +1480,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1212,8 +1497,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index 8207bd488..0c6a79bf5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -42,6 +42,72 @@ public func _bjs_roundTripInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void #endif } +@_expose(wasm, "bjs_roundTripInt8") +@_cdecl("bjs_roundTripInt8") +public func _bjs_roundTripInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripInt8(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt8") +@_cdecl("bjs_roundTripUInt8") +public func _bjs_roundTripUInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripUInt8(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt16") +@_cdecl("bjs_roundTripInt16") +public func _bjs_roundTripInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripInt16(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt16") +@_cdecl("bjs_roundTripUInt16") +public func _bjs_roundTripUInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripUInt16(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt32") +@_cdecl("bjs_roundTripInt32") +public func _bjs_roundTripInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripInt32(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripUInt32") +@_cdecl("bjs_roundTripUInt32") +public func _bjs_roundTripUInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripUInt32(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripBool") @_cdecl("bjs_roundTripBool") public func _bjs_roundTripBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json index 8b586dbe0..f75bf7610 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -21,8 +21,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -30,8 +33,11 @@ "label" : "b", "name" : "b", "type" : { - "uint" : { - + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json index aae09ea49..cded9a973 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -20,8 +20,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -37,8 +40,11 @@ ], "returnType" : { - "uint" : { - + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json index 1c71b2b8f..24e3f44cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json @@ -14,8 +14,11 @@ "label" : "intValue", "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -92,8 +95,11 @@ "isStatic" : false, "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -142,8 +148,11 @@ "isStatic" : false, "name" : "readonlyInt", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -222,8 +231,11 @@ "isStatic" : false, "name" : "computedReadonly", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -242,8 +254,11 @@ "isStatic" : false, "name" : "observedProperty", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -269,8 +284,11 @@ "label" : "intValue", "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index e9f5264cd..757115c59 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -14,8 +14,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -47,8 +50,11 @@ "isStatic" : false, "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -131,8 +137,11 @@ "label" : "_", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -399,8 +408,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -550,8 +562,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -774,8 +789,11 @@ "isReadonly" : false, "name" : "eventCount", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index b0eac3313..c241595a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -27,8 +27,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -36,15 +39,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -66,8 +75,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -75,15 +87,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -105,8 +123,11 @@ "label" : "x", "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -114,15 +135,21 @@ "label" : "y", "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -166,15 +193,21 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -208,8 +241,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index e4ec22855..7c5df25b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -27,8 +27,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -36,15 +39,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -66,8 +75,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -75,15 +87,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -105,8 +123,11 @@ "label" : "x", "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -114,15 +135,21 @@ "label" : "y", "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -166,15 +193,21 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -208,8 +241,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json index bb9e48091..d14f9b0a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json @@ -43,8 +43,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -103,8 +106,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -179,8 +185,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -280,8 +289,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json index d385e3887..35d740dff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json @@ -43,8 +43,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -103,8 +106,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -179,8 +185,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -280,8 +289,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index 11c6cb893..f610d4bde 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -215,8 +215,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -362,14 +365,20 @@ "moduleName" : "TestModule", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -387,14 +396,20 @@ "moduleName" : "TestModule", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -689,8 +704,11 @@ { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -700,8 +718,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -724,8 +745,11 @@ { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -735,8 +759,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json index 0013c810c..4359b50ec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -9,8 +9,11 @@ { "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -25,14 +28,20 @@ "moduleName" : "TestModule", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -42,8 +51,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -53,8 +65,11 @@ { "name" : "base", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -68,14 +83,20 @@ "moduleName" : "TestModule", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 00c6af5cb..eeb567d4a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -186,8 +186,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -252,8 +255,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -311,8 +317,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -343,8 +352,11 @@ "isStatic" : false, "name" : "age", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -387,8 +399,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -496,8 +511,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index 50af441a9..c1329cd79 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -25,8 +25,11 @@ "isStatic" : false, "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -35,8 +38,11 @@ "isStatic" : false, "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -63,16 +69,22 @@ { "name" : "dx", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { "name" : "dy", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index fcd29e31a..85e9c749a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -34,6 +34,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -116,6 +117,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_Point"] = function(objectId) { structHelpers.Point.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index d274e5606..bf368738e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 67e73fb33..004320e4b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -27,6 +27,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -133,6 +134,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_Config"] = function(objectId) { structHelpers.Config.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 7c31ce220..1e9059e34 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 18cc2c945..eb474d3b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -102,6 +102,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -824,6 +825,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_Point"] = function(objectId) { structHelpers.Point.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index a79d508a0..fe94c046f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -45,6 +45,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -115,6 +116,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 e52cf02d5..948039cf9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -65,6 +65,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -135,6 +136,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 2d05a7a2d..5201350b2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -46,6 +46,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -116,6 +117,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts index 50a45a58d..fbd5ad637 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts @@ -46,10 +46,10 @@ export const PriorityValues: { export type PriorityTag = typeof PriorityValues[keyof typeof PriorityValues]; export const FileSizeValues: { - readonly Tiny: 1024; - readonly Small: 10240; - readonly Medium: 102400; - readonly Large: 1048576; + readonly Tiny: 1024n; + readonly Small: 10240n; + readonly Medium: 102400n; + readonly Large: 1048576n; }; export type FileSizeTag = typeof FileSizeValues[keyof typeof FileSizeValues]; @@ -68,9 +68,9 @@ export const TokenIdValues: { export type TokenIdTag = typeof TokenIdValues[keyof typeof TokenIdValues]; export const SessionIdValues: { - readonly None: 0; - readonly Active: 9876543210; - readonly Expired: 1234567890; + readonly None: 0n; + readonly Active: 9876543210n; + readonly Expired: 1234567890n; }; export type SessionIdTag = typeof SessionIdValues[keyof typeof SessionIdValues]; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 5d28ce60b..7e5334811 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -42,10 +42,10 @@ export const PriorityValues = { }; export const FileSizeValues = { - Tiny: 1024, - Small: 10240, - Medium: 102400, - Large: 1048576, + Tiny: 1024n, + Small: 10240n, + Medium: 102400n, + Large: 1048576n, }; export const UserIdValues = { @@ -61,9 +61,9 @@ export const TokenIdValues = { }; export const SessionIdValues = { - None: 0, - Active: 9876543210, - Expired: 1234567890, + None: 0n, + Active: 9876543210n, + Expired: 1234567890n, }; export const PrecisionValues = { @@ -96,6 +96,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -167,6 +168,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -426,8 +433,14 @@ export async function createInstantiator(options, swift) { roundTripOptionalFileSize: function bjs_roundTripOptionalFileSize(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const rawValue = i64Stack.pop(); + optResult = rawValue; + } else { + optResult = null; + } return optResult; }, setUserId: function bjs_setUserId(id) { @@ -435,7 +448,7 @@ export async function createInstantiator(options, swift) { }, getUserId: function bjs_getUserId() { const ret = instance.exports.bjs_getUserId(); - return ret; + return ret >>> 0; }, roundTripOptionalUserId: function bjs_roundTripOptionalUserId(input) { const isSome = input != null; @@ -449,7 +462,7 @@ export async function createInstantiator(options, swift) { }, getTokenId: function bjs_getTokenId() { const ret = instance.exports.bjs_getTokenId(); - return ret; + return ret >>> 0; }, roundTripOptionalTokenId: function bjs_roundTripOptionalTokenId(input) { const isSome = input != null; @@ -463,13 +476,19 @@ export async function createInstantiator(options, swift) { }, getSessionId: function bjs_getSessionId() { const ret = instance.exports.bjs_getSessionId(); - return ret; + return BigInt.asUintN(64, ret); }, roundTripOptionalSessionId: function bjs_roundTripOptionalSessionId(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const rawValue = i64Stack.pop(); + optResult = rawValue; + } else { + optResult = null; + } return optResult; }, setPrecision: function 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 new file mode 100644 index 000000000..d6ab5aa8f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.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 type Exports = { + roundTripInt8(v: number): number; + roundTripUInt8(v: number): number; + roundTripInt16(v: number): number; + roundTripUInt16(v: number): number; + roundTripInt32(v: number): number; + roundTripUInt32(v: number): number; + roundTripInt64(v: bigint): bigint; + roundTripUInt64(v: bigint): bigint; +} +export type Imports = { + roundTripInt8(v: number): number; + roundTripUInt8(v: number): number; + roundTripInt16(v: number): number; + roundTripUInt16(v: number): number; + roundTripInt32(v: number): number; + roundTripUInt32(v: number): number; + roundTripInt64(v: bigint): bigint; + roundTripUInt64(v: bigint): bigint; +} +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/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js new file mode 100644 index 000000000..53ddd7301 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -0,0 +1,317 @@ +// 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 = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + 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(); + } + 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_roundTripInt8"] = function bjs_roundTripInt8(v) { + try { + let ret = imports.roundTripInt8(v); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripUInt8"] = function bjs_roundTripUInt8(v) { + try { + let ret = imports.roundTripUInt8(v >>> 0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripInt16"] = function bjs_roundTripInt16(v) { + try { + let ret = imports.roundTripInt16(v); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripUInt16"] = function bjs_roundTripUInt16(v) { + try { + let ret = imports.roundTripUInt16(v >>> 0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripInt32"] = function bjs_roundTripInt32(v) { + try { + let ret = imports.roundTripInt32(v); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripUInt32"] = function bjs_roundTripUInt32(v) { + try { + let ret = imports.roundTripUInt32(v >>> 0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripInt64"] = function bjs_roundTripInt64(v) { + try { + let ret = imports.roundTripInt64(v); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_roundTripUInt64"] = function bjs_roundTripUInt64(v) { + try { + let ret = imports.roundTripUInt64(BigInt.asUintN(64, v)); + 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 = { + roundTripInt8: function bjs_roundTripInt8(v) { + const ret = instance.exports.bjs_roundTripInt8(v); + return ret; + }, + roundTripUInt8: function bjs_roundTripUInt8(v) { + const ret = instance.exports.bjs_roundTripUInt8(v); + return ret >>> 0; + }, + roundTripInt16: function bjs_roundTripInt16(v) { + const ret = instance.exports.bjs_roundTripInt16(v); + return ret; + }, + roundTripUInt16: function bjs_roundTripUInt16(v) { + const ret = instance.exports.bjs_roundTripUInt16(v); + return ret >>> 0; + }, + roundTripInt32: function bjs_roundTripInt32(v) { + const ret = instance.exports.bjs_roundTripInt32(v); + return ret; + }, + roundTripUInt32: function bjs_roundTripUInt32(v) { + const ret = instance.exports.bjs_roundTripUInt32(v); + return ret >>> 0; + }, + roundTripInt64: function bjs_roundTripInt64(v) { + const ret = instance.exports.bjs_roundTripInt64(v); + return ret; + }, + roundTripUInt64: function bjs_roundTripUInt64(v) { + const ret = instance.exports.bjs_roundTripUInt64(v); + return BigInt.asUintN(64, ret); + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 4d1e7abdf..346b74eac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 e4a17ebd0..f74095374 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 7a97a47ff..06cf6550e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 cfb0f75e7..c469fcb58 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -130,6 +131,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_FooContainer"] = function(objectId) { structHelpers.FooContainer.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index ca54d8f16..952197c2a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 7e97170e9..88a5adb38 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 39a859e4a..10fafb7a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 9ed0b93f2..08675da6a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -181,6 +182,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 1b5651765..f4fe4dd61 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 840a7a107..4ce318f40 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 672d5ef7b..025a6fc8a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 8401e96b4..4a6ee1990 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 9efb38ffa..267d96152 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index b1a67ccde..a5a6e16fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -50,6 +50,12 @@ export type Exports = { testOptionalPropertyRoundtrip(holder: OptionalPropertyHolder | null): OptionalPropertyHolder | null; roundTripString(name: string | null): string | null; roundTripInt(value: number | null): number | null; + roundTripInt8(value: number | null): number | null; + roundTripUInt8(value: number | null): number | null; + roundTripInt16(value: number | null): number | null; + roundTripUInt16(value: number | null): number | null; + roundTripInt32(value: number | null): number | null; + roundTripUInt32(value: number | null): number | null; roundTripBool(flag: boolean | null): boolean | null; roundTripFloat(number: number | null): number | null; roundTripDouble(precision: 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 f247c8efc..37408a42d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -661,6 +668,48 @@ export async function createInstantiator(options, swift) { tmpRetOptionalInt = undefined; return optResult; }, + roundTripInt8: function bjs_roundTripInt8(value) { + const isSome = value != null; + instance.exports.bjs_roundTripInt8(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripUInt8: function bjs_roundTripUInt8(value) { + const isSome = value != null; + instance.exports.bjs_roundTripUInt8(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripInt16: function bjs_roundTripInt16(value) { + const isSome = value != null; + instance.exports.bjs_roundTripInt16(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripUInt16: function bjs_roundTripUInt16(value) { + const isSome = value != null; + instance.exports.bjs_roundTripUInt16(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripInt32: function bjs_roundTripInt32(value) { + const isSome = value != null; + instance.exports.bjs_roundTripInt32(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripUInt32: function bjs_roundTripUInt32(value) { + const isSome = value != null; + instance.exports.bjs_roundTripUInt32(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, roundTripBool: function bjs_roundTripBool(flag) { const isSome = flag != null; instance.exports.bjs_roundTripBool(+isSome, isSome ? flag ? 1 : 0 : 0); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 770212417..490f2b4e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 0efb2d2b5..bec07b959 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 338e87f9a..658702a39 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 79711d878..e606c3a77 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -45,6 +45,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -148,6 +149,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 ffdac6fa6..13070a3cc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -116,6 +117,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 800b07107..073784583 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -32,6 +32,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -135,6 +136,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 a4290f828..173bd6c27 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -32,6 +32,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -135,6 +136,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 056293ff7..9928804eb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -26,6 +26,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -96,6 +97,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 06f032555..f82ac20df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -26,6 +26,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -96,6 +97,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 d602d4e5a..033f08cd2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 b2241d6ca..8187b9e92 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 9acf70de2..4dd231e0e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 a0e874907..7e90c9415 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -51,6 +51,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -207,6 +208,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 42ca68e78..d9df868ec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -117,6 +118,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 cd2d396df..4334bec62 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -26,6 +26,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -281,6 +282,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_DataPoint"] = function(objectId) { structHelpers.DataPoint.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index cb161707a..d4f1160f3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -103,6 +104,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_Point"] = function(objectId) { structHelpers.Point.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index ae9625f00..b2c381a03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -91,6 +92,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 169b001cf..ef81ef69e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -108,6 +109,12 @@ export async function createInstantiator(options, swift) { 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(); + } bjs["swift_js_struct_lower_PointerFields"] = function(objectId) { structHelpers.PointerFields.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index cc6c0359b..97948b286 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -21,6 +21,7 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalHeapObject; let strStack = []; let i32Stack = []; + let i64Stack = []; let f32Stack = []; let f64Stack = []; let ptrStack = []; @@ -92,6 +93,12 @@ export async function createInstantiator(options, swift) { 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(); + } 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 fd183583b..3dda6b28e 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -65,6 +65,8 @@ async function createInstantiator(options, swift) { swift_js_get_optional_heap_object_pointer: unexpectedBjsCall, swift_js_push_pointer: unexpectedBjsCall, swift_js_pop_pointer: unexpectedBjsCall, + swift_js_push_i64: unexpectedBjsCall, + swift_js_pop_i64: unexpectedBjsCall, swift_js_closure_unregister: unexpectedBjsCall, }; }, diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index c2d1c4cd8..180567ed1 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -261,39 +261,139 @@ extension UInt: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftSta } } -extension Int32: _BridgedSwiftStackType { +extension Int8: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Int8 { + Int8(truncatingIfNeeded: value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Int8 { + Int8(truncatingIfNeeded: value) + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int8 { bridgeJSLiftParameter(_swift_js_pop_i32()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(Int32(self)) } +} + +extension UInt8: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> UInt8 { + UInt8(truncatingIfNeeded: value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> UInt8 { + UInt8(truncatingIfNeeded: value) + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt8 { bridgeJSLiftParameter(_swift_js_pop_i32()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(Int32(self)) } +} + +extension Int16: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Int16 { + Int16(truncatingIfNeeded: value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Int16 { + Int16(truncatingIfNeeded: value) + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int16 { bridgeJSLiftParameter(_swift_js_pop_i32()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(Int32(self)) } +} + +extension UInt16: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> UInt16 { + UInt16(truncatingIfNeeded: value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> UInt16 { + UInt16(truncatingIfNeeded: value) + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt16 { bridgeJSLiftParameter(_swift_js_pop_i32()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(Int32(self)) } +} + +extension Int32: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { self } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Int32 { value } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Int32 { value } @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int32 { _swift_js_pop_i32() } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { self } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(self) } } -extension Int64: _BridgedSwiftStackType { - @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int64 { - Int64(_swift_js_pop_i32()) +extension UInt32: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(bitPattern: self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> UInt32 { + UInt32(bitPattern: value) } - @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - _swift_js_push_i32(Int32(self)) + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> UInt32 { + UInt32(bitPattern: value) } -} - -extension UInt32: _BridgedSwiftStackType { @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt32 { UInt32(bitPattern: _swift_js_pop_i32()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(bitPattern: self) } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { _swift_js_push_i32(Int32(bitPattern: self)) } } -extension UInt64: _BridgedSwiftStackType { +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_push_i64") +private func _swift_js_push_i64_extern(_ v: Int64) +#else +private func _swift_js_push_i64_extern(_ v: Int64) { + _onlyAvailableOnWasm() +} +#endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_i64(_ v: Int64) { + _swift_js_push_i64_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_pop_i64") +private func _swift_js_pop_i64_extern() -> Int64 +#else +private func _swift_js_pop_i64_extern() -> Int64 { + _onlyAvailableOnWasm() +} +#endif +@_spi(BridgeJS) @inline(never) public func _swift_js_pop_i64() -> Int64 { + return _swift_js_pop_i64_extern() +} + +extension Int64: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int64 { self } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int64) -> Int64 { value } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int64) -> Int64 { value } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int64 { + Int64(bitPattern: UInt64(bitPattern: _swift_js_pop_i64())) + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int64 { self } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i64(self) + } +} + +extension UInt64: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int64 { Int64(bitPattern: self) } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int64) -> UInt64 { + UInt64(bitPattern: value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int64) -> UInt64 { + UInt64(bitPattern: value) + } @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt64 { - UInt64(UInt32(bitPattern: _swift_js_pop_i32())) + UInt64(bitPattern: _swift_js_pop_i64()) } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int64 { Int64(bitPattern: self) } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - _swift_js_push_i32(Int32(bitPattern: UInt32(self))) + _swift_js_push_i64(Int64(bitPattern: self)) } } @@ -1319,15 +1419,10 @@ public protocol _BridgedSwiftOptionalScalarSideChannelBridge: _BridgedSwiftOptio @_spi(BridgeJS) static func bridgeJSReadOptionalSideChannelPayload() -> WasmCoreType } -extension Bool: _BridgedSwiftOptionalScalarBridge { - @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } - @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } - @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { - _swift_js_return_optional_bool(isSome, value) - } -} +private protocol _BridgedSwiftOptionalInt32SideChannelBridge: _BridgedSwiftOptionalScalarSideChannelBridge +where WasmCoreType == Int32 {} -extension Int: _BridgedSwiftOptionalScalarSideChannelBridge { +extension _BridgedSwiftOptionalInt32SideChannelBridge { @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { @@ -1341,20 +1436,23 @@ extension Int: _BridgedSwiftOptionalScalarSideChannelBridge { } } -extension UInt: _BridgedSwiftOptionalScalarSideChannelBridge { +extension Bool: _BridgedSwiftOptionalScalarBridge { @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { - _swift_js_return_optional_int(isSome, value) - } - @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPresence() -> Int32 { - _swift_js_get_optional_int_presence() - } - @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPayload() -> Int32 { - _swift_js_get_optional_int_value() + _swift_js_return_optional_bool(isSome, value) } } +extension Int: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension UInt: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension Int8: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension UInt8: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension Int16: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension UInt16: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension Int32: _BridgedSwiftOptionalInt32SideChannelBridge {} +extension UInt32: _BridgedSwiftOptionalInt32SideChannelBridge {} + extension Float: _BridgedSwiftOptionalScalarSideChannelBridge { @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Float32 { _swift_js_pop_f32() } @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Float32 { 0.0 } @@ -1750,115 +1848,69 @@ where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.Ra } extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - switch asOptional { - case .none: - return (isSome: 0, value: 0) - case .some(let value): - return (isSome: 1, value: value.bridgeJSLowerParameter()) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { - let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) - return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - let isSome = _swift_js_get_optional_int_presence() - if isSome == 0 { - return Self(optional: nil) - } else { - let rawValue = _swift_js_get_optional_int_value() - return Self(optional: Wrapped(rawValue: Int(rawValue))) - } - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Int? = asOptional?.rawValue - optionalRawValue.bridgeJSLowerReturn() +where + Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, + Wrapped.RawValue: _BridgedSwiftOptionalScalarBridge +{ + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Wrapped.RawValue.WasmCoreType + ) { + let optionalRawValue: Wrapped.RawValue? = asOptional?.rawValue + return optionalRawValue.bridgeJSLowerParameter() } -} -extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Bool { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { - let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ wrappedValue: Wrapped.RawValue.WasmCoreType + ) -> Self { + let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Bool? = asOptional?.rawValue + let optionalRawValue: Wrapped.RawValue? = asOptional?.rawValue optionalRawValue.bridgeJSLowerReturn() } } extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Float { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Float32 +where + Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: _BridgedSwiftRawValueEnum, Wrapped: RawRepresentable, + Wrapped.RawValue: _BridgedSwiftStackType, + Wrapped.RawValue: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, + Wrapped.RawValue.WasmCoreType == Int64 +{ + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Int64 ) { switch asOptional { case .none: - return (isSome: 0, value: 0.0) + return (isSome: 0, value: 0) case .some(let wrapped): return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Self { - let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) - return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - let isSome = _swift_js_get_optional_float_presence() + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int64) -> Self { if isSome == 0 { return Self(optional: nil) - } else { - let rawValue = _swift_js_get_optional_float_value() - return Self(optional: Wrapped(rawValue: Float(rawValue))) } + return Self(optional: Wrapped(rawValue: Wrapped.RawValue.bridgeJSLiftParameter(wrappedValue))) } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Float? = asOptional?.rawValue - optionalRawValue.bridgeJSLowerReturn() + Wrapped.bridgeJSStackPushAsOptional(asOptional) } } extension _BridgedAsOptional -where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Double { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Float64 - ) { - switch asOptional { - case .none: - return (isSome: 0, value: 0.0) - case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Self { - let optionalRawValue = Optional.bridgeJSLiftParameter(isSome, wrappedValue) - return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) - } - +where + Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, + Wrapped.RawValue: _BridgedSwiftOptionalScalarSideChannelBridge +{ @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { - let isSome = _swift_js_get_optional_double_presence() - if isSome == 0 { - return Self(optional: nil) - } else { - let rawValue = _swift_js_get_optional_double_value() - return Self(optional: Wrapped(rawValue: Double(rawValue))) - } - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - let optionalRawValue: Double? = asOptional?.rawValue - optionalRawValue.bridgeJSLowerReturn() + let optionalRawValue = Optional.bridgeJSLiftReturnFromSideChannel() + return Self(optional: optionalRawValue.flatMap { Wrapped(rawValue: $0) }) } } diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index 9403e3b0c..f57f91936 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -138,8 +138,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -164,8 +167,11 @@ "GlobalUtils" ], "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -476,8 +482,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, diff --git a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift index 6795c79ec..90c4b138e 100644 --- a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift @@ -190,6 +190,8 @@ final class ArraySupportTests: XCTestCase { @JS static func roundTripCaseEnumArray(_ v: [Direction]) -> [Direction] { v } @JS static func roundTripStringRawValueEnumArray(_ v: [Theme]) -> [Theme] { v } @JS static func roundTripIntRawValueEnumArray(_ v: [HttpStatus]) -> [HttpStatus] { v } + @JS static func roundTripInt64RawValueEnumArray(_ v: [FileSize]) -> [FileSize] { v } + @JS static func roundTripUInt64RawValueEnumArray(_ v: [SessionId]) -> [SessionId] { v } @JS static func roundTripStructArray(_ v: [DataPoint]) -> [DataPoint] { v } @JS static func roundTripSwiftClassArray(_ v: [Greeter]) -> [Greeter] { v } @JS static func roundTripNamespacedSwiftClassArray(_ v: [Utils.Converter]) -> [Utils.Converter] { v } @@ -202,6 +204,8 @@ final class ArraySupportTests: XCTestCase { @JS static func roundTripOptionalCaseEnumArray(_ v: [Direction?]) -> [Direction?] { v } @JS static func roundTripOptionalStringRawValueEnumArray(_ v: [Theme?]) -> [Theme?] { v } @JS static func roundTripOptionalIntRawValueEnumArray(_ v: [HttpStatus?]) -> [HttpStatus?] { v } + @JS static func roundTripOptionalInt64RawValueEnumArray(_ v: [FileSize?]) -> [FileSize?] { v } + @JS static func roundTripOptionalUInt64RawValueEnumArray(_ v: [SessionId?]) -> [SessionId?] { v } @JS static func roundTripOptionalStructArray(_ v: [DataPoint?]) -> [DataPoint?] { v } @JS static func roundTripOptionalSwiftClassArray(_ v: [Greeter?]) -> [Greeter?] { v } @JS static func roundTripOptionalJSClassArray(_ v: [ArrayElementObject?]) -> [ArrayElementObject?] { v } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index d2fe49db2..595f6c051 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -10,12 +10,6 @@ func runJsWorks() -> Void return } -@JS func roundTripInt(v: Int) -> Int { - return v -} -@JS func roundTripUInt(v: UInt) -> UInt { - return v -} @JS func roundTripFloat(v: Float) -> Float { return v } @@ -225,6 +219,19 @@ struct TestError: Error { case unknown = -1 } +@JS enum FileSize: Int64 { + case tiny = 1024 + case small = 10240 + case medium = 102400 + case large = 1048576 +} + +@JS enum SessionId: UInt64 { + case none = 0 + case active = 9876543210 + case expired = 1234567890 +} + @JS enum Precision: Float { case rough = 0.1 case normal = 0.01 @@ -281,6 +288,22 @@ struct TestError: Error { return .ok } +@JS func setFileSize(_ size: FileSize) -> FileSize { + return size +} + +@JS func getFileSize() -> FileSize { + return .small +} + +@JS func setSessionId(_ session: SessionId) -> SessionId { + return session +} + +@JS func getSessionId() -> SessionId { + return .active +} + @JS func processTheme(_ theme: Theme) -> HttpStatus { switch theme { case .light: return .ok diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e9c0e7653..e01761a8e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -2685,6 +2685,28 @@ public func _bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray() -> V #endif } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripInt64RawValueEnumArray(_: [FileSize].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripUInt64RawValueEnumArray(_: [SessionId].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_ArraySupportExports_static_roundTripStructArray") @_cdecl("bjs_ArraySupportExports_static_roundTripStructArray") public func _bjs_ArraySupportExports_static_roundTripStructArray() -> Void { @@ -2808,6 +2830,28 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArra #endif } +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalInt64RawValueEnumArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray") +@_cdecl("bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray") +public func _bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray() -> Void { + #if arch(wasm32) + let ret = ArraySupportExports.roundTripOptionalUInt64RawValueEnumArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_ArraySupportExports_static_roundTripOptionalStructArray") @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStructArray") public func _bjs_ArraySupportExports_static_roundTripOptionalStructArray() -> Void { @@ -3223,6 +3267,12 @@ extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } +extension FileSize: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension SessionId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } @@ -3935,6 +3985,116 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_se #endif } +@_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 +} + +@_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 +} + +@_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_IntegerTypesSupportExports_static_roundTripUInt16") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt16") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt16(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #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 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) + 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 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) + 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 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) + 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 + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalString") @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalString") public func _bjs_OptionalSupportExports_static_roundTripOptionalString(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { @@ -4034,6 +4194,28 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum( #endif } +@_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) + let ret = OptionalSupportExports.roundTripOptionalInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + 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 +} + @_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") public func _bjs_OptionalSupportExports_static_roundTripOptionalTSEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { @@ -5468,28 +5650,6 @@ public func _bjs_roundTripVoid() -> Void { #endif } -@_expose(wasm, "bjs_roundTripInt") -@_cdecl("bjs_roundTripInt") -public func _bjs_roundTripInt(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = roundTripInt(v: Int.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripUInt") -@_cdecl("bjs_roundTripUInt") -public func _bjs_roundTripUInt(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = roundTripUInt(v: UInt.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_roundTripFloat") @_cdecl("bjs_roundTripFloat") public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { @@ -6136,6 +6296,50 @@ public func _bjs_getHttpStatus() -> Int32 { #endif } +@_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_getFileSize") +@_cdecl("bjs_getFileSize") +public func _bjs_getFileSize() -> Int64 { + #if arch(wasm32) + let ret = getFileSize() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_setSessionId") +@_cdecl("bjs_setSessionId") +public func _bjs_setSessionId(_ session: Int64) -> Int64 { + #if arch(wasm32) + let ret = setSessionId(_: SessionId.bridgeJSLiftParameter(session)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getSessionId") +@_cdecl("bjs_getSessionId") +public func _bjs_getSessionId() -> Int64 { + #if arch(wasm32) + let ret = getSessionId() + 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 { @@ -11501,6 +11705,235 @@ func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException return Point.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripUInt_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripUInt_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt8_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt8_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt8_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt8_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripInt8_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt16_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt16_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt16_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt16_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripInt16_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt32_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt32_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt32_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt32_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripInt32_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static(_ v: Int32) -> Int32 { + return bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt64_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt64_static_extern(_ v: Int64) -> Int64 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt64_static_extern(_ v: Int64) -> Int64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt64_static(_ v: Int64) -> Int64 { + return bjs_IntegerTypesSupportImports_jsRoundTripInt64_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static") +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static_extern(_ v: Int64) -> Int64 +#else +fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static_extern(_ v: Int64) -> Int64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static(_ v: Int64) -> Int64 { + return bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static") +fileprivate func bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static_extern() -> Void +#else +fileprivate func bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static() -> Void { + return bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static_extern() +} + +func _$IntegerTypesSupportImports_jsRoundTripInt(_ v: Int) throws(JSException) -> Int { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripInt_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripUInt(_ v: UInt) throws(JSException) -> UInt { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripUInt_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripInt8(_ v: Int8) throws(JSException) -> Int8 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripInt8_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int8.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripUInt8(_ v: UInt8) throws(JSException) -> UInt8 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripUInt8_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt8.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripInt16(_ v: Int16) throws(JSException) -> Int16 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripInt16_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int16.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripUInt16(_ v: UInt16) throws(JSException) -> UInt16 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripUInt16_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt16.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripInt32(_ v: Int32) throws(JSException) -> Int32 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripInt32_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int32.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripUInt32(_ v: UInt32) throws(JSException) -> UInt32 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripUInt32_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt32.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripInt64(_ v: Int64) throws(JSException) -> Int64 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripInt64_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int64.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_jsRoundTripUInt64(_ v: UInt64) throws(JSException) -> UInt64 { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_IntegerTypesSupportImports_jsRoundTripUInt64_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return UInt64.bridgeJSLiftReturn(ret) +} + +func _$IntegerTypesSupportImports_runJsIntegerTypesSupportTests() throws(JSException) -> Void { + bjs_IntegerTypesSupportImports_runJsIntegerTypesSupportTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSClassWithArrayMembers_init") fileprivate func bjs_JSClassWithArrayMembers_init_extern() -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 8a3656b65..cd8111566 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -16,8 +16,11 @@ "label" : "_", "name" : "base", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -31,14 +34,20 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -160,8 +169,11 @@ "label" : "_", "name" : "base", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -175,14 +187,20 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -330,8 +348,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -421,8 +442,11 @@ "isStatic" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -747,15 +771,21 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -772,8 +802,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -781,15 +814,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -862,8 +901,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -888,8 +930,11 @@ "Utils" ], "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1066,8 +1111,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1083,8 +1131,11 @@ "isStatic" : false, "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1104,8 +1155,11 @@ "label" : "intValue", "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1191,8 +1245,11 @@ "isStatic" : false, "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1241,8 +1298,11 @@ "isStatic" : false, "name" : "readonlyInt", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1321,8 +1381,11 @@ "isStatic" : false, "name" : "computedReadonly", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1341,8 +1404,11 @@ "isStatic" : false, "name" : "observedProperty", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1364,8 +1430,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1373,15 +1442,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -1403,8 +1478,11 @@ "label" : "a", "name" : "a", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1412,15 +1490,21 @@ "label" : "b", "name" : "b", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -1478,8 +1562,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1568,8 +1655,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1605,8 +1695,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1665,8 +1758,11 @@ "label" : "_", "name" : "amount", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -1757,8 +1853,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -1793,8 +1892,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1884,8 +1986,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -1907,8 +2012,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -2191,8 +2299,11 @@ "label" : "by", "name" : "amount", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -2215,8 +2326,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2442,8 +2556,11 @@ "isStatic" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -2479,8 +2596,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -2808,8 +2928,11 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, { @@ -2946,8 +3069,11 @@ { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -3210,8 +3336,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -3221,8 +3350,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -3367,8 +3499,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -3915,8 +4050,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -4057,8 +4195,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -4068,8 +4209,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -4641,6 +4785,92 @@ } } }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt64RawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt64RawValueEnumArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, { "abiName" : "bjs_ArraySupportExports_static_roundTripStructArray", "effects" : { @@ -4866,8 +5096,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -4882,8 +5115,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -5157,13 +5393,13 @@ } }, { - "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalStructArray", + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "roundTripOptionalStructArray", + "name" : "roundTripOptionalInt64RawValueEnumArray", "namespace" : [ "ArraySupportExports" ], @@ -5176,8 +5412,9 @@ "_0" : { "nullable" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" } }, "_1" : "null" @@ -5192,8 +5429,9 @@ "_0" : { "nullable" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" } }, "_1" : "null" @@ -5208,13 +5446,13 @@ } }, { - "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray", + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "roundTripOptionalSwiftClassArray", + "name" : "roundTripOptionalUInt64RawValueEnumArray", "namespace" : [ "ArraySupportExports" ], @@ -5227,7 +5465,111 @@ "_0" : { "nullable" : { "_0" : { - "swiftHeapObject" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalStructArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalStructArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ArraySupportExports" + } + } + }, + { + "abiName" : "bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalSwiftClassArray", + "namespace" : [ + "ArraySupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { "_0" : "Greeter" } }, @@ -5329,8 +5671,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5344,8 +5689,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5670,8 +6018,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5694,8 +6045,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5724,8 +6078,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5780,8 +6137,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5814,8 +6174,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5849,8 +6212,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -5971,15 +6337,21 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -6109,8 +6481,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -6377,8 +6752,11 @@ "label" : "count", "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -6514,8 +6892,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -6523,8 +6904,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -6558,8 +6942,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -6570,8 +6957,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -6628,8 +7018,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -6822,6 +7215,85 @@ { "associatedValues" : [ + ], + "name" : "tiny", + "rawValue" : "1024" + }, + { + "associatedValues" : [ + + ], + "name" : "small", + "rawValue" : "10240" + }, + { + "associatedValues" : [ + + ], + "name" : "medium", + "rawValue" : "102400" + }, + { + "associatedValues" : [ + + ], + "name" : "large", + "rawValue" : "1048576" + } + ], + "emitStyle" : "const", + "name" : "FileSize", + "rawType" : "Int64", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "FileSize", + "tsFullPath" : "FileSize" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "none", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "active", + "rawValue" : "9876543210" + }, + { + "associatedValues" : [ + + ], + "name" : "expired", + "rawValue" : "1234567890" + } + ], + "emitStyle" : "const", + "name" : "SessionId", + "rawType" : "UInt64", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "SessionId", + "tsFullPath" : "SessionId" + }, + { + "cases" : [ + { + "associatedValues" : [ + ], "name" : "rough", "rawValue" : "0.1" @@ -7306,8 +7778,11 @@ "associatedValues" : [ { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -7393,8 +7868,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -7438,8 +7916,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -7497,15 +7978,21 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -7605,8 +8092,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -7624,8 +8114,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -7694,8 +8187,11 @@ }, { "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -7773,8 +8269,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -7924,15 +8423,21 @@ "label" : "_", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -8043,15 +8548,21 @@ "label" : "rootId", "name" : "rootId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -8078,15 +8589,21 @@ "label" : "graphId", "name" : "graphId", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "staticContext" : { @@ -8148,8 +8665,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -8178,8 +8698,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -8193,8 +8716,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -8294,8 +8820,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -8338,8 +8867,412 @@ } } ], - "swiftCallName" : "StaticPropertyNamespace.NestedProperties", - "tsFullPath" : "StaticPropertyNamespace.NestedProperties" + "swiftCallName" : "StaticPropertyNamespace.NestedProperties", + "tsFullPath" : "StaticPropertyNamespace.NestedProperties" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "IntegerTypesSupportExports", + "staticMethods" : [ + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripInt", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripUInt", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripInt8", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt8", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripUInt8", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt8", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripInt16", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt16", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripUInt16", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt16", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripInt32", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt32", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripUInt32", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt32", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripInt64", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt64", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + }, + { + "abiName" : "bjs_IntegerTypesSupportExports_static_roundTripUInt64", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUInt64", + "namespace" : [ + "IntegerTypesSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "IntegerTypesSupportExports" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "IntegerTypesSupportExports", + "tsFullPath" : "IntegerTypesSupportExports" }, { "cases" : [ @@ -8409,8 +9342,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -8421,8 +9357,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -8739,6 +9678,96 @@ } } }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalInt64RawValueEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, + { + "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripOptionalUInt64RawValueEnum", + "namespace" : [ + "OptionalSupportExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "OptionalSupportExports" + } + } + }, { "abiName" : "bjs_OptionalSupportExports_static_roundTripOptionalTSEnum", "effects" : { @@ -8933,8 +9962,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -8949,8 +9981,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -9664,8 +10699,11 @@ "_0" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -9737,8 +10775,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -9778,8 +10819,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -9833,56 +10877,6 @@ } } }, - { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_roundTripUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUInt", - "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "uint" : { - - } - } - } - ], - "returnType" : { - "uint" : { - - } - } - }, { "abiName" : "bjs_roundTripFloat", "effects" : { @@ -10197,8 +11191,11 @@ "type" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -10208,8 +11205,11 @@ "returnType" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -10423,8 +11423,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -10560,15 +11563,21 @@ "label" : "v", "name" : "v", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -10795,8 +11804,11 @@ "label" : "x", "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -10804,15 +11816,21 @@ "label" : "y", "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -10907,128 +11925,218 @@ "isStatic" : false, "isThrows" : false }, - "name" : "getDirection", + "name" : "getDirection", + "parameters" : [ + + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "abiName" : "bjs_processDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDirection", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "abiName" : "bjs_setTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_getTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTheme", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_setHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setHttpStatus", "parameters" : [ - + { + "label" : "_", + "name" : "status", + "type" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_getHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "getHttpStatus", "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } + ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_setFileSize", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "setFileSize", "parameters" : [ { "label" : "_", - "name" : "theme", + "name" : "size", "type" : { "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "_0" : "FileSize", + "_1" : "Int64" } } } ], "returnType" : { "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "_0" : "FileSize", + "_1" : "Int64" } } }, { - "abiName" : "bjs_getTheme", + "abiName" : "bjs_getFileSize", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getTheme", + "name" : "getFileSize", "parameters" : [ ], "returnType" : { "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "_0" : "FileSize", + "_1" : "Int64" } } }, { - "abiName" : "bjs_setHttpStatus", + "abiName" : "bjs_setSessionId", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setHttpStatus", + "name" : "setSessionId", "parameters" : [ { "label" : "_", - "name" : "status", + "name" : "session", "type" : { "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "_0" : "SessionId", + "_1" : "UInt64" } } } ], "returnType" : { "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "_0" : "SessionId", + "_1" : "UInt64" } } }, { - "abiName" : "bjs_getHttpStatus", + "abiName" : "bjs_getSessionId", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getHttpStatus", + "name" : "getSessionId", "parameters" : [ ], "returnType" : { "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "_0" : "SessionId", + "_1" : "UInt64" } } }, @@ -11185,8 +12293,11 @@ "label" : "value", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -11491,8 +12602,11 @@ "label" : "_", "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -11667,8 +12781,11 @@ "label" : "_", "name" : "code", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -11744,8 +12861,11 @@ "label" : "_", "name" : "code", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -11839,8 +12959,11 @@ "label" : "_", "name" : "count1", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -11848,8 +12971,11 @@ "label" : "_", "name" : "count2", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -11969,8 +13095,11 @@ "label" : "_", "name" : "code", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -12003,8 +13132,11 @@ "label" : "_", "name" : "code", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -12071,8 +13203,11 @@ "label" : "_", "name" : "code", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -12196,8 +13331,11 @@ "label" : "intValue", "name" : "intValue", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -12420,8 +13558,11 @@ "label" : "base", "name" : "base", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -12435,14 +13576,20 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -12960,8 +14107,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -12969,8 +14119,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13029,8 +14182,11 @@ "isReadonly" : false, "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -13051,8 +14207,11 @@ "label" : "by", "name" : "amount", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -13075,8 +14234,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13301,8 +14463,11 @@ "isReadonly" : false, "name" : "count", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13335,8 +14500,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -13439,8 +14607,11 @@ "isStatic" : false, "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13449,8 +14620,11 @@ "isStatic" : false, "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -13637,8 +14811,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -13703,8 +14880,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -13742,8 +14922,11 @@ "label" : "x", "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13751,8 +14934,11 @@ "label" : "y", "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -13769,8 +14955,11 @@ "isStatic" : false, "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13779,8 +14968,11 @@ "isStatic" : false, "name" : "y", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -13820,8 +15012,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -13852,8 +15047,11 @@ "isStatic" : false, "name" : "age", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -13971,8 +15169,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14005,8 +15206,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14064,8 +15268,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14445,8 +15652,11 @@ "isStatic" : false, "name" : "x", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14489,8 +15699,11 @@ "isStatic" : false, "name" : "quantity", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -14537,8 +15750,11 @@ "isStatic" : false, "name" : "id", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14591,8 +15807,11 @@ "isStatic" : false, "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14621,8 +15840,11 @@ } }, "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14744,8 +15966,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -14753,8 +15978,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14802,8 +16030,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -14894,8 +16125,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -14903,8 +16137,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -14916,8 +16153,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -14927,8 +16167,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -15100,8 +16343,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -15116,8 +16362,11 @@ "_0" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -15445,8 +16694,11 @@ { "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15461,14 +16713,20 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15478,8 +16736,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15621,8 +16882,11 @@ { "name" : "base", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -15636,14 +16900,20 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15729,8 +16999,11 @@ { "name" : "value", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15745,8 +17018,11 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], @@ -15762,8 +17038,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15781,19 +17060,28 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15803,8 +17091,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15822,24 +17113,36 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15849,8 +17152,11 @@ } ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -15972,8 +17278,11 @@ ], "returnType" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -16049,8 +17358,11 @@ "type" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16060,8 +17372,11 @@ "returnType" : { "dictionary" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16820,16 +18135,22 @@ { "name" : "dx", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { "name" : "dy", "type" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16848,6 +18169,278 @@ { "functions" : [ + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "IntegerTypesSupportImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "name" : "jsRoundTripInt", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "jsRoundTripUInt", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "word" + } + } + } + }, + { + "name" : "jsRoundTripInt8", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w8" + } + } + } + }, + { + "name" : "jsRoundTripUInt8", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w8" + } + } + } + }, + { + "name" : "jsRoundTripInt16", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w16" + } + } + } + }, + { + "name" : "jsRoundTripUInt16", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w16" + } + } + } + }, + { + "name" : "jsRoundTripInt32", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w32" + } + } + } + }, + { + "name" : "jsRoundTripUInt32", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w32" + } + } + } + }, + { + "name" : "jsRoundTripInt64", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + }, + { + "name" : "jsRoundTripUInt64", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : false, + "width" : "w64" + } + } + } + }, + { + "name" : "runJsIntegerTypesSupportTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, + { + "functions" : [ + ], "types" : [ { @@ -16858,8 +18451,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16885,8 +18481,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16914,8 +18513,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16925,8 +18527,11 @@ "returnType" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -16989,8 +18594,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -17034,8 +18642,11 @@ "type" : { "array" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } @@ -17221,8 +18832,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -17233,8 +18847,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "null" @@ -17249,8 +18866,11 @@ "type" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" @@ -17261,8 +18881,11 @@ "returnType" : { "nullable" : { "_0" : { - "int" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } }, "_1" : "undefined" diff --git a/Tests/BridgeJSRuntimeTests/IntegerTypesSupportTests.swift b/Tests/BridgeJSRuntimeTests/IntegerTypesSupportTests.swift new file mode 100644 index 000000000..c4ed65d0c --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/IntegerTypesSupportTests.swift @@ -0,0 +1,73 @@ +import JavaScriptKit +import XCTest + +@JSClass struct IntegerTypesSupportImports { + @JSFunction static func jsRoundTripInt(_ v: Int) throws(JSException) -> Int + @JSFunction static func jsRoundTripUInt(_ v: UInt) throws(JSException) -> UInt + @JSFunction static func jsRoundTripInt8(_ v: Int8) throws(JSException) -> Int8 + @JSFunction static func jsRoundTripUInt8(_ v: UInt8) throws(JSException) -> UInt8 + @JSFunction static func jsRoundTripInt16(_ v: Int16) throws(JSException) -> Int16 + @JSFunction static func jsRoundTripUInt16(_ v: UInt16) throws(JSException) -> UInt16 + @JSFunction static func jsRoundTripInt32(_ v: Int32) throws(JSException) -> Int32 + @JSFunction static func jsRoundTripUInt32(_ v: UInt32) throws(JSException) -> UInt32 + @JSFunction static func jsRoundTripInt64(_ v: Int64) throws(JSException) -> Int64 + @JSFunction static func jsRoundTripUInt64(_ v: UInt64) throws(JSException) -> UInt64 + + @JSFunction static func runJsIntegerTypesSupportTests() throws(JSException) -> Void +} + +final class IntegerTypesSupportTests: XCTestCase { + func testRunJsIntegerTypesSupportTests() throws { + try IntegerTypesSupportImports.runJsIntegerTypesSupportTests() + } + + private func roundTripTest(_ fn: (T) throws -> T, _ input: [T]) throws { + for v in input { + let result = try fn(v) + XCTAssertEqual(result, v) + } + } + func testRoundTripInt() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripInt, [0, 1, -1, Int.min, Int.max]) + } + func testRoundTripUInt() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripUInt, [0, 1, UInt.max]) + } + func testRoundTripInt8() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripInt8, [0, 1, -1, Int8.min, Int8.max]) + } + func testRoundTripUInt8() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripUInt8, [0, 1, UInt8.max]) + } + func testRoundTripInt16() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripInt16, [0, 1, -1, Int16.min, Int16.max]) + } + func testRoundTripUInt16() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripUInt16, [0, 1, UInt16.max]) + } + func testRoundTripInt32() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripInt32, [0, 1, -1, Int32.min, Int32.max]) + } + func testRoundTripUInt32() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripUInt32, [0, 1, UInt32.max]) + } + func testRoundTripInt64() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripInt64, [0, 1, -1, Int64.min, Int64.max]) + } + func testRoundTripUInt64() throws { + try roundTripTest(IntegerTypesSupportImports.jsRoundTripUInt64, [0, 1, UInt64.max]) + } +} + +@JS enum IntegerTypesSupportExports { + @JS static func roundTripInt(_ v: Int) -> Int { v } + @JS static func roundTripUInt(_ v: UInt) -> UInt { v } + @JS static func roundTripInt8(_ v: Int8) -> Int8 { v } + @JS static func roundTripUInt8(_ v: UInt8) -> UInt8 { v } + @JS static func roundTripInt16(_ v: Int16) -> Int16 { v } + @JS static func roundTripUInt16(_ v: UInt16) -> UInt16 { v } + @JS static func roundTripInt32(_ v: Int32) -> Int32 { v } + @JS static func roundTripUInt32(_ v: UInt32) -> UInt32 { v } + @JS static func roundTripInt64(_ v: Int64) -> Int64 { v } + @JS static func roundTripUInt64(_ v: UInt64) -> UInt64 { v } +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs index b877e9cf2..29ce274ce 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs @@ -75,7 +75,7 @@ export function getImports(importsContext) { */ export function runJsArraySupportTests(rootExports) { const exports = rootExports.ArraySupportExports; - const { Direction, Status, Theme, HttpStatus, Greeter, Utils } = rootExports; + const { Direction, Status, Theme, HttpStatus, FileSize, SessionId, Greeter, Utils } = rootExports; // Primitive arrays assert.deepEqual(exports.roundTripIntArray([1, 2, 3, -10, 2147483647]), [1, 2, 3, -10, 2147483647]); @@ -112,6 +112,8 @@ export function runJsArraySupportTests(rootExports) { assert.deepEqual(exports.roundTripCaseEnumArray([Direction.North, Direction.South]), [Direction.North, Direction.South]); assert.deepEqual(exports.roundTripIntRawValueEnumArray([HttpStatus.Ok, HttpStatus.NotFound]), [HttpStatus.Ok, HttpStatus.NotFound]); assert.deepEqual(exports.roundTripStringRawValueEnumArray([Theme.Light, Theme.Dark]), [Theme.Light, Theme.Dark]); + assert.deepEqual(exports.roundTripInt64RawValueEnumArray([FileSize.Tiny, FileSize.Large]), [FileSize.Tiny, FileSize.Large]); + assert.deepEqual(exports.roundTripUInt64RawValueEnumArray([SessionId.None, SessionId.Active]), [SessionId.None, SessionId.Active]); // Struct arrays const points = [ @@ -172,6 +174,8 @@ export function runJsArraySupportTests(rootExports) { assert.equal(optPoints[1], null); assert.deepEqual(exports.roundTripOptionalCaseEnumArray([Direction.North, null]), [Direction.North, null]); assert.deepEqual(exports.roundTripOptionalIntRawValueEnumArray([HttpStatus.Ok, null]), [HttpStatus.Ok, null]); + assert.deepEqual(exports.roundTripOptionalInt64RawValueEnumArray([FileSize.Small, null]), [FileSize.Small, null]); + assert.deepEqual(exports.roundTripOptionalUInt64RawValueEnumArray([SessionId.Expired, null]), [SessionId.Expired, null]); assert.deepEqual(exports.roundTripOptionalJSClassArray([]), []); const optJsClassResult = exports.roundTripOptionalJSClassArray([foo1, null, foo2]); assert.equal(optJsClassResult.length, 3); @@ -205,4 +209,4 @@ export function runJsArraySupportTests(rootExports) { assert.deepEqual(exports.multiOptionalArraySecond(null, ["y"]), ["y"]); assert.deepEqual(exports.multiOptionalArrayFirst([5], null), [5]); assert.equal(exports.multiOptionalArraySecond([5], null), null); -} \ No newline at end of file +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs new file mode 100644 index 000000000..c66e1adcd --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs @@ -0,0 +1,175 @@ +// @ts-check + +import assert from 'node:assert'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["IntegerTypesSupportImports"]} + */ +export function getImports(importsContext) { + return { + jsRoundTripInt: (v) => { + return v; + }, + jsRoundTripUInt: (v) => { + return v; + }, + jsRoundTripInt8: (v) => { + return v; + }, + jsRoundTripUInt8: (v) => { + return v; + }, + jsRoundTripInt16: (v) => { + return v; + }, + jsRoundTripUInt16: (v) => { + return v; + }, + jsRoundTripInt32: (v) => { + return v; + }, + jsRoundTripUInt32: (v) => { + return v; + }, + jsRoundTripInt64: (v) => { + return v; + }, + jsRoundTripUInt64: (v) => { + return v; + }, + runJsIntegerTypesSupportTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsIntegerTypesSupportTests(exports); + }, + } +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports + */ +export function runJsIntegerTypesSupportTests(rootExports) { + const exports = rootExports.IntegerTypesSupportExports; + const int8Min = -(1 << 7); + const int8Max = (1 << 7) - 1; + const uint8Max = (1 << 8) - 1; + const int16Min = -(1 << 15); + const int16Max = (1 << 15) - 1; + const uint16Max = (1 << 16) - 1; + const int32Min = -(2 ** 31); + const int32Max = (2 ** 31) - 1; + const uint32Max = (2 ** 32) - 1; + const int64Min = -(1n << 63n); + const int64Max = (1n << 63n) - 1n; + const uint64Max = (1n << 64n) - 1n; + + for (const v of [0, 1, -1, int32Min, int32Max]) { + assert.equal(exports.roundTripInt(v), v); + } + for (const v of [0, 1, uint32Max]) { + assert.equal(exports.roundTripUInt(v), v); + } + for (const [v, expected] of [ + [int32Max + 1, int32Min], + [int32Min - 1, int32Max], + ]) { + assert.equal(exports.roundTripInt(v), expected); + } + for (const [v, expected] of [ + [-1, uint32Max], + [uint32Max + 1, 0], + ]) { + assert.equal(exports.roundTripUInt(v), expected); + } + for (const v of [0, 1, -1, int8Min, int8Max]) { + assert.equal(exports.roundTripInt8(v), v); + } + for (const v of [0, 1, uint8Max]) { + assert.equal(exports.roundTripUInt8(v), v); + } + for (const v of [0, 1, -1, int16Min, int16Max]) { + assert.equal(exports.roundTripInt16(v), v); + } + for (const v of [0, 1, uint16Max]) { + assert.equal(exports.roundTripUInt16(v), v); + } + for (const v of [0, 1, -1, int32Min, int32Max]) { + assert.equal(exports.roundTripInt32(v), v); + } + for (const v of [0, 1, uint32Max]) { + assert.equal(exports.roundTripUInt32(v), v); + } + for (const [v, expected] of [ + [int8Max + 1, -128], + [int8Min - 1, 127], + ]) { + assert.equal(exports.roundTripInt8(v), expected); + } + for (const [v, expected] of [ + [-1, 255], + [uint8Max + 1, 0], + ]) { + assert.equal(exports.roundTripUInt8(v), expected); + } + for (const [v, expected] of [ + [int16Max + 1, -32768], + [int16Min - 1, 32767], + ]) { + assert.equal(exports.roundTripInt16(v), expected); + } + for (const [v, expected] of [ + [-1, 65535], + [uint16Max + 1, 0], + ]) { + assert.equal(exports.roundTripUInt16(v), expected); + } + for (const [v, expected] of [ + [int32Max + 1, int32Min], + [int32Min - 1, int32Max], + ]) { + assert.equal(exports.roundTripInt32(v), expected); + } + for (const [v, expected] of [ + [-1, uint32Max], + [uint32Max + 1, 0], + ]) { + assert.equal(exports.roundTripUInt32(v), expected); + } + for (const v of [ + 0n, 1n, -1n, + BigInt(Number.MIN_SAFE_INTEGER), + BigInt(Number.MAX_SAFE_INTEGER), + int64Min, + int64Max, + ]) { + assert.equal(exports.roundTripInt64(v), v); + } + for (const v of [ + 0n, 1n, + BigInt(Number.MAX_SAFE_INTEGER), + uint64Max, + ]) { + assert.equal(exports.roundTripUInt64(v), v); + } + for (const v of [ + int64Max + 1n, + int64Min - 1n, + uint64Max, + uint64Max + 1n, + -(1n << 64n), + (1n << 127n) - 1n, + ]) { + assert.equal(exports.roundTripInt64(v), BigInt.asIntN(64, v)); + } + for (const v of [ + -1n, + -2n, + int64Min, + int64Max, + uint64Max + 1n, + -(1n << 64n), + (1n << 127n) - 1n, + ]) { + assert.equal(exports.roundTripUInt64(v), BigInt.asUintN(64, v)); + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index f9fa397f6..6576876da 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -5,6 +5,8 @@ import { StatusValues, ThemeValues, HttpStatusValues, + FileSizeValues, + SessionIdValues, TSDirection, TSTheme, APIResultValues, @@ -58,7 +60,7 @@ export function getImports(importsContext) { */ export function runJsOptionalSupportTests(rootExports) { const exports = rootExports.OptionalSupportExports; - const { Status, Theme, HttpStatus, Networking, ComplexResult, APIResult, Greeter, OptionalPropertyHolder, TypedPayloadResult, Direction } = rootExports; + const { Status, Theme, HttpStatus, FileSize, SessionId, Networking, ComplexResult, APIResult, Greeter, OptionalPropertyHolder, TypedPayloadResult, Direction } = rootExports; assert.equal(exports.roundTripOptionalString(null), null); assert.equal(exports.roundTripOptionalInt(null), null); assert.equal(exports.roundTripOptionalBool(null), null); @@ -76,6 +78,8 @@ export function runJsOptionalSupportTests(rootExports) { assert.equal(exports.roundTripOptionalCaseEnum(Status.Success), StatusValues.Success); assert.equal(exports.roundTripOptionalStringRawValueEnum(Theme.Light), ThemeValues.Light); assert.equal(exports.roundTripOptionalIntRawValueEnum(HttpStatus.Ok), HttpStatusValues.Ok); + assert.equal(exports.roundTripOptionalInt64RawValueEnum(FileSize.Tiny), FileSizeValues.Tiny); + assert.equal(exports.roundTripOptionalUInt64RawValueEnum(SessionId.Active), SessionIdValues.Active); 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); diff --git a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift index 7f9708f57..3b06901db 100644 --- a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -96,6 +96,8 @@ final class OptionalSupportTests: XCTestCase { @JS static func roundTripOptionalCaseEnum(_ v: Status?) -> Status? { v } @JS static func roundTripOptionalStringRawValueEnum(_ v: Theme?) -> Theme? { v } @JS static func roundTripOptionalIntRawValueEnum(_ v: HttpStatus?) -> HttpStatus? { v } + @JS static func roundTripOptionalInt64RawValueEnum(_ v: FileSize?) -> FileSize? { v } + @JS static func roundTripOptionalUInt64RawValueEnum(_ v: SessionId?) -> SessionId? { v } @JS static func roundTripOptionalTSEnum(_ v: TSDirection?) -> TSDirection? { v } @JS static func roundTripOptionalTSStringEnum(_ v: TSTheme?) -> TSTheme? { v } @JS static func roundTripOptionalNamespacedEnum(_ v: Networking.API.Method?) -> Networking.API.Method? { v } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index ca2da4324..265781bff 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -1,7 +1,7 @@ // @ts-check import { - DirectionValues, StatusValues, ThemeValues, HttpStatusValues, TSDirection, TSTheme, APIResultValues, ComplexResultValues, APIOptionalResultValues, StaticCalculatorValues, StaticPropertyEnumValues, PrecisionValues, TypedPayloadResultValues, AllTypesResultValues, OptionalAllTypesResultValues + DirectionValues, StatusValues, ThemeValues, HttpStatusValues, FileSizeValues, SessionIdValues, TSDirection, TSTheme, APIResultValues, ComplexResultValues, APIOptionalResultValues, StaticCalculatorValues, StaticPropertyEnumValues, PrecisionValues, TypedPayloadResultValues, AllTypesResultValues, OptionalAllTypesResultValues } from '../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; import { ImportedFoo } from './BridgeJSRuntimeTests/JavaScript/Types.mjs'; import { runJsOptionalSupportTests } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; @@ -12,6 +12,7 @@ import { getImports as getArraySupportImports, ArrayElementObject } from './Brid import { getImports as getDictionarySupportImports } from './BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs'; import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs'; import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; +import { getImports as getIntegerTypesSupportImports } from './BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { @@ -144,6 +145,7 @@ export async function setupOptions(options, context) { DictionarySupportImports: getDictionarySupportImports(importsContext), DefaultArgumentImports: getDefaultArgumentImports(importsContext), JSClassSupportImports: getJSClassSupportImports(importsContext), + IntegerTypesSupportImports: getIntegerTypesSupportImports(importsContext), }; }, addToCoreImports(importObject, importsContext) { @@ -182,12 +184,6 @@ import assert from "node:assert"; /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { exports.roundTripVoid(); - for (const v of [0, 1, -1, 2147483647, -2147483648]) { - assert.equal(exports.roundTripInt(v), v); - } - for (const v of [0, 1, 2147483647, 4294967295]) { - assert.equal(exports.roundTripUInt(v), v); - } for (const v of [ 0.0, 1.0, -1.0, NaN, @@ -534,6 +530,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.HttpStatus.NotFound, 404); assert.equal(HttpStatusValues.ServerError, 500); assert.equal(HttpStatusValues.Unknown, -1); + assert.equal(exports.FileSize.Tiny, 1024n); + assert.equal(FileSizeValues.Large, 1048576n); + assert.equal(exports.SessionId.None, 0n); + assert.equal(SessionIdValues.Active, 9876543210n); assert.equal(exports.Precision.Rough, 0.1); assert.equal(exports.Precision.Normal, 0.01); @@ -547,6 +547,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.getTheme(), ThemeValues.Light); assert.equal(exports.setHttpStatus(exports.HttpStatus.Ok), HttpStatusValues.Ok); assert.equal(exports.getHttpStatus(), exports.HttpStatus.Ok); + assert.equal(exports.setFileSize(exports.FileSize.Medium), FileSizeValues.Medium); + assert.equal(exports.getFileSize(), FileSizeValues.Small); + assert.equal(exports.setSessionId(exports.SessionId.Expired), SessionIdValues.Expired); + assert.equal(exports.getSessionId(), SessionIdValues.Active); assert.equal(exports.processTheme(exports.Theme.Light), exports.HttpStatus.Ok); assert.equal(exports.processTheme(exports.Theme.Dark), HttpStatusValues.NotFound); From abf1c88b7cbb455bcab2158b6ace30a5c7936d8c Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Mon, 16 Mar 2026 21:56:48 +0000 Subject: [PATCH 028/140] Revert "BridgeJS: Correctly emit @JS methods in extensions" (#703) Revert of https://github.com/swiftwasm/JavaScriptKit/pull/694. Required to unblock CI on https://github.com/swiftwasm/JavaScriptKit/pull/702. --- .../BridgeJSCore/SwiftToSkeleton.swift | 72 +----- .../BridgeJSCodegenTests.swift | 17 -- .../Multifile/CrossFileExtension.swift | 5 - .../Multifile/CrossFileExtensionClass.swift | 4 - .../Inputs/MacroSwift/StaticFunctions.swift | 16 -- .../Inputs/MacroSwift/SwiftClass.swift | 14 - .../Inputs/MacroSwift/SwiftStruct.swift | 23 -- .../CrossFileExtension.json | 82 ------ .../CrossFileExtension.swift | 60 ----- .../StaticFunctions.Global.json | 97 ------- .../StaticFunctions.Global.swift | 44 ---- .../BridgeJSCodegenTests/StaticFunctions.json | 97 ------- .../StaticFunctions.swift | 44 ---- .../BridgeJSCodegenTests/SwiftClass.json | 64 ----- .../BridgeJSCodegenTests/SwiftClass.swift | 44 ---- .../BridgeJSCodegenTests/SwiftStruct.json | 106 -------- .../BridgeJSCodegenTests/SwiftStruct.swift | 92 ------- .../StaticFunctions.Global.d.ts | 4 - .../StaticFunctions.Global.js | 18 -- .../BridgeJSLinkTests/StaticFunctions.d.ts | 4 - .../BridgeJSLinkTests/StaticFunctions.js | 18 -- .../BridgeJSLinkTests/SwiftClass.d.ts | 4 - .../BridgeJSLinkTests/SwiftClass.js | 22 -- .../BridgeJSLinkTests/SwiftStruct.d.ts | 8 - .../BridgeJSLinkTests/SwiftStruct.js | 42 --- .../Exporting-Swift/Exporting-Swift-Class.md | 48 ---- .../Exporting-Swift/Exporting-Swift-Enum.md | 1 - .../Exporting-Swift/Exporting-Swift-Struct.md | 1 - .../BridgeJSRuntimeTests/ExportAPITests.swift | 22 -- .../Generated/BridgeJS.swift | 169 ------------ .../Generated/JavaScript/BridgeJS.json | 242 ------------------ Tests/BridgeJSRuntimeTests/StructAPIs.swift | 28 -- Tests/prelude.mjs | 24 -- 33 files changed, 1 insertion(+), 1535 deletions(-) delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 482b1fff5..81ad32813 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -43,14 +43,12 @@ public final class SwiftToSkeleton { var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = [] var importedFiles: [ImportedFileSkeleton] = [] var exported = ExportedSkeleton(functions: [], classes: [], enums: [], exposeToGlobal: exposeToGlobal) - var exportCollectors: [ExportSwiftAPICollector] = [] for (sourceFile, inputFilePath) in sourceFiles { progress.print("Processing \(inputFilePath)") let exportCollector = ExportSwiftAPICollector(parent: self) exportCollector.walk(sourceFile) - exportCollectors.append(exportCollector) let typeNameCollector = ImportSwiftMacrosJSImportTypeNameCollector(viewMode: .sourceAccurate) typeNameCollector.walk(sourceFile) @@ -76,15 +74,7 @@ public final class SwiftToSkeleton { if !importedFile.isEmpty { importedFiles.append(importedFile) } - } - - // 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) - } - - for collector in exportCollectors { - collector.finalize(&exported) + exportCollector.finalize(&exported) } if !perSourceErrors.isEmpty { @@ -496,8 +486,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { var exportedStructNames: [String] = [] var exportedStructByName: [String: ExportedStruct] = [:] var errors: [DiagnosticError] = [] - /// Extensions collected during the walk, to be resolved after all files have been walked - var deferredExtensions: [ExtensionDeclSyntax] = [] func finalize(_ result: inout ExportedSkeleton) { result.functions.append(contentsOf: exportedFunctions) @@ -1400,64 +1388,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } - override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { - // Defer until all type declarations in the module have been collected. - deferredExtensions.append(node) - 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 { - diagnose( - node: ext.extendedType, - message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", - hint: "You can only extend `@JS` annotated types defined in the same module" - ) - } - } - } - - /// 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 - 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 }) { - diagnose( - node: ext.extendedType, - message: "Protocol extensions are not supported by BridgeJS.", - hint: "You cannot extend `@JS` protocol '\(name)' with additional members" - ) - return true - } else { - return false - } - stateStack.push(state: state) - for member in ext.memberBlock.members { - walk(member) - } - stateStack.pop() - return true - } - override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index dd0ce5d03..9754fbced 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -167,23 +167,6 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileFunctionTypes.ReverseOrder") } - @Test - func codegenCrossFileExtension() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - let classURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionClass.swift") - swiftAPI.addSourceFile( - Parser.parse(source: try String(contentsOf: classURL, encoding: .utf8)), - inputFilePath: "CrossFileExtensionClass.swift" - ) - let extensionURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtension.swift") - swiftAPI.addSourceFile( - Parser.parse(source: try String(contentsOf: extensionURL, encoding: .utf8)), - inputFilePath: "CrossFileExtension.swift" - ) - let skeleton = try swiftAPI.finalize() - try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtension") - } - @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift deleted file mode 100644 index ce9e8e2b0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift +++ /dev/null @@ -1,5 +0,0 @@ -extension Greeter { - @JS func greetFormally() -> String { - return "Good day, " + self.name + "." - } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift deleted file mode 100644 index 48625d42a..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift +++ /dev/null @@ -1,4 +0,0 @@ -@JS class Greeter { - @JS init(name: String) {} - @JS func greet() -> String { return "" } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift index 4f6296d2e..1d42cf415 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift @@ -38,19 +38,3 @@ enum APIResult { } } } - -extension MathUtils { - @JS static func divide(a: Int, b: Int) -> Int { - return a / b - } - - @JS static var pi: Double { 3.14159 } -} - -extension Calculator { - @JS static func cube(value: Int) -> Int { - return value * value * value - } - - @JS static var version: String { "1.0" } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift index 2fb050eeb..d7b5a5b8e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift @@ -12,20 +12,6 @@ } } -extension Greeter { - @JS func greetEnthusiastically() -> String { - return "Hey, " + self.name + "!!!" - } - - @JS var nameCount: Int { name.count } - - @JS static func greetAnonymously() -> String { - return "Hello." - } - - @JS static var defaultGreeting: String { "Hello, world!" } -} - @JS func takeGreeter(greeter: Greeter) { print(greeter.greet()) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 63bb0ff8d..0d84f4736 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -60,26 +60,3 @@ } @JS func roundtripContainer(_ container: Container) -> Container - -@JS struct Vector2D { - var dx: Double - var dy: Double -} - -extension Vector2D { - @JS func magnitude() -> Double { - return (dx * dx + dy * dy).squareRoot() - } - - @JS func scaled(by factor: Double) -> Vector2D { - return Vector2D(dx: dx * factor, dy: dy * factor) - } -} - -extension DataPoint { - @JS static func origin() -> DataPoint { - return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) - } - - @JS static var dimensions: Int { 2 } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json deleted file mode 100644 index f77d39ad9..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "exported" : { - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_Greeter_greetFormally", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greetFormally", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Greeter", - "properties" : [ - - ], - "swiftCallName" : "Greeter" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] - }, - "moduleName" : "TestModule" -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift deleted file mode 100644 index ab73df508..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift +++ /dev/null @@ -1,60 +0,0 @@ -@_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_greetFormally") -@_cdecl("bjs_Greeter_greetFormally") -public func _bjs_Greeter_greetFormally(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetFormally() - return ret.bridgeJSLowerReturn() - #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 { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _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/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index 7e332fe3a..c241595a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -152,64 +152,11 @@ } } } - }, - { - "abiName" : "bjs_MathUtils_static_divide", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "divide", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } } ], "name" : "MathUtils", "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "pi", - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - }, - "type" : { - "double" : { - } - } - } ], "swiftCallName" : "MathUtils" } @@ -268,54 +215,10 @@ "_0" : "Calculator" } } - }, - { - "abiName" : "bjs_Calculator_static_cube", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "cube", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - } } ], "staticProperties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "version", - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - }, - "type" : { - "string" : { - } - } - } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index d329c7a96..60d7fa83c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -44,28 +44,6 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } -@_expose(wasm, "bjs_Calculator_static_cube") -@_cdecl("bjs_Calculator_static_cube") -public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { - #if arch(wasm32) - let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Calculator_static_version_get") -@_cdecl("bjs_Calculator_static_version_get") -public func _bjs_Calculator_static_version_get() -> Void { - #if arch(wasm32) - let ret = Calculator.version - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -156,28 +134,6 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } -@_expose(wasm, "bjs_MathUtils_static_divide") -@_cdecl("bjs_MathUtils_static_divide") -public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { - #if arch(wasm32) - let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_MathUtils_static_pi_get") -@_cdecl("bjs_MathUtils_static_pi_get") -public func _bjs_MathUtils_static_pi_get() -> Float64 { - #if arch(wasm32) - let ret = MathUtils.pi - 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index 041afc2f9..7c5df25b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -152,64 +152,11 @@ } } } - }, - { - "abiName" : "bjs_MathUtils_static_divide", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "divide", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } } ], "name" : "MathUtils", "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "pi", - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - }, - "type" : { - "double" : { - } - } - } ], "swiftCallName" : "MathUtils" } @@ -268,54 +215,10 @@ "_0" : "Calculator" } } - }, - { - "abiName" : "bjs_Calculator_static_cube", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "cube", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - } } ], "staticProperties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "version", - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - }, - "type" : { - "string" : { - } - } - } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index d329c7a96..60d7fa83c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -44,28 +44,6 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } -@_expose(wasm, "bjs_Calculator_static_cube") -@_cdecl("bjs_Calculator_static_cube") -public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { - #if arch(wasm32) - let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Calculator_static_version_get") -@_cdecl("bjs_Calculator_static_version_get") -public func _bjs_Calculator_static_version_get() -> Void { - #if arch(wasm32) - let ret = Calculator.version - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -156,28 +134,6 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } -@_expose(wasm, "bjs_MathUtils_static_divide") -@_cdecl("bjs_MathUtils_static_divide") -public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { - #if arch(wasm32) - let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_MathUtils_static_pi_get") -@_cdecl("bjs_MathUtils_static_pi_get") -public func _bjs_MathUtils_static_pi_get() -> Float64 { - #if arch(wasm32) - let ret = MathUtils.pi - 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index cf5156d8d..7cebdd5e6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -63,45 +63,6 @@ } } - }, - { - "abiName" : "bjs_Greeter_greetEnthusiastically", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greetEnthusiastically", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_Greeter_static_greetAnonymously", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "greetAnonymously", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "Greeter" - } - } } ], "name" : "Greeter", @@ -113,31 +74,6 @@ "type" : { "string" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "nameCount", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "defaultGreeting", - "staticContext" : { - "className" : { - "_0" : "Greeter" - } - }, - "type" : { - "string" : { - } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index abf33ec5e..aab0eb308 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -40,28 +40,6 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameByte #endif } -@_expose(wasm, "bjs_Greeter_greetEnthusiastically") -@_cdecl("bjs_Greeter_greetEnthusiastically") -public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() - 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 { - #if arch(wasm32) - let ret = Greeter.greetAnonymously() - 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 { @@ -83,28 +61,6 @@ public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes #endif } -@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount - 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 { - #if arch(wasm32) - let ret = Greeter.defaultGreeting - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 4c36dc15c..eeb567d4a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -214,28 +214,7 @@ ] }, "methods" : [ - { - "abiName" : "bjs_DataPoint_static_origin", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "origin", - "parameters" : [ - ], - "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - }, - "staticContext" : { - "structName" : { - "_0" : "DataPoint" - } - } - } ], "name" : "DataPoint", "properties" : [ @@ -301,21 +280,6 @@ "_1" : "null" } } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "dimensions", - "staticContext" : { - "structName" : { - "_0" : "DataPoint" - } - }, - "type" : { - "int" : { - - } - } } ], "swiftCallName" : "DataPoint" @@ -636,76 +600,6 @@ } ], "swiftCallName" : "Container" - }, - { - "methods" : [ - { - "abiName" : "bjs_Vector2D_magnitude", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "magnitude", - "parameters" : [ - - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_Vector2D_scaled", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "scaled", - "parameters" : [ - { - "label" : "by", - "name" : "factor", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "Vector2D" - } - } - } - ], - "name" : "Vector2D", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "dx", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "dy", - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "Vector2D" } ] }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 9f671c711..236937db9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -66,28 +66,6 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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 -} - extension Address: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { let zipCode = Optional.bridgeJSStackPop() @@ -455,76 +433,6 @@ fileprivate func _bjs_struct_lift_Container_extern() -> Int32 { return _bjs_struct_lift_Container_extern() } -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_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 -} - -@_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 -} - @_expose(wasm, "bjs_roundtrip") @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { 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..a2f1c7d6d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -22,8 +22,6 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; - cube(value: number): number; - readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -55,8 +53,6 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 42e25545e..073784583 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -304,14 +304,6 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } - static divide(a, b) { - const ret = instance.exports.bjs_MathUtils_static_divide(a, b); - return ret; - } - static get pi() { - const ret = instance.exports.bjs_MathUtils_static_pi_get(); - return ret; - } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -329,16 +321,6 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; - }, - cube: function(value) { - const ret = instance.exports.bjs_Calculator_static_cube(value); - return ret; - }, - get version() { - instance.exports.bjs_Calculator_static_version_get(); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index c9cb26910..e938ddb9a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -22,8 +22,6 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; - cube(value: number): number; - readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -45,8 +43,6 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 4cf9615fb..173bd6c27 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -304,14 +304,6 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } - static divide(a, b) { - const ret = instance.exports.bjs_MathUtils_static_divide(a, b); - return ret; - } - static get pi() { - const ret = instance.exports.bjs_MathUtils_static_pi_get(); - return ret; - } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -323,16 +315,6 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; - }, - cube: function(value) { - const ret = instance.exports.bjs_Calculator_static_cube(value); - return ret; - }, - get version() { - instance.exports.bjs_Calculator_static_version_get(); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 6d590950c..05fc97fee 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -14,9 +14,7 @@ export interface SwiftHeapObject { export interface Greeter extends SwiftHeapObject { greet(): string; changeName(name: string): void; - greetEnthusiastically(): string; name: string; - readonly nameCount: number; } export interface PublicGreeter extends SwiftHeapObject { } @@ -25,8 +23,6 @@ export interface PackageGreeter extends SwiftHeapObject { export type Exports = { Greeter: { new(name: string): Greeter; - greetAnonymously(): string; - readonly defaultGreeting: string; } PublicGreeter: { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index cf9faa707..4dd231e0e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -289,18 +289,6 @@ export async function createInstantiator(options, swift) { const nameId = swift.memory.retain(nameBytes); instance.exports.bjs_Greeter_changeName(this.pointer, nameId, nameBytes.length); } - greetEnthusiastically() { - instance.exports.bjs_Greeter_greetEnthusiastically(this.pointer); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - static greetAnonymously() { - instance.exports.bjs_Greeter_static_greetAnonymously(); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } get name() { instance.exports.bjs_Greeter_name_get(this.pointer); const ret = tmpRetString; @@ -312,16 +300,6 @@ export async function createInstantiator(options, swift) { const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); } - get nameCount() { - const ret = instance.exports.bjs_Greeter_nameCount_get(this.pointer); - return ret; - } - static get defaultGreeting() { - instance.exports.bjs_Greeter_static_defaultGreeting_get(); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } } class PublicGreeter extends SwiftHeapObject { static __construct(ptr) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index bf4ebc71f..4a61a26e3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -43,12 +43,6 @@ export interface Container { object: any; optionalObject: any | null; } -export interface Vector2D { - dx: number; - dy: number; - magnitude(): number; - scaled(factor: number): Vector2D; -} export type PrecisionObject = typeof PrecisionValues; /// Represents a Swift heap object like a class instance or an actor instance. @@ -71,8 +65,6 @@ export type Exports = { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index a60615686..4334bec62 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -220,29 +220,6 @@ export async function createInstantiator(options, swift) { return { object: value, optionalObject: optValue }; } }); - const __bjs_createVector2DHelpers = () => ({ - 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.Vector2D.lower(this); - const ret = instance.exports.bjs_Vector2D_magnitude(); - return ret; - }.bind(instance1); - instance1.scaled = function(factor) { - structHelpers.Vector2D.lower(this); - const ret = instance.exports.bjs_Vector2D_scaled(factor); - const structValue = structHelpers.Vector2D.lift(); - return structValue; - }.bind(instance1); - return instance1; - } - }); return { /** @@ -360,13 +337,6 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Container.lift(); return swift.memory.retain(value); } - bjs["swift_js_struct_lower_Vector2D"] = function(objectId) { - structHelpers.Vector2D.lower(swift.memory.getObject(objectId)); - } - bjs["swift_js_struct_lift_Vector2D"] = function() { - const value = structHelpers.Vector2D.lift(); - return swift.memory.retain(value); - } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -558,9 +528,6 @@ export async function createInstantiator(options, swift) { const ContainerHelpers = __bjs_createContainerHelpers(); structHelpers.Container = ContainerHelpers; - const Vector2DHelpers = __bjs_createVector2DHelpers(); - structHelpers.Vector2D = Vector2DHelpers; - const exports = { Greeter, roundtrip: function bjs_roundtrip(session) { @@ -586,15 +553,6 @@ export async function createInstantiator(options, swift) { 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() { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md index a16c81286..9cd4a2224 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -77,53 +77,6 @@ export type Exports = { } ``` -## Adding Members via Extensions - -You can add exported methods, computed properties, and static members to a `@JS` class using extensions. The extension block itself does not need `@JS` - only the individual members do: - -```swift -@JS class Greeter { - @JS var name: String - - @JS init(name: String) { - self.name = name - } - - @JS func greet() -> String { - return "Hello, " + self.name + "!" - } -} - -extension Greeter { - @JS func greetEnthusiastically() -> String { - return "Hey, " + self.name + "!!!" - } - - @JS var nameCount: Int { name.count } - - @JS static func greetAnonymously() -> String { - return "Hello." - } - - @JS static var defaultGreeting: String { "Hello, world!" } -} -``` - -This also works across files within the same module: - -```swift -// GreeterExtension.swift -extension Greeter { - @JS func greetFormally() -> String { - return "Good day, " + self.name + "." - } -} -``` - -All `@JS`-annotated members in extensions are merged into the same generated TypeScript interface as the original class declaration. - -> Note: Extensions must target `@JS`-annotated types from the same module. - ## How It Works Classes use **reference semantics** when crossing the Swift/JavaScript boundary: @@ -150,6 +103,5 @@ This differs from structs, which use copy semantics and transfer data by value. | Static / class properties: `static var`, `class let` | ✅ (See )| | Methods: `func` | ✅ (See ) | | Static/class methods: `static func`, `class func` | ✅ (See ) | -| Extension methods/properties | ✅ | | Subscripts: `subscript()` | ❌ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md index 68996b27b..2220d457c 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md @@ -514,5 +514,4 @@ This differs from classes, which use reference semantics and share state across | Associated values: `JSObject` | ✅ | | Associated values: Arrays | ✅ | | Associated values: Optionals of all supported types | ✅ | -| Extension static functions/properties | ✅ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md index c4a9524d9..32bb79ed3 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md @@ -165,7 +165,6 @@ This differs from classes, which use reference semantics and share state across | Instance methods | ✅ | | Static methods | ✅ | | Static properties | ✅ | -| Extension methods/properties | ✅ | | Property observers (`willSet`, `didSet`) | ❌ | | Generics | ❌ | | Conformances | ❌ | diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 171d0dd3a..595f6c051 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -144,20 +144,6 @@ struct TestError: Error { } } -extension Greeter { - @JS func greetEnthusiastically() -> String { - return "Hey, \(name)!!!" - } - - @JS var nameCount: Int { name.count } - - @JS static func greetAnonymously() -> String { - return "Hello." - } - - @JS static var defaultGreeting: String { "Hello, world!" } -} - @JS func takeGreeter(g: Greeter, name: String) { g.changeName(name: name) } @@ -271,14 +257,6 @@ extension Greeter { case auto = "auto" } -extension StaticCalculator { - @JS static func doubleValue(_ value: Int) -> Int { - return value * 2 - } - - @JS static var version: String { "1.0" } -} - @JS func setDirection(_ direction: Direction) -> Direction { return direction } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index b54106be9..e01761a8e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3726,28 +3726,6 @@ public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { #endif } -@_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 = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) - 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 { - #if arch(wasm32) - 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 { @@ -4695,28 +4673,6 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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 -} - extension PublicPoint: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { let y = Int.bridgeJSStackPop() @@ -5518,87 +5474,6 @@ public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { #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 { - #if arch(wasm32) - let ret = Vector2D(dx: Double.bridgeJSLiftParameter(dx), dy: Double.bridgeJSLiftParameter(dy)) - 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 { - #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().magnitude() - 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 { - #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) - 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() @@ -7527,28 +7402,6 @@ public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> #endif } -@_expose(wasm, "bjs_Greeter_greetEnthusiastically") -@_cdecl("bjs_Greeter_greetEnthusiastically") -public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() - 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 { - #if arch(wasm32) - let ret = Greeter.greetAnonymously() - 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 { @@ -7581,28 +7434,6 @@ public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { #endif } -@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount - 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 { - #if arch(wasm32) - let ret = Greeter.defaultGreeting - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 484620191..cd8111566 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -729,45 +729,6 @@ "useJSTypedClosure" : false } } - }, - { - "abiName" : "bjs_Greeter_greetEnthusiastically", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greetEnthusiastically", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_Greeter_static_greetAnonymously", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "greetAnonymously", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "Greeter" - } - } } ], "name" : "Greeter", @@ -789,31 +750,6 @@ "type" : { "string" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "nameCount", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "defaultGreeting", - "staticContext" : { - "className" : { - "_0" : "Greeter" - } - }, - "type" : { - "string" : { - } } } @@ -8509,54 +8445,10 @@ "_0" : "StaticCalculator" } } - }, - { - "abiName" : "bjs_StaticCalculator_static_doubleValue", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "doubleValue", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "StaticCalculator" - } - } } ], "staticProperties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "version", - "staticContext" : { - "enumName" : { - "_0" : "StaticCalculator" - } - }, - "type" : { - "string" : { - } - } - } ], "swiftCallName" : "StaticCalculator", "tsFullPath" : "StaticCalculator" @@ -14947,28 +14839,7 @@ ] }, "methods" : [ - { - "abiName" : "bjs_DataPoint_static_origin", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "origin", - "parameters" : [ - ], - "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - }, - "staticContext" : { - "structName" : { - "_0" : "DataPoint" - } - } - } ], "name" : "DataPoint", "properties" : [ @@ -15034,21 +14905,6 @@ "_1" : "null" } } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "dimensions", - "staticContext" : { - "structName" : { - "_0" : "DataPoint" - } - }, - "type" : { - "int" : { - - } - } } ], "swiftCallName" : "DataPoint" @@ -16025,104 +15881,6 @@ ], "swiftCallName" : "ConfigStruct" }, - { - "constructor" : { - "abiName" : "bjs_Vector2D_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "dx", - "name" : "dx", - "type" : { - "double" : { - - } - } - }, - { - "label" : "dy", - "name" : "dy", - "type" : { - "double" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Vector2D_magnitude", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "magnitude", - "parameters" : [ - - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_Vector2D_scaled", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "scaled", - "parameters" : [ - { - "label" : "by", - "name" : "factor", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "Vector2D" - } - } - } - ], - "name" : "Vector2D", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "dx", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "dy", - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "Vector2D" - }, { "methods" : [ diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index daa7ad1e2..0a05a517d 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -174,34 +174,6 @@ import JavaScriptKit } } -extension DataPoint { - @JS static func origin() -> DataPoint { - return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) - } - - @JS static var dimensions: Int { 2 } -} - -@JS struct Vector2D { - var dx: Double - var dy: Double - - @JS init(dx: Double, dy: Double) { - self.dx = dx - self.dy = dy - } -} - -extension Vector2D { - @JS func magnitude() -> Double { - return (dx * dx + dy * dy).squareRoot() - } - - @JS func scaled(by factor: Double) -> Vector2D { - return Vector2D(dx: dx * factor, dy: dy * factor) - } -} - @JS func roundTripDataPoint(_ data: DataPoint) -> DataPoint { return data } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 8eb9a0270..265781bff 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -265,12 +265,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(g.name, "Bob"); assert.equal(g.greet(), "Hello, Bob!"); - // Test class extension members - assert.equal(g.greetEnthusiastically(), "Hey, Bob!!!"); - assert.equal(g.nameCount, 3); - assert.equal(exports.Greeter.greetAnonymously(), "Hello."); - assert.equal(exports.Greeter.defaultGreeting, "Hello, world!"); - const g2 = exports.roundTripSwiftHeapObject(g) assert.equal(g2.greet(), "Hello, Bob!"); assert.equal(g2.name, "Bob"); @@ -771,10 +765,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(StaticCalculatorValues.Basic, 1); assert.equal(StaticCalculatorValues.Scientific, exports.StaticCalculator.Scientific); assert.equal(StaticCalculatorValues.Basic, exports.StaticCalculator.Basic); - - // Test enum extension static members - assert.equal(exports.StaticCalculator.doubleValue(21), 42); - assert.equal(exports.StaticCalculator.version, "1.0"); assert.equal(exports.StaticUtils.Nested.roundtrip("hello world"), "hello world"); assert.equal(exports.StaticUtils.Nested.roundtrip("test"), "test"); @@ -793,20 +783,6 @@ function testStructSupport(exports) { const data2 = { x: 0.0, y: 0.0, label: "", optCount: null, optFlag: null }; assert.deepEqual(exports.roundTripDataPoint(data2), data2); - // Test struct extension static members - const origin = exports.DataPoint.origin(); - assert.equal(origin.x, 0.0); - assert.equal(origin.y, 0.0); - assert.equal(origin.label, "origin"); - assert.equal(exports.DataPoint.dimensions, 2); - - // Test struct extension instance methods - const vec = exports.Vector2D.init(3.0, 4.0); - assert.equal(vec.magnitude(), 5.0); - const scaled = vec.scaled(2.0); - assert.equal(scaled.dx, 6.0); - assert.equal(scaled.dy, 8.0); - const publicPoint = { x: 9, y: -3 }; assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); From d6630c81cece8a263b1666f85c14ab5a8dd2ef99 Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Mon, 23 Mar 2026 19:05:48 +0000 Subject: [PATCH 029/140] Fix Embedded, bump 6.3 Swift toolchain in `test.yml` (#702) * Bump Swift toolchain snapshots in `test.yml` Bumping to `2026-03-05` for 6.3 and `2026-03-09` for `main`. * Fix concurrency `@_spi` * Downgrade `main` snapshot to old version * Fix 6.3 build error * EmbeddedApp/main.swift: Fix capitalization in print statement * Add `Examples/EmbeddedConcurrency` * EmbeddedConcurrency: don't use `-c release` for SwiftSyntax Remove the '-c release' option from the build command. * Fix warnings with untyped throws, fix npm install error # Conflicts: # Examples/EmbeddedConcurrency/build.sh * Fix formatting * Bump `build-examples` snapshots to 2026-03-14 * Use 2026-03-09 for `main` development snapshots * Add Swift version check before building examples * Exercise `await` on `JSPromise/value` * Address PR feedback * Move `EmbeddedConcurrencyApp` to fixtures * Temporarily disable `main` snapshots * Removing crashing test from the PR --- .github/workflows/test.yml | 8 +++-- .../Embedded/Sources/EmbeddedApp/main.swift | 2 +- Sources/JavaScriptEventLoop/JSSending.swift | 35 +++++++++++++++++++ .../JavaScriptEventLoop+ExecutorFactory.swift | 30 +++++++++++++--- .../JavaScriptEventLoop.swift | 7 ++-- .../BasicObjects/JSTypedArray.swift | 6 ++-- 6 files changed, 76 insertions(+), 12 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 69f63a27c..419c772a0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,7 +26,7 @@ jobs: target: "wasm32-unknown-wasip1" - os: ubuntu-24.04 toolchain: - download-url: https://download.swift.org/swift-6.3-branch/ubuntu2404/swift-6.3-DEVELOPMENT-SNAPSHOT-2025-12-05-a/swift-6.3-DEVELOPMENT-SNAPSHOT-2025-12-05-a-ubuntu24.04.tar.gz + 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" - os: ubuntu-22.04 @@ -167,14 +167,16 @@ jobs: - uses: actions/checkout@v6 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-02-02-a/swift-DEVELOPMENT-SNAPSHOT-2026-02-02-a-ubuntu22.04.tar.gz + 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 - 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: ./Utilities/build-examples.sh + - run: | + swift --version + ./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/Embedded/Sources/EmbeddedApp/main.swift b/Examples/Embedded/Sources/EmbeddedApp/main.swift index f6bf5b6ac..5e7f01a3c 100644 --- a/Examples/Embedded/Sources/EmbeddedApp/main.swift +++ b/Examples/Embedded/Sources/EmbeddedApp/main.swift @@ -3,7 +3,7 @@ import JavaScriptKit let alert = JSObject.global.alert.object! let document = JSObject.global.document -print("Hello from WASM, document title: \(document.title.string ?? "")") +print("Hello from Wasm, document title: \(document.title.string ?? "")") var count = 0 diff --git a/Sources/JavaScriptEventLoop/JSSending.swift b/Sources/JavaScriptEventLoop/JSSending.swift index 7a3750c15..fb2fb1ddf 100644 --- a/Sources/JavaScriptEventLoop/JSSending.swift +++ b/Sources/JavaScriptEventLoop/JSSending.swift @@ -226,6 +226,32 @@ extension JSSending { /// - Parameter isolation: The actor isolation context for this call, used in Swift concurrency. /// - Returns: The received object of type `T`. /// - Throws: `JSSendingError` if the sending operation fails, or `JSException` if a JavaScript error occurs. + #if compiler(>=6.4) + @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) + public func receive( + isolation: isolated (any Actor)? = #isolation, + file: StaticString = #file, + line: UInt = #line + ) async throws(JSException) -> T { + #if _runtime(_multithreaded) + let idInDestination = try await withCheckedThrowingContinuation { continuation in + let context = _JSSendingContext(continuation: continuation) + let idInSource = self.storage.idInSource + let transferring = self.storage.transferring ? [idInSource] : [] + swjs_request_sending_object( + idInSource, + transferring, + Int32(transferring.count), + self.storage.sourceTid, + Unmanaged.passRetained(context).toOpaque() + ) + } + return storage.construct(JSObject(id: idInDestination)) + #else + return storage.construct(storage.sourceObject) + #endif + } + #else @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func receive( isolation: isolated (any Actor)? = #isolation, @@ -250,6 +276,7 @@ extension JSSending { return storage.construct(storage.sourceObject) #endif } + #endif // 6.0 and below can't compile the following without a compiler crash. #if compiler(>=6.1) @@ -341,11 +368,19 @@ extension JSSending { @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) private final class _JSSendingContext: Sendable { + #if compiler(>=6.4) + let continuation: CheckedContinuation + + init(continuation: CheckedContinuation) { + self.continuation = continuation + } + #else let continuation: CheckedContinuation init(continuation: CheckedContinuation) { self.continuation = continuation } + #endif } /// Error type representing failures during JavaScript object sending operations. diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift index 7de4cb74a..a9b6091e8 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift @@ -5,10 +5,10 @@ // See: https://forums.swift.org/t/pitch-2-custom-main-and-global-executors/78437 #if compiler(>=6.3) -@_spi(ExperimentalCustomExecutors) import _Concurrency +@_spi(ExperimentalCustomExecutors) @_spi(ExperimentalScheduling) import _Concurrency #else import _Concurrency -#endif +#endif // #if compiler(>=6.3) import _CJavaScriptKit #if compiler(>=6.3) @@ -40,6 +40,22 @@ 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 + ) + #else + fatalError( + "Delayed enqueue requires Swift 6.4+ in Embedded mode" + ) + #endif // #if compiler(>=6.4) (Embedded) + #else // #if hasFeature(Embedded) let duration: Duration // Handle clocks we know if let _ = clock as? ContinuousClock { @@ -47,7 +63,9 @@ extension JavaScriptEventLoop: SchedulingExecutor { } else if let _ = clock as? SuspendingClock { duration = delay as! SuspendingClock.Duration } else { - // Hand-off the scheduling work to Clock implementation for unknown clocks + #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, @@ -55,12 +73,16 @@ extension JavaScriptEventLoop: SchedulingExecutor { 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( UnownedJob(job), withDelay: milliseconds ) + #endif // #if hasFeature(Embedded) } private static func delayInMilliseconds(from swiftDuration: Duration) -> Double { @@ -111,4 +133,4 @@ extension JavaScriptEventLoop: ExecutorFactory { } } -#endif // compiler(>=6.3) +#endif // #if compiler(>=6.3) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift index aebc90d65..aec1441a5 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift @@ -123,13 +123,16 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { private static func installGlobalExecutorIsolated() { guard !didInstallGlobalExecutor else { return } didInstallGlobalExecutor = true - #if compiler(>=6.3) + #if compiler(>=6.3) && !hasFeature(Embedded) if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999, *) { // For Swift 6.3 and above, we can use the new `ExecutorFactory` API _Concurrency._createExecutors(factory: JavaScriptEventLoop.self) } #else - // For Swift 6.1 and below, we need to install the global executor by hook API + // For Swift 6.1 and below, or 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. installByLegacyHook() #endif } diff --git a/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift b/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift index dceecf5bf..0ad7b235a 100644 --- a/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift +++ b/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift @@ -98,7 +98,7 @@ public final class JSTypedArray: JSBridgedClass, ExpressibleByArrayLiter /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. - public func withUnsafeBytes(_ body: (UnsafeBufferPointer) throws -> R) rethrows -> R { + public func withUnsafeBytes(_ body: (UnsafeBufferPointer) throws(E) -> R) throws(E) -> R { let buffer = UnsafeMutableBufferPointer.allocate(capacity: length) defer { buffer.deallocate() } copyMemory(to: buffer) @@ -121,7 +121,9 @@ public final class JSTypedArray: JSBridgedClass, ExpressibleByArrayLiter /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body`async closure parameter. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - public func withUnsafeBytesAsync(_ body: (UnsafeBufferPointer) async throws -> R) async rethrows -> R { + public func withUnsafeBytesAsync( + _ body: (UnsafeBufferPointer) async throws(E) -> R + ) async throws(E) -> R { let buffer = UnsafeMutableBufferPointer.allocate(capacity: length) defer { buffer.deallocate() } copyMemory(to: buffer) From c36a7422659cfcf017d6f673b03cf70e134c9d59 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Mon, 23 Mar 2026 20:32:53 +0000 Subject: [PATCH 030/140] Gate `ExperimentalCustomExecutors` usage behind Swift 6.4 compiler check (#705) Gate `ExperimentalCustomExecutors` usage behind Swift 6.4 for non-Wasm targets Seems like it's dropped in Swift 6.3 rc shipped along with Xcode 26.4 RC in the last minute --- .../JavaScriptEventLoop+ExecutorFactory.swift | 8 ++++---- Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift index a9b6091e8..0d2010016 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift @@ -4,14 +4,14 @@ // See: https://github.com/swiftlang/swift/pull/80266 // See: https://forums.swift.org/t/pitch-2-custom-main-and-global-executors/78437 -#if compiler(>=6.3) +#if compiler(>=6.4) || (swift(>=6.3) && arch(wasm32)) @_spi(ExperimentalCustomExecutors) @_spi(ExperimentalScheduling) import _Concurrency #else import _Concurrency -#endif // #if compiler(>=6.3) +#endif // #if compiler(>=6.4) || (swift(>=6.3) && arch(wasm32)) import _CJavaScriptKit -#if compiler(>=6.3) +#if compiler(>=6.4) || (swift(>=6.3) && arch(wasm32)) // MARK: - MainExecutor Implementation // MainExecutor is used by the main actor to execute tasks on the main thread @@ -133,4 +133,4 @@ extension JavaScriptEventLoop: ExecutorFactory { } } -#endif // #if compiler(>=6.3) +#endif // #if compiler(>=6.4) || (swift(>=6.3) && arch(wasm32)) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift index aec1441a5..5fc267ddc 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift @@ -1,5 +1,5 @@ import JavaScriptKit -#if compiler(>=6.3) +#if compiler(>=6.4) || (swift(>=6.3) && arch(wasm32)) @_spi(ExperimentalCustomExecutors) import _Concurrency #else import _Concurrency @@ -123,9 +123,9 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { private static func installGlobalExecutorIsolated() { guard !didInstallGlobalExecutor else { return } didInstallGlobalExecutor = true - #if compiler(>=6.3) && !hasFeature(Embedded) + #if (compiler(>=6.4) || (swift(>=6.3) && arch(wasm32))) && !hasFeature(Embedded) if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999, *) { - // For Swift 6.3 and above, we can use the new `ExecutorFactory` API + // For Swift 6.4 and above, we can use the new `ExecutorFactory` API _Concurrency._createExecutors(factory: JavaScriptEventLoop.self) } #else From 7be7d4e9d821e7d7147a85bd89755cbc3aea7970 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 24 Mar 2026 08:44:14 +0100 Subject: [PATCH 031/140] BridgeJS: Re-land extension method support (reverted in #703) (#706) * BridgeJS: Correctly emit @JS methods in extensions * BridgeJS: Improve test coverage for @JS methods and properties in extensions * Fix formatting * Update test code to avoid accidentally introduced failure * Fix CI: update snapshots, formatting, runtime test, add docs and review feedback * BridgeJS: Regenerate snapshots and runtime bindings against current main --------- Co-authored-by: William Taylor Co-authored-by: Max Desiatov --- .../BridgeJSCore/SwiftToSkeleton.swift | 72 ++++- .../BridgeJSCodegenTests.swift | 17 ++ .../Multifile/CrossFileExtension.swift | 5 + .../Multifile/CrossFileExtensionClass.swift | 4 + .../Inputs/MacroSwift/StaticFunctions.swift | 16 ++ .../Inputs/MacroSwift/SwiftClass.swift | 14 + .../Inputs/MacroSwift/SwiftStruct.swift | 23 ++ .../CrossFileExtension.json | 82 ++++++ .../CrossFileExtension.swift | 63 +++++ .../StaticFunctions.Global.json | 112 ++++++++ .../StaticFunctions.Global.swift | 44 +++ .../BridgeJSCodegenTests/StaticFunctions.json | 112 ++++++++ .../StaticFunctions.swift | 44 +++ .../BridgeJSCodegenTests/SwiftClass.json | 67 +++++ .../BridgeJSCodegenTests/SwiftClass.swift | 44 +++ .../BridgeJSCodegenTests/SwiftStruct.json | 109 ++++++++ .../BridgeJSCodegenTests/SwiftStruct.swift | 92 +++++++ .../StaticFunctions.Global.d.ts | 4 + .../StaticFunctions.Global.js | 18 ++ .../BridgeJSLinkTests/StaticFunctions.d.ts | 4 + .../BridgeJSLinkTests/StaticFunctions.js | 18 ++ .../BridgeJSLinkTests/SwiftClass.d.ts | 4 + .../BridgeJSLinkTests/SwiftClass.js | 22 ++ .../BridgeJSLinkTests/SwiftStruct.d.ts | 8 + .../BridgeJSLinkTests/SwiftStruct.js | 42 +++ .../Exporting-Swift/Exporting-Swift-Class.md | 48 ++++ .../Exporting-Swift/Exporting-Swift-Enum.md | 1 + .../Exporting-Swift/Exporting-Swift-Struct.md | 1 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 22 ++ .../Generated/BridgeJS.swift | 169 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 254 ++++++++++++++++++ Tests/BridgeJSRuntimeTests/StructAPIs.swift | 28 ++ Tests/prelude.mjs | 24 ++ 33 files changed, 1586 insertions(+), 1 deletion(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 81ad32813..482b1fff5 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -43,12 +43,14 @@ public final class SwiftToSkeleton { var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = [] var importedFiles: [ImportedFileSkeleton] = [] var exported = ExportedSkeleton(functions: [], classes: [], enums: [], exposeToGlobal: exposeToGlobal) + var exportCollectors: [ExportSwiftAPICollector] = [] for (sourceFile, inputFilePath) in sourceFiles { progress.print("Processing \(inputFilePath)") let exportCollector = ExportSwiftAPICollector(parent: self) exportCollector.walk(sourceFile) + exportCollectors.append(exportCollector) let typeNameCollector = ImportSwiftMacrosJSImportTypeNameCollector(viewMode: .sourceAccurate) typeNameCollector.walk(sourceFile) @@ -74,7 +76,15 @@ public final class SwiftToSkeleton { if !importedFile.isEmpty { importedFiles.append(importedFile) } - exportCollector.finalize(&exported) + } + + // 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) + } + + for collector in exportCollectors { + collector.finalize(&exported) } if !perSourceErrors.isEmpty { @@ -486,6 +496,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { var exportedStructNames: [String] = [] var exportedStructByName: [String: ExportedStruct] = [:] var errors: [DiagnosticError] = [] + /// Extensions collected during the walk, to be resolved after all files have been walked + var deferredExtensions: [ExtensionDeclSyntax] = [] func finalize(_ result: inout ExportedSkeleton) { result.functions.append(contentsOf: exportedFunctions) @@ -1388,6 +1400,64 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } + override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { + // Defer until all type declarations in the module have been collected. + deferredExtensions.append(node) + 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 { + diagnose( + node: ext.extendedType, + message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", + hint: "You can only extend `@JS` annotated types defined in the same module" + ) + } + } + } + + /// 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 + 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 }) { + diagnose( + node: ext.extendedType, + message: "Protocol extensions are not supported by BridgeJS.", + hint: "You cannot extend `@JS` protocol '\(name)' with additional members" + ) + return true + } else { + return false + } + stateStack.push(state: state) + for member in ext.memberBlock.members { + walk(member) + } + stateStack.pop() + return true + } + override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 9754fbced..dd0ce5d03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -167,6 +167,23 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileFunctionTypes.ReverseOrder") } + @Test + func codegenCrossFileExtension() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let classURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionClass.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classURL, encoding: .utf8)), + inputFilePath: "CrossFileExtensionClass.swift" + ) + let extensionURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtension.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: extensionURL, encoding: .utf8)), + inputFilePath: "CrossFileExtension.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtension") + } + @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift new file mode 100644 index 000000000..ce9e8e2b0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtension.swift @@ -0,0 +1,5 @@ +extension Greeter { + @JS func greetFormally() -> String { + return "Good day, " + self.name + "." + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift new file mode 100644 index 000000000..48625d42a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionClass.swift @@ -0,0 +1,4 @@ +@JS class Greeter { + @JS init(name: String) {} + @JS func greet() -> String { return "" } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift index 1d42cf415..4f6296d2e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift @@ -38,3 +38,19 @@ enum APIResult { } } } + +extension MathUtils { + @JS static func divide(a: Int, b: Int) -> Int { + return a / b + } + + @JS static var pi: Double { 3.14159 } +} + +extension Calculator { + @JS static func cube(value: Int) -> Int { + return value * value * value + } + + @JS static var version: String { "1.0" } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift index d7b5a5b8e..2fb050eeb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift @@ -12,6 +12,20 @@ } } +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, " + self.name + "!!!" + } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } +} + @JS func takeGreeter(greeter: Greeter) { print(greeter.greet()) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 0d84f4736..63bb0ff8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -60,3 +60,26 @@ } @JS func roundtripContainer(_ container: Container) -> Container + +@JS struct Vector2D { + var dx: Double + var dy: Double +} + +extension Vector2D { + @JS func magnitude() -> Double { + return (dx * dx + dy * dy).squareRoot() + } + + @JS func scaled(by factor: Double) -> Vector2D { + return Vector2D(dx: dx * factor, dy: dy * factor) + } +} + +extension DataPoint { + @JS static func origin() -> DataPoint { + return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) + } + + @JS static var dimensions: Int { 2 } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json new file mode 100644 index 000000000..f77d39ad9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json @@ -0,0 +1,82 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_greetFormally", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetFormally", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + + ], + "swiftCallName" : "Greeter" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift new file mode 100644 index 000000000..521e8b595 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift @@ -0,0 +1,63 @@ +@_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_greetFormally") +@_cdecl("bjs_Greeter_greetFormally") +public func _bjs_Greeter_greetFormally(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetFormally() + return ret.bridgeJSLowerReturn() + #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/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index c241595a3..e20af8a3b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -152,11 +152,73 @@ } } } + }, + { + "abiName" : "bjs_MathUtils_static_divide", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "divide", + "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" + } + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } } ], "name" : "MathUtils", "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "pi", + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + }, + "type" : { + "double" : { + } + } + } ], "swiftCallName" : "MathUtils" } @@ -215,10 +277,60 @@ "_0" : "Calculator" } } + }, + { + "abiName" : "bjs_Calculator_static_cube", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "cube", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 60d7fa83c..d329c7a96 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -44,6 +44,28 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_cube") +@_cdecl("bjs_Calculator_static_cube") +public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Calculator_static_version_get") +@_cdecl("bjs_Calculator_static_version_get") +public func _bjs_Calculator_static_version_get() -> Void { + #if arch(wasm32) + let ret = Calculator.version + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -134,6 +156,28 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } +@_expose(wasm, "bjs_MathUtils_static_divide") +@_cdecl("bjs_MathUtils_static_divide") +public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathUtils_static_pi_get") +@_cdecl("bjs_MathUtils_static_pi_get") +public func _bjs_MathUtils_static_pi_get() -> Float64 { + #if arch(wasm32) + let ret = MathUtils.pi + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index 7c5df25b7..ded6f7602 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -152,11 +152,73 @@ } } } + }, + { + "abiName" : "bjs_MathUtils_static_divide", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "divide", + "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" + } + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } } ], "name" : "MathUtils", "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "pi", + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + }, + "type" : { + "double" : { + } + } + } ], "swiftCallName" : "MathUtils" } @@ -215,10 +277,60 @@ "_0" : "Calculator" } } + }, + { + "abiName" : "bjs_Calculator_static_cube", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "cube", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Calculator", "tsFullPath" : "Calculator" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 60d7fa83c..d329c7a96 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -44,6 +44,28 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_Calculator_static_cube") +@_cdecl("bjs_Calculator_static_cube") +public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Calculator_static_version_get") +@_cdecl("bjs_Calculator_static_version_get") +public func _bjs_Calculator_static_version_get() -> Void { + #if arch(wasm32) + let ret = Calculator.version + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension APIResult: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { @@ -134,6 +156,28 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 #endif } +@_expose(wasm, "bjs_MathUtils_static_divide") +@_cdecl("bjs_MathUtils_static_divide") +public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathUtils_static_pi_get") +@_cdecl("bjs_MathUtils_static_pi_get") +public func _bjs_MathUtils_static_pi_get() -> Float64 { + #if arch(wasm32) + let ret = MathUtils.pi + 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 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index 7cebdd5e6..6ab78c82c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -63,6 +63,45 @@ } } + }, + { + "abiName" : "bjs_Greeter_greetEnthusiastically", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetEnthusiastically", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_static_greetAnonymously", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "greetAnonymously", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + } } ], "name" : "Greeter", @@ -74,6 +113,34 @@ "type" : { "string" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "nameCount", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + }, + "type" : { + "string" : { + } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index aab0eb308..abf33ec5e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -40,6 +40,28 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameByte #endif } +@_expose(wasm, "bjs_Greeter_greetEnthusiastically") +@_cdecl("bjs_Greeter_greetEnthusiastically") +public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + 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 { + #if arch(wasm32) + let ret = Greeter.greetAnonymously() + 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 { @@ -61,6 +83,28 @@ public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes #endif } +@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount + 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 { + #if arch(wasm32) + let ret = Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index eeb567d4a..4c1ef582b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -214,7 +214,28 @@ ] }, "methods" : [ + { + "abiName" : "bjs_DataPoint_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + } + } ], "name" : "DataPoint", "properties" : [ @@ -280,6 +301,24 @@ "_1" : "null" } } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "dimensions", + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "swiftCallName" : "DataPoint" @@ -600,6 +639,76 @@ } ], "swiftCallName" : "Container" + }, + { + "methods" : [ + { + "abiName" : "bjs_Vector2D_magnitude", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "magnitude", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_Vector2D_scaled", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "scaled", + "parameters" : [ + { + "label" : "by", + "name" : "factor", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + } + ], + "name" : "Vector2D", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Vector2D" } ] }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 236937db9..9f671c711 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -66,6 +66,28 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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 +} + extension Address: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { let zipCode = Optional.bridgeJSStackPop() @@ -433,6 +455,76 @@ fileprivate func _bjs_struct_lift_Container_extern() -> Int32 { return _bjs_struct_lift_Container_extern() } +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_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 +} + +@_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 +} + @_expose(wasm, "bjs_roundtrip") @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { 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 a2f1c7d6d..5916e1648 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -22,6 +22,8 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; + cube(value: number): number; + readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -53,6 +55,8 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 073784583..42e25545e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -304,6 +304,14 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } + static divide(a, b) { + const ret = instance.exports.bjs_MathUtils_static_divide(a, b); + return ret; + } + static get pi() { + const ret = instance.exports.bjs_MathUtils_static_pi_get(); + return ret; + } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -321,6 +329,16 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; + }, + cube: function(value) { + const ret = instance.exports.bjs_Calculator_static_cube(value); + return ret; + }, + get version() { + instance.exports.bjs_Calculator_static_version_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index e938ddb9a..c9cb26910 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -22,6 +22,8 @@ export type APIResultTag = export type CalculatorObject = typeof CalculatorValues & { square(value: number): number; + cube(value: number): number; + readonly version: string; }; export type APIResultObject = typeof APIResultValues & { @@ -43,6 +45,8 @@ export type Exports = { 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 173bd6c27..4cf9615fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -304,6 +304,14 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_MathUtils_multiply(this.pointer, x, y); return ret; } + static divide(a, b) { + const ret = instance.exports.bjs_MathUtils_static_divide(a, b); + return ret; + } + static get pi() { + const ret = instance.exports.bjs_MathUtils_static_pi_get(); + return ret; + } } const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); enumHelpers.APIResult = APIResultHelpers; @@ -315,6 +323,16 @@ export async function createInstantiator(options, swift) { square: function(value) { const ret = instance.exports.bjs_Calculator_static_square(value); return ret; + }, + cube: function(value) { + const ret = instance.exports.bjs_Calculator_static_cube(value); + return ret; + }, + get version() { + instance.exports.bjs_Calculator_static_version_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; } }, APIResult: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 05fc97fee..6d590950c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -14,7 +14,9 @@ export interface SwiftHeapObject { export interface Greeter extends SwiftHeapObject { greet(): string; changeName(name: string): void; + greetEnthusiastically(): string; name: string; + readonly nameCount: number; } export interface PublicGreeter extends SwiftHeapObject { } @@ -23,6 +25,8 @@ export interface PackageGreeter extends SwiftHeapObject { export type Exports = { Greeter: { new(name: string): Greeter; + greetAnonymously(): string; + readonly defaultGreeting: string; } PublicGreeter: { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 4dd231e0e..cf9faa707 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -289,6 +289,18 @@ export async function createInstantiator(options, swift) { const nameId = swift.memory.retain(nameBytes); instance.exports.bjs_Greeter_changeName(this.pointer, nameId, nameBytes.length); } + greetEnthusiastically() { + instance.exports.bjs_Greeter_greetEnthusiastically(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + static greetAnonymously() { + instance.exports.bjs_Greeter_static_greetAnonymously(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } get name() { instance.exports.bjs_Greeter_name_get(this.pointer); const ret = tmpRetString; @@ -300,6 +312,16 @@ export async function createInstantiator(options, swift) { const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); } + get nameCount() { + const ret = instance.exports.bjs_Greeter_nameCount_get(this.pointer); + return ret; + } + static get defaultGreeting() { + instance.exports.bjs_Greeter_static_defaultGreeting_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } } class PublicGreeter extends SwiftHeapObject { static __construct(ptr) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 4a61a26e3..bf4ebc71f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -43,6 +43,12 @@ export interface Container { object: any; optionalObject: any | null; } +export interface Vector2D { + dx: number; + dy: number; + magnitude(): number; + scaled(factor: number): Vector2D; +} export type PrecisionObject = typeof PrecisionValues; /// Represents a Swift heap object like a class instance or an actor instance. @@ -65,6 +71,8 @@ export type Exports = { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 4334bec62..a60615686 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -220,6 +220,29 @@ export async function createInstantiator(options, swift) { return { object: value, optionalObject: optValue }; } }); + const __bjs_createVector2DHelpers = () => ({ + 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.Vector2D.lower(this); + const ret = instance.exports.bjs_Vector2D_magnitude(); + return ret; + }.bind(instance1); + instance1.scaled = function(factor) { + structHelpers.Vector2D.lower(this); + const ret = instance.exports.bjs_Vector2D_scaled(factor); + const structValue = structHelpers.Vector2D.lift(); + return structValue; + }.bind(instance1); + return instance1; + } + }); return { /** @@ -337,6 +360,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Container.lift(); return swift.memory.retain(value); } + bjs["swift_js_struct_lower_Vector2D"] = function(objectId) { + structHelpers.Vector2D.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Vector2D"] = function() { + const value = structHelpers.Vector2D.lift(); + return swift.memory.retain(value); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -528,6 +558,9 @@ export async function createInstantiator(options, swift) { const ContainerHelpers = __bjs_createContainerHelpers(); structHelpers.Container = ContainerHelpers; + const Vector2DHelpers = __bjs_createVector2DHelpers(); + structHelpers.Vector2D = Vector2DHelpers; + const exports = { Greeter, roundtrip: function bjs_roundtrip(session) { @@ -553,6 +586,15 @@ export async function createInstantiator(options, swift) { 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() { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md index 9cd4a2224..a16c81286 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -77,6 +77,53 @@ export type Exports = { } ``` +## Adding Members via Extensions + +You can add exported methods, computed properties, and static members to a `@JS` class using extensions. The extension block itself does not need `@JS` - only the individual members do: + +```swift +@JS class Greeter { + @JS var name: String + + @JS init(name: String) { + self.name = name + } + + @JS func greet() -> String { + return "Hello, " + self.name + "!" + } +} + +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, " + self.name + "!!!" + } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } +} +``` + +This also works across files within the same module: + +```swift +// GreeterExtension.swift +extension Greeter { + @JS func greetFormally() -> String { + return "Good day, " + self.name + "." + } +} +``` + +All `@JS`-annotated members in extensions are merged into the same generated TypeScript interface as the original class declaration. + +> Note: Extensions must target `@JS`-annotated types from the same module. + ## How It Works Classes use **reference semantics** when crossing the Swift/JavaScript boundary: @@ -103,5 +150,6 @@ This differs from structs, which use copy semantics and transfer data by value. | Static / class properties: `static var`, `class let` | ✅ (See )| | Methods: `func` | ✅ (See ) | | Static/class methods: `static func`, `class func` | ✅ (See ) | +| Extension methods/properties | ✅ | | Subscripts: `subscript()` | ❌ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md index 2220d457c..68996b27b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md @@ -514,4 +514,5 @@ This differs from classes, which use reference semantics and share state across | Associated values: `JSObject` | ✅ | | Associated values: Arrays | ✅ | | Associated values: Optionals of all supported types | ✅ | +| Extension static functions/properties | ✅ | | Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md index 32bb79ed3..c4a9524d9 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md @@ -165,6 +165,7 @@ This differs from classes, which use reference semantics and share state across | Instance methods | ✅ | | Static methods | ✅ | | Static properties | ✅ | +| Extension methods/properties | ✅ | | Property observers (`willSet`, `didSet`) | ❌ | | Generics | ❌ | | Conformances | ❌ | diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 595f6c051..171d0dd3a 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -144,6 +144,20 @@ struct TestError: Error { } } +extension Greeter { + @JS func greetEnthusiastically() -> String { + return "Hey, \(name)!!!" + } + + @JS var nameCount: Int { name.count } + + @JS static func greetAnonymously() -> String { + return "Hello." + } + + @JS static var defaultGreeting: String { "Hello, world!" } +} + @JS func takeGreeter(g: Greeter, name: String) { g.changeName(name: name) } @@ -257,6 +271,14 @@ struct TestError: Error { case auto = "auto" } +extension StaticCalculator { + @JS static func doubleValue(_ value: Int) -> Int { + return value * 2 + } + + @JS static var version: String { "1.0" } +} + @JS func setDirection(_ direction: Direction) -> Direction { return direction } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e01761a8e..b54106be9 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3726,6 +3726,28 @@ public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { #endif } +@_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 = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) + 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 { + #if arch(wasm32) + 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 { @@ -4673,6 +4695,28 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #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 +} + extension PublicPoint: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { let y = Int.bridgeJSStackPop() @@ -5474,6 +5518,87 @@ public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { #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 { + #if arch(wasm32) + let ret = Vector2D(dx: Double.bridgeJSLiftParameter(dx), dy: Double.bridgeJSLiftParameter(dy)) + 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 { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().magnitude() + 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 { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + 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() @@ -7402,6 +7527,28 @@ public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> #endif } +@_expose(wasm, "bjs_Greeter_greetEnthusiastically") +@_cdecl("bjs_Greeter_greetEnthusiastically") +public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + 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 { + #if arch(wasm32) + let ret = Greeter.greetAnonymously() + 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 { @@ -7434,6 +7581,28 @@ public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { #endif } +@_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 = Greeter.bridgeJSLiftParameter(_self).nameCount + 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 { + #if arch(wasm32) + let ret = Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Greeter_deinit") @_cdecl("bjs_Greeter_deinit") public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index cd8111566..842bcff24 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -729,6 +729,45 @@ "useJSTypedClosure" : false } } + }, + { + "abiName" : "bjs_Greeter_greetEnthusiastically", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetEnthusiastically", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_static_greetAnonymously", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "greetAnonymously", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + } } ], "name" : "Greeter", @@ -750,6 +789,34 @@ "type" : { "string" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "nameCount", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + }, + "type" : { + "string" : { + } } } @@ -8445,10 +8512,60 @@ "_0" : "StaticCalculator" } } + }, + { + "abiName" : "bjs_StaticCalculator_static_doubleValue", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "doubleValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" + } + } } ], "staticProperties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "version", + "staticContext" : { + "enumName" : { + "_0" : "StaticCalculator" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "StaticCalculator", "tsFullPath" : "StaticCalculator" @@ -14839,7 +14956,28 @@ ] }, "methods" : [ + { + "abiName" : "bjs_DataPoint_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + } + } ], "name" : "DataPoint", "properties" : [ @@ -14905,6 +15043,24 @@ "_1" : "null" } } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "dimensions", + "staticContext" : { + "structName" : { + "_0" : "DataPoint" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "swiftCallName" : "DataPoint" @@ -15881,6 +16037,104 @@ ], "swiftCallName" : "ConfigStruct" }, + { + "constructor" : { + "abiName" : "bjs_Vector2D_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "dx", + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "label" : "dy", + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Vector2D_magnitude", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "magnitude", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_Vector2D_scaled", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "scaled", + "parameters" : [ + { + "label" : "by", + "name" : "factor", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + } + ], + "name" : "Vector2D", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dy", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Vector2D" + }, { "methods" : [ diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index 0a05a517d..daa7ad1e2 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -174,6 +174,34 @@ import JavaScriptKit } } +extension DataPoint { + @JS static func origin() -> DataPoint { + return DataPoint(x: 0, y: 0, label: "origin", optCount: nil, optFlag: nil) + } + + @JS static var dimensions: Int { 2 } +} + +@JS struct Vector2D { + var dx: Double + var dy: Double + + @JS init(dx: Double, dy: Double) { + self.dx = dx + self.dy = dy + } +} + +extension Vector2D { + @JS func magnitude() -> Double { + return (dx * dx + dy * dy).squareRoot() + } + + @JS func scaled(by factor: Double) -> Vector2D { + return Vector2D(dx: dx * factor, dy: dy * factor) + } +} + @JS func roundTripDataPoint(_ data: DataPoint) -> DataPoint { return data } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 265781bff..8eb9a0270 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -265,6 +265,12 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(g.name, "Bob"); assert.equal(g.greet(), "Hello, Bob!"); + // Test class extension members + assert.equal(g.greetEnthusiastically(), "Hey, Bob!!!"); + assert.equal(g.nameCount, 3); + assert.equal(exports.Greeter.greetAnonymously(), "Hello."); + assert.equal(exports.Greeter.defaultGreeting, "Hello, world!"); + const g2 = exports.roundTripSwiftHeapObject(g) assert.equal(g2.greet(), "Hello, Bob!"); assert.equal(g2.name, "Bob"); @@ -765,6 +771,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(StaticCalculatorValues.Basic, 1); assert.equal(StaticCalculatorValues.Scientific, exports.StaticCalculator.Scientific); assert.equal(StaticCalculatorValues.Basic, exports.StaticCalculator.Basic); + + // Test enum extension static members + assert.equal(exports.StaticCalculator.doubleValue(21), 42); + assert.equal(exports.StaticCalculator.version, "1.0"); assert.equal(exports.StaticUtils.Nested.roundtrip("hello world"), "hello world"); assert.equal(exports.StaticUtils.Nested.roundtrip("test"), "test"); @@ -783,6 +793,20 @@ function testStructSupport(exports) { const data2 = { x: 0.0, y: 0.0, label: "", optCount: null, optFlag: null }; assert.deepEqual(exports.roundTripDataPoint(data2), data2); + // Test struct extension static members + const origin = exports.DataPoint.origin(); + assert.equal(origin.x, 0.0); + assert.equal(origin.y, 0.0); + assert.equal(origin.label, "origin"); + assert.equal(exports.DataPoint.dimensions, 2); + + // Test struct extension instance methods + const vec = exports.Vector2D.init(3.0, 4.0); + assert.equal(vec.magnitude(), 5.0); + const scaled = vec.scaled(2.0); + assert.equal(scaled.dx, 6.0); + assert.equal(scaled.dy, 8.0); + const publicPoint = { x: 9, y: -3 }; assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); From 7e242b01453f23f16df2e83b48558dc088f54ec9 Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Fri, 27 Mar 2026 09:09:32 +0000 Subject: [PATCH 032/140] BridgeJS: support imports of JS `Promise` as `async` Swift (#707) * BridgeJS: support imports of `Promise` JS as `async` Swift * E2e testing of bridging Promise returns * fix formatting * `JSTypedClosure`-based approach * Clean up `BridgeJSLink` * Fix missing `import _Concurrency` * Fix formatting * Use `JSTypedClosure` without wrapping the result value * Make closure parameters as `sending` * Check more stack ABI types * Add support for `async` in `@JSFunction` * Use namespaced import * Fix missing `fetchWeatherData` * Bring back `fetchWeatherData` * Regenerate `fetchWeatherData` bridging code * BridgeJS: Centralize closure sig collection in BridgeSkeletonWalker * BridgeJS: Stop spreading isAsync handling outside of CallJSEmission * BridgeJS: Remove error-prone default effects in thunk generation * BridgeJSLink: Centralize async handling in ImportedThunkBuilder * BridgeJS: Remove reundant returnType from `call` family of methods in ImportedThunkBuilder --------- Co-authored-by: Yuta Saito --- .../Generated/JavaScript/BridgeJS.json | 15 + .../Generated/JavaScript/BridgeJS.json | 10 + .../Sources/BridgeJSCore/ClosureCodegen.swift | 11 +- .../Sources/BridgeJSCore/ExportSwift.swift | 3 + .../Sources/BridgeJSCore/ImportTS.swift | 132 +- .../BridgeJSCore/SwiftToSkeleton.swift | 12 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 292 ++-- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 72 +- .../TS2Swift/JavaScript/src/processor.js | 33 +- .../test/__snapshots__/ts2swift.test.js.snap | 14 +- .../Inputs/MacroSwift/AsyncImport.swift | 6 + .../Inputs/MacroSwift/AsyncStaticImport.swift | 4 + .../BridgeJSCodegenTests/ArrayTypes.json | 35 + .../BridgeJSCodegenTests/AsyncImport.json | 151 ++ .../BridgeJSCodegenTests/AsyncImport.swift | 569 ++++++++ .../AsyncStaticImport.json | 67 + .../AsyncStaticImport.swift | 227 +++ .../CrossFileSkipsEmptySkeletons.json | 5 + .../BridgeJSCodegenTests/DictionaryTypes.json | 5 + .../BridgeJSCodegenTests/EnumRawType.json | 10 + .../FixedWidthIntegers.json | 40 + .../BridgeJSCodegenTests/GlobalGetter.json | 5 + .../GlobalThisImports.json | 15 + .../BridgeJSCodegenTests/ImportArray.json | 10 + .../InvalidPropertyNames.json | 25 + .../BridgeJSCodegenTests/JSClass.json | 25 + .../JSClassStaticFunctions.json | 30 + .../BridgeJSCodegenTests/JSValue.json | 10 + .../BridgeJSCodegenTests/Optionals.json | 40 + .../PrimitiveParameters.json | 5 + .../BridgeJSCodegenTests/PrimitiveReturn.json | 10 + .../ProtocolInClosure.json | 15 +- .../BridgeJSCodegenTests/StringParameter.json | 10 + .../BridgeJSCodegenTests/StringReturn.json | 5 + .../BridgeJSCodegenTests/SwiftClass.json | 10 + .../BridgeJSCodegenTests/SwiftClosure.json | 129 +- .../SwiftClosureImports.json | 16 +- .../SwiftStructImports.json | 5 + .../VoidParameterVoidReturn.json | 5 + .../BridgeJSLinkTests/AsyncImport.d.ts | 23 + .../BridgeJSLinkTests/AsyncImport.js | 507 +++++++ .../BridgeJSLinkTests/AsyncStaticImport.d.ts | 23 + .../BridgeJSLinkTests/AsyncStaticImport.js | 402 ++++++ .../JavaScriptKit/BridgeJSIntrinsics.swift | 89 ++ .../AsyncImportTests.swift | 85 ++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 2 +- .../Generated/BridgeJS.Macros.swift | 13 +- .../Generated/BridgeJS.swift | 1087 +++++++++++++- .../Generated/JavaScript/BridgeJS.json | 1254 ++++++++++++++--- .../JavaScript/AsyncImportTests.mjs | 46 + Tests/BridgeJSRuntimeTests/bridge-js.d.ts | 7 + Tests/prelude.mjs | 16 +- 52 files changed, 5227 insertions(+), 410 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncStaticImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js create mode 100644 Tests/BridgeJSRuntimeTests/AsyncImportTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index 95c4ac18e..b2c33ac01 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -2839,6 +2839,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "benchmarkHelperNoop", "parameters" : [ @@ -2850,6 +2855,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "benchmarkHelperNoopWithNumber", "parameters" : [ { @@ -2868,6 +2878,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "benchmarkRunner", "parameters" : [ { diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 60eb694ff..1a21916ee 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -242,6 +242,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "createTS2Swift", "parameters" : [ @@ -260,6 +265,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "convert", "parameters" : [ { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 142050f56..f3ed97ba3 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -12,7 +12,10 @@ public struct ClosureCodegen { public init() {} private func swiftClosureType(for signature: ClosureSignature) -> String { - let closureParams = signature.parameters.map { "\($0.closureSwiftType)" }.joined(separator: ", ") + let sendingPrefix = signature.sendingParameters ? "sending " : "" + let closureParams = signature.parameters.map { "\(sendingPrefix)\($0.closureSwiftType)" }.joined( + separator: ", " + ) let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") let swiftReturnType = signature.returnType.closureSwiftType return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" @@ -29,6 +32,7 @@ public struct ClosureCodegen { let builder = try ImportTS.CallJSEmission( moduleName: "bjs", abiName: externName, + effects: Effects(isAsync: signature.isAsync, isThrows: signature.isThrows), returnType: signature.returnType, context: .exportSwift ) @@ -185,11 +189,10 @@ public struct ClosureCodegen { } public func renderSupport(for skeleton: BridgeJSSkeleton) throws -> String? { - let collector = ClosureSignatureCollectorVisitor() - var walker = BridgeTypeWalker(visitor: collector) + let collector = ClosureSignatureCollectorVisitor(moduleName: skeleton.moduleName) + var walker = BridgeSkeletonWalker(visitor: collector) walker.walk(skeleton) let closureSignatures = walker.visitor.signatures - guard !closureSignatures.isEmpty else { return nil } var decls: [DeclSyntax] = [] diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 5b6c7d1ff..ca7bdc3c2 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -1228,6 +1228,7 @@ struct ProtocolCodegen { let builder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: "_extern_\(method.name)", + effects: method.effects, returnType: method.returnType, context: .exportSwift ) @@ -1327,6 +1328,7 @@ struct ProtocolCodegen { let getterBuilder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: getterAbiName, + effects: Effects(isAsync: false, isThrows: false), returnType: property.type, context: .exportSwift ) @@ -1360,6 +1362,7 @@ struct ProtocolCodegen { let setterBuilder = try ImportTS.CallJSEmission( moduleName: moduleName, abiName: setterAbiName, + effects: Effects(isAsync: false, isThrows: false), returnType: .void, context: .exportSwift ) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 1d1fe3aa9..536c7eeab 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -66,9 +66,11 @@ public struct ImportTS { _ getter: ImportedGetterSkeleton, topLevelDecls: inout [DeclSyntax] ) throws -> [DeclSyntax] { + let effects = Effects(isAsync: false, isThrows: true) let builder = try CallJSEmission( moduleName: moduleName, abiName: getter.abiName(context: nil), + effects: effects, returnType: getter.type ) try builder.call() @@ -78,7 +80,8 @@ public struct ImportTS { builder.renderThunkDecl( name: "_$\(getter.name)_get", parameters: [], - returnType: getter.type + returnType: getter.type, + effects: effects ) .with(\.leadingTrivia, Self.renderDocumentation(documentation: getter.documentation)) ] @@ -94,13 +97,14 @@ public struct ImportTS { let abiName: String let moduleName: String + let effects: Effects let returnType: BridgeType let context: BridgeContext var body = CodeFragmentPrinter() var abiParameterForwardings: [String] = [] var abiParameterSignatures: [(name: String, type: WasmCoreType)] = [] - var abiReturnType: WasmCoreType? + 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 @@ -111,15 +115,29 @@ public struct ImportTS { private var borrowedArguments: [BorrowedArgument] = [] private let needsReturnVariable: Bool - init(moduleName: String, abiName: String, returnType: BridgeType, context: BridgeContext = .importTS) throws { + init( + moduleName: String, + abiName: String, + effects: Effects, + returnType: BridgeType, + context: BridgeContext = .importTS + ) throws { self.moduleName = moduleName self.abiName = abiName + self.effects = effects self.returnType = returnType self.context = context let liftingInfo = try returnType.liftingReturnInfo(context: context) - needsReturnVariable = - !(returnType == .void || returnType.usesSideChannelForOptionalReturn() - || liftingInfo.valueToLift == nil) + if effects.isAsync || returnType == .void || returnType.usesSideChannelForOptionalReturn() { + abiReturnType = nil + } else { + abiReturnType = liftingInfo.valueToLift + } + needsReturnVariable = abiReturnType != nil + + if effects.isAsync { + prependClosureCallbackParams() + } } func lowerParameter(param: Parameter) throws { @@ -212,6 +230,15 @@ public struct ImportTS { } } + /// Prepends `resolveRef: Int32, rejectRef: Int32` parameters to the ABI parameter list. + /// + /// Used for async imports where the JS side receives closure-backed + /// resolve/reject callbacks as object references. + private func prependClosureCallbackParams() { + abiParameterSignatures.insert(contentsOf: [("resolveRef", .i32), ("rejectRef", .i32)], at: 0) + abiParameterForwardings.insert(contentsOf: ["resolveRef", "rejectRef"], at: 0) + } + func call() throws { for stmt in stackLoweringStmts { body.write(stmt.description) @@ -243,26 +270,32 @@ public struct ImportTS { } } - // Add exception check for ImportTS context - if context == .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 { body.write("if let error = _swift_js_take_exception() { throw error }") } } func liftReturnValue() throws { + if effects.isAsync { + liftAsyncReturnValue() + } else { + try liftSyncReturnValue() + } + } + + private func liftSyncReturnValue() throws { let liftingInfo = try returnType.liftingReturnInfo(context: context) if returnType == .void { - abiReturnType = nil return } if returnType.usesSideChannelForOptionalReturn() { // Side channel returns: extern function returns Void, value is retrieved via side channel - abiReturnType = nil body.write("return \(returnType.swiftType).bridgeJSLiftReturnFromSideChannel()") } else { - abiReturnType = liftingInfo.valueToLift let liftExpr: String switch returnType { case .closure(let signature, _): @@ -278,12 +311,38 @@ public struct ImportTS { } } - func assignThis(returnType: BridgeType) { - guard case .jsObject = returnType else { - preconditionFailure("assignThis can only be called with a jsObject return type") + private func liftAsyncReturnValue() { + // For async imports, the extern function takes leading `resolveRef: Int32, rejectRef: Int32` + // and returns void. The JS side calls the resolve/reject closures when the Promise settles. + // The resolve closure is typed to match the return type, so the ABI conversion is handled + // by the existing closure codegen infrastructure — no manual JSValue-to-type switch needed. + + // Wrap the existing body (parameter lowering + extern call) in _bjs_awaitPromise + let innerBody = body + body = CodeFragmentPrinter() + + 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" + ) + } 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" + ) + } + body.indent { + body.write(lines: innerBody.lines) + } + body.write("}") + + if returnType != .void { + body.write("return resolved") } - abiReturnType = .i32 - body.write("self.jsObject = JSObject(id: UInt32(bitPattern: ret))") } func renderImportDecl() -> DeclSyntax { @@ -299,9 +358,13 @@ public struct ImportTS { return "\(raw: printer.lines.joined(separator: "\n"))" } - func renderThunkDecl(name: String, parameters: [Parameter], returnType: BridgeType) -> DeclSyntax { + func renderThunkDecl( + name: String, + parameters: [Parameter], + returnType: BridgeType, + effects: Effects + ) -> DeclSyntax { let printer = CodeFragmentPrinter() - let effects = Effects(isAsync: false, isThrows: true) let signature = SwiftSignatureBuilder.buildFunctionSignature( parameters: parameters, returnType: returnType, @@ -362,6 +425,7 @@ public struct ImportTS { let builder = try CallJSEmission( moduleName: moduleName, abiName: function.abiName(context: nil), + effects: function.effects, returnType: function.returnType ) for param in function.parameters { @@ -374,7 +438,8 @@ public struct ImportTS { builder.renderThunkDecl( name: Self.thunkName(function: function), parameters: function.parameters, - returnType: function.returnType + returnType: function.returnType, + effects: function.effects ) .with(\.leadingTrivia, Self.renderDocumentation(documentation: function.documentation)) ] @@ -388,6 +453,7 @@ public struct ImportTS { let builder = try CallJSEmission( moduleName: moduleName, abiName: method.abiName(context: type), + effects: method.effects, returnType: method.returnType ) try builder.lowerParameter(param: selfParameter) @@ -401,14 +467,20 @@ public struct ImportTS { builder.renderThunkDecl( name: Self.thunkName(type: type, method: method), parameters: [selfParameter] + method.parameters, - returnType: method.returnType + returnType: method.returnType, + effects: method.effects ) ] } func renderStaticMethod(method: ImportedFunctionSkeleton) throws -> [DeclSyntax] { let abiName = method.abiName(context: type, operation: "static") - let builder = try CallJSEmission(moduleName: moduleName, abiName: abiName, returnType: method.returnType) + let builder = try CallJSEmission( + moduleName: moduleName, + abiName: abiName, + effects: method.effects, + returnType: method.returnType + ) for param in method.parameters { try builder.lowerParameter(param: param) } @@ -419,15 +491,18 @@ public struct ImportTS { builder.renderThunkDecl( name: Self.thunkName(type: type, method: method), parameters: method.parameters, - returnType: method.returnType + returnType: method.returnType, + effects: method.effects ) ] } func renderConstructorDecl(constructor: ImportedConstructorSkeleton) throws -> [DeclSyntax] { + let effects = Effects(isAsync: false, isThrows: true) let builder = try CallJSEmission( moduleName: moduleName, abiName: constructor.abiName(context: type), + effects: effects, returnType: .jsObject(nil) ) for param in constructor.parameters { @@ -440,15 +515,18 @@ public struct ImportTS { builder.renderThunkDecl( name: Self.thunkName(type: type), parameters: constructor.parameters, - returnType: .jsObject(nil) + returnType: .jsObject(nil), + effects: effects ) ] } func renderGetterDecl(getter: ImportedGetterSkeleton) throws -> DeclSyntax { + let effects = Effects(isAsync: false, isThrows: true) let builder = try CallJSEmission( moduleName: moduleName, abiName: getter.abiName(context: type), + effects: effects, returnType: getter.type ) try builder.lowerParameter(param: selfParameter) @@ -459,15 +537,18 @@ public struct ImportTS { builder.renderThunkDecl( name: Self.thunkName(type: type, propertyName: getter.name, operation: "get"), parameters: [selfParameter], - returnType: getter.type + returnType: getter.type, + effects: effects ) ) } func renderSetterDecl(setter: ImportedSetterSkeleton) throws -> DeclSyntax { + let effects = Effects(isAsync: false, isThrows: true) let builder = try CallJSEmission( moduleName: moduleName, abiName: setter.abiName(context: type), + effects: effects, returnType: .void ) let newValue = Parameter(label: nil, name: "newValue", type: setter.type) @@ -487,7 +568,8 @@ public struct ImportTS { return builder.renderThunkDecl( name: Self.thunkName(type: type, propertyName: propertyNameForThunk, operation: "set"), parameters: [selfParameter, newValue], - returnType: .void + returnType: .void, + effects: effects ) } if let constructor = type.constructor { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 482b1fff5..7b7c6ca30 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -2137,7 +2137,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let valueType: BridgeType } - /// Validates effects (throws required, async not supported) + /// Validates effects (throws required, async only supported for @JSFunction) private func validateEffects( _ effects: FunctionEffectSpecifiersSyntax?, node: some SyntaxProtocol, @@ -2153,7 +2153,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { ) return nil } - if effects.isAsync { + if effects.isAsync && attributeName != "JSFunction" { errors.append( DiagnosticError( node: node, @@ -2490,7 +2490,12 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { _ jsFunction: AttributeSyntax, _ node: FunctionDeclSyntax, ) -> ImportedFunctionSkeleton? { - guard validateEffects(node.signature.effectSpecifiers, node: node, attributeName: "JSFunction") != nil + guard + let effects = validateEffects( + node.signature.effectSpecifiers, + node: node, + attributeName: "JSFunction" + ) else { return nil } @@ -2516,6 +2521,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { from: from, parameters: parameters, returnType: returnType, + effects: effects, documentation: nil ) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index f69a4b266..63b628eb3 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -636,11 +636,10 @@ public struct BridgeJSLink { for unified in skeletons { let moduleName = unified.moduleName - let collector = ClosureSignatureCollectorVisitor() - var walker = BridgeTypeWalker(visitor: collector) + let collector = ClosureSignatureCollectorVisitor(moduleName: moduleName) + var walker = BridgeSkeletonWalker(visitor: collector) walker.walk(unified) let closureSignatures = walker.visitor.signatures - guard !closureSignatures.isEmpty else { continue } intrinsicRegistry.register(name: "swiftClosureHelpers") { helperPrinter in @@ -742,7 +741,12 @@ public struct BridgeJSLink { signature: ClosureSignature, functionName: String ) throws -> [String] { - let thunkBuilder = ImportedThunkBuilder(context: .exportSwift, intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: signature.isAsync, isThrows: signature.isThrows), + returnType: signature.returnType, + context: .exportSwift, + intrinsicRegistry: intrinsicRegistry + ) thunkBuilder.parameterNames.append("callbackId") thunkBuilder.body.write("const callback = \(JSGlueVariableScope.reservedSwift).memory.getObject(callbackId);") @@ -751,13 +755,9 @@ public struct BridgeJSLink { try thunkBuilder.liftParameter(param: Parameter(label: nil, name: paramName, type: paramType)) } - let returnExpr = try thunkBuilder.call(calleeExpr: "callback", returnType: signature.returnType) + try thunkBuilder.call(calleeExpr: "callback") - var functionLines = thunkBuilder.renderFunction( - name: nil, - returnExpr: returnExpr, - returnType: signature.returnType - ) + var functionLines = thunkBuilder.renderFunction(name: nil) functionLines[0] = "bjs[\"\(functionName)\"] = " + functionLines[0] return functionLines @@ -1233,7 +1233,7 @@ public struct BridgeJSLink { for method in type.methods { let methodName = method.jsName ?? method.name let methodSignature = - "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: Effects(isAsync: false, isThrows: false)));" + "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" printer.write(methodSignature) } @@ -2164,15 +2164,25 @@ extension BridgeJSLink { class ImportedThunkBuilder { let body: CodeFragmentPrinter let scope: JSGlueVariableScope + let effects: Effects + let returnType: BridgeType let context: BridgeContext var parameterNames: [String] = [] var parameterForwardings: [String] = [] + var returnExpr: String? let printContext: IntrinsicJSFragment.PrintCodeContext - init(context: BridgeContext = .importTS, intrinsicRegistry: JSIntrinsicRegistry) { + init( + effects: Effects, + returnType: BridgeType, + context: BridgeContext = .importTS, + intrinsicRegistry: JSIntrinsicRegistry + ) { self.body = CodeFragmentPrinter() self.scope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) self.context = context + self.effects = effects + self.returnType = returnType self.printContext = IntrinsicJSFragment.PrintCodeContext( scope: scope, printer: body, @@ -2202,7 +2212,15 @@ extension BridgeJSLink { parameterForwardings.append(contentsOf: liftedValues) } - func renderFunction( + func renderFunction(name: String?) -> [String] { + if effects.isAsync { + return renderAsyncFunction(name: name) + } else { + return renderSyncFunction(name: name, returnExpr: returnExpr, returnType: returnType) + } + } + + private func renderSyncFunction( name: String?, returnExpr: String?, returnType: BridgeType @@ -2232,21 +2250,44 @@ extension BridgeJSLink { return printer.lines } - func call(name: String, fromObjectExpr: String, returnType: BridgeType) throws -> String? { + /// Renders an async import function with resolve/reject closure refs. + /// + /// The generated function takes `resolveRef` and `rejectRef` as the first parameters, + /// looks up the resolve/reject closures from memory, and executes the body which + /// chains `.then(resolve, reject)` on the import's returned Promise. + private func renderAsyncFunction(name: String?) -> [String] { + let printer = CodeFragmentPrinter() + let allParams = ["resolveRef", "rejectRef"] + parameterNames + printer.write("function\(name.map { " \($0)" } ?? "")(\(allParams.joined(separator: ", "))) {") + printer.indent { + let s = JSGlueVariableScope.reservedSwift + printer.write("const resolve = \(s).memory.getObject(resolveRef);") + printer.write("const reject = \(s).memory.getObject(rejectRef);") + printer.write(contentsOf: body) + } + printer.write("}") + return printer.lines + } + + func call(name: String, fromObjectExpr: String) throws { let calleeExpr = Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: name) - return try self.call(calleeExpr: calleeExpr, returnType: returnType) + return try self.call(calleeExpr: calleeExpr) } - func call(name: String, returnType: BridgeType) throws -> String? { - return try call(name: name, fromObjectExpr: "imports", returnType: returnType) + func call(name: String) throws { + return try call(name: name, fromObjectExpr: "imports") } - func call(calleeExpr: String, returnType: BridgeType) throws -> String? { + func call(calleeExpr: String) throws { let callExpr = "\(calleeExpr)(\(parameterForwardings.joined(separator: ", ")))" - return try self.call(callExpr: callExpr, returnType: returnType) + try self.call(callExpr: callExpr) } - private func call(callExpr: String, returnType: BridgeType) throws -> String? { + private func call(callExpr: String) throws { + if effects.isAsync { + body.write("\(callExpr).then(resolve, reject);") + return + } let loweringFragment = try IntrinsicJSFragment.lowerReturn(type: returnType, context: context) let returnExpr: String? if loweringFragment.parameters.count == 0 { @@ -2257,43 +2298,49 @@ extension BridgeJSLink { body.write("let \(resultVariable) = \(callExpr);") returnExpr = resultVariable } - return try lowerReturnValue( + self.returnExpr = try lowerReturnValue( returnType: returnType, returnExpr: returnExpr, loweringFragment: loweringFragment ) } - func callConstructor(jsName: String, swiftTypeName: String, fromObjectExpr: String) throws -> String? { + func callConstructor(jsName: String, swiftTypeName: String, fromObjectExpr: String) throws { let ctorExpr = Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: jsName) let call = "new \(ctorExpr)(\(parameterForwardings.joined(separator: ", ")))" let type: BridgeType = .jsObject(swiftTypeName) let loweringFragment = try IntrinsicJSFragment.lowerReturn(type: type, context: context) - return try lowerReturnValue(returnType: type, returnExpr: call, loweringFragment: loweringFragment) + self.returnExpr = try lowerReturnValue( + returnType: type, + returnExpr: call, + loweringFragment: loweringFragment + ) } - func callConstructor(jsName: String, swiftTypeName: String) throws -> String? { + func callConstructor(jsName: String, swiftTypeName: String) throws { return try callConstructor(jsName: jsName, swiftTypeName: swiftTypeName, fromObjectExpr: "imports") } - func callMethod(name: String, returnType: BridgeType) throws -> String? { + func callMethod(name: String) throws { let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) - return try call( - calleeExpr: calleeExpr, - returnType: returnType - ) + return try call(calleeExpr: calleeExpr) } - func callStaticMethod(on objectExpr: String, name: String, returnType: BridgeType) throws -> String? { + /// Generates an async method call with resolve/reject closure refs. + func callAsyncMethod(name: String) { + let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) - return try call( - calleeExpr: calleeExpr, - returnType: returnType - ) + let callExpr = "\(calleeExpr)(\(parameterForwardings.joined(separator: ", ")))" + body.write("\(callExpr).then(resolve, reject);") + } + + func callStaticMethod(on objectExpr: String, name: String) throws { + let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) + return try call(calleeExpr: calleeExpr) } - func callPropertyGetter(name: String, returnType: BridgeType) throws -> String? { + func callPropertyGetter(name: String) throws { let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" let accessExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) if context == .exportSwift, returnType.usesSideChannelForOptionalReturn() { @@ -2308,24 +2355,22 @@ extension BridgeJSLink { let fragment = try IntrinsicJSFragment.protocolPropertyOptionalToSideChannel(wrappedType: wrappedType) _ = try fragment.printCode([resultVar], printContext) - - return nil // Side-channel types return nil (no direct return value) + // Side-channel types return nil (no direct return value) + self.returnExpr = nil + return } - return try call( - callExpr: accessExpr, - returnType: returnType - ) + return try call(callExpr: accessExpr) } - func callPropertySetter(name: String, returnType: BridgeType) { + func callPropertySetter(name: String) { let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" let accessExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) let call = "\(accessExpr) = \(parameterForwardings.joined(separator: ", "))" body.write("\(call);") } - func getImportProperty(name: String, fromObjectExpr: String, returnType: BridgeType) throws -> String? { + func getImportProperty(name: String, fromObjectExpr: String, returnType: BridgeType) throws { if returnType == .void { throw BridgeJSLinkError(message: "Void is not supported for imported JS properties") } @@ -2343,14 +2388,14 @@ extension BridgeJSLink { returnExpr = resultVariable } - return try lowerReturnValue( + self.returnExpr = try lowerReturnValue( returnType: returnType, returnExpr: returnExpr, loweringFragment: loweringFragment ) } - func getImportProperty(name: String, returnType: BridgeType) throws -> String? { + func getImportProperty(name: String, returnType: BridgeType) throws { return try getImportProperty(name: name, fromObjectExpr: "imports", returnType: returnType) } @@ -3118,27 +3163,23 @@ extension BridgeJSLink { importObjectBuilder: ImportObjectBuilder, function: ImportedFunctionSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: function.effects, + returnType: function.returnType, + intrinsicRegistry: intrinsicRegistry + ) for param in function.parameters { try thunkBuilder.liftParameter(param: param) } let jsName = function.jsName ?? function.name let importRootExpr = function.from == .global ? "globalThis" : "imports" - let returnExpr = try thunkBuilder.call( - name: jsName, - fromObjectExpr: importRootExpr, - returnType: function.returnType - ) - let funcLines = thunkBuilder.renderFunction( - name: function.abiName(context: nil), - returnExpr: returnExpr, - returnType: function.returnType - ) - let effects = Effects(isAsync: false, isThrows: false) + + try thunkBuilder.call(name: jsName, fromObjectExpr: importRootExpr) + let funcLines = thunkBuilder.renderFunction(name: function.abiName(context: nil)) if function.from == nil { importObjectBuilder.appendDts( [ - "\(renderTSPropertyName(jsName))\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: effects));" + "\(renderTSPropertyName(jsName))\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ] ) } @@ -3149,20 +3190,20 @@ extension BridgeJSLink { importObjectBuilder: ImportObjectBuilder, getter: ImportedGetterSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: getter.type, + intrinsicRegistry: intrinsicRegistry + ) let jsName = getter.jsName ?? getter.name let importRootExpr = getter.from == .global ? "globalThis" : "imports" - let returnExpr = try thunkBuilder.getImportProperty( + try thunkBuilder.getImportProperty( name: jsName, fromObjectExpr: importRootExpr, returnType: getter.type ) let abiName = getter.abiName(context: nil) - let funcLines = thunkBuilder.renderFunction( - name: abiName, - returnExpr: returnExpr, - returnType: getter.type - ) + let funcLines = thunkBuilder.renderFunction(name: abiName) if getter.from == nil { importObjectBuilder.appendDts(["readonly \(renderTSPropertyName(jsName)): \(getter.type.tsType);"]) } @@ -3186,10 +3227,7 @@ extension BridgeJSLink { getter: getter, abiName: getterAbiName, emitCall: { thunkBuilder in - return try thunkBuilder.callPropertyGetter( - name: getter.jsName ?? getter.name, - returnType: getter.type - ) + return try thunkBuilder.callPropertyGetter(name: getter.jsName ?? getter.name) } ) importObjectBuilder.assignToImportObject(name: getterAbiName, function: js) @@ -3205,8 +3243,7 @@ extension BridgeJSLink { try thunkBuilder.liftParameter( param: Parameter(label: nil, name: "newValue", type: setter.type) ) - thunkBuilder.callPropertySetter(name: setter.jsName ?? setter.name, returnType: setter.type) - return nil + thunkBuilder.callPropertySetter(name: setter.jsName ?? setter.name) } ) importObjectBuilder.assignToImportObject(name: setterAbiName, function: js) @@ -3231,7 +3268,7 @@ extension BridgeJSLink { for method in type.staticMethods { let methodName = method.jsName ?? method.name let signature = - "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: Effects(isAsync: false, isThrows: false)));" + "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" dtsPrinter.write(signature) } } @@ -3250,55 +3287,54 @@ extension BridgeJSLink { type: ImportedTypeSkeleton, constructor: ImportedConstructorSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: BridgeType.jsObject(type.name), + intrinsicRegistry: intrinsicRegistry + ) for param in constructor.parameters { try thunkBuilder.liftParameter(param: param) } - let returnType = BridgeType.jsObject(type.name) let importRootExpr = type.from == .global ? "globalThis" : "imports" - let returnExpr = try thunkBuilder.callConstructor( + try thunkBuilder.callConstructor( jsName: type.jsName ?? type.name, swiftTypeName: type.name, fromObjectExpr: importRootExpr ) let abiName = constructor.abiName(context: type) - let funcLines = thunkBuilder.renderFunction( - name: abiName, - returnExpr: returnExpr, - returnType: returnType - ) + let funcLines = thunkBuilder.renderFunction(name: abiName) importObjectBuilder.assignToImportObject(name: abiName, function: funcLines) } func renderImportedGetter( getter: ImportedGetterSkeleton, abiName: String, - emitCall: (ImportedThunkBuilder) throws -> String? + emitCall: (ImportedThunkBuilder) throws -> Void ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) - thunkBuilder.liftSelf() - let returnExpr = try emitCall(thunkBuilder) - let funcLines = thunkBuilder.renderFunction( - name: abiName, - returnExpr: returnExpr, - returnType: getter.type + let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: getter.type, + intrinsicRegistry: intrinsicRegistry ) + thunkBuilder.liftSelf() + try emitCall(thunkBuilder) + let funcLines = thunkBuilder.renderFunction(name: abiName) return (funcLines, []) } func renderImportedSetter( setter: ImportedSetterSkeleton, abiName: String, - emitCall: (ImportedThunkBuilder) throws -> String? + emitCall: (ImportedThunkBuilder) throws -> Void ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) - thunkBuilder.liftSelf() - let returnExpr = try emitCall(thunkBuilder) - let funcLines = thunkBuilder.renderFunction( - name: abiName, - returnExpr: returnExpr, - returnType: .void + let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: .void, + intrinsicRegistry: intrinsicRegistry ) + thunkBuilder.liftSelf() + try emitCall(thunkBuilder) + let funcLines = thunkBuilder.renderFunction(name: abiName) return (funcLines, []) } @@ -3306,7 +3342,11 @@ extension BridgeJSLink { context: ImportedTypeSkeleton, method: ImportedFunctionSkeleton ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: method.effects, + returnType: method.returnType, + intrinsicRegistry: intrinsicRegistry + ) for param in method.parameters { try thunkBuilder.liftParameter(param: param) } @@ -3315,16 +3355,9 @@ extension BridgeJSLink { objectExpr: importRootExpr, propertyName: context.jsName ?? context.name ) - let returnExpr = try thunkBuilder.callStaticMethod( - on: constructorExpr, - name: method.jsName ?? method.name, - returnType: method.returnType - ) - let funcLines = thunkBuilder.renderFunction( - name: method.abiName(context: context, operation: "static"), - returnExpr: returnExpr, - returnType: method.returnType - ) + + try thunkBuilder.callStaticMethod(on: constructorExpr, name: method.jsName ?? method.name) + let funcLines = thunkBuilder.renderFunction(name: method.abiName(context: context, operation: "static")) return (funcLines, []) } @@ -3332,17 +3365,18 @@ extension BridgeJSLink { context: ImportedTypeSkeleton, method: ImportedFunctionSkeleton ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + let thunkBuilder = ImportedThunkBuilder( + effects: method.effects, + returnType: method.returnType, + intrinsicRegistry: intrinsicRegistry + ) thunkBuilder.liftSelf() for param in method.parameters { try thunkBuilder.liftParameter(param: param) } - let returnExpr = try thunkBuilder.callMethod(name: method.jsName ?? method.name, returnType: method.returnType) - let funcLines = thunkBuilder.renderFunction( - name: method.abiName(context: context), - returnExpr: returnExpr, - returnType: method.returnType - ) + + try thunkBuilder.callMethod(name: method.jsName ?? method.name) + let funcLines = thunkBuilder.renderFunction(name: method.abiName(context: context)) return (funcLines, []) } @@ -3360,16 +3394,14 @@ extension BridgeJSLink { ) let getterThunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: property.type, context: .exportSwift, intrinsicRegistry: intrinsicRegistry ) getterThunkBuilder.liftSelf() - let returnExpr = try getterThunkBuilder.callPropertyGetter(name: property.name, returnType: property.type) - let getterLines = getterThunkBuilder.renderFunction( - name: getterAbiName, - returnExpr: returnExpr, - returnType: property.type - ) + try getterThunkBuilder.callPropertyGetter(name: property.name) + let getterLines = getterThunkBuilder.renderFunction(name: getterAbiName) importObjectBuilder.assignToImportObject(name: getterAbiName, function: getterLines) if !property.isReadonly { @@ -3381,6 +3413,8 @@ extension BridgeJSLink { className: `protocol`.name ) let setterThunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + returnType: .void, context: .exportSwift, intrinsicRegistry: intrinsicRegistry ) @@ -3388,12 +3422,8 @@ extension BridgeJSLink { try setterThunkBuilder.liftParameter( param: Parameter(label: nil, name: "value", type: property.type) ) - setterThunkBuilder.callPropertySetter(name: property.name, returnType: property.type) - let setterLines = setterThunkBuilder.renderFunction( - name: setterAbiName, - returnExpr: nil, - returnType: .void - ) + setterThunkBuilder.callPropertySetter(name: property.name) + let setterLines = setterThunkBuilder.renderFunction(name: setterAbiName) importObjectBuilder.assignToImportObject(name: setterAbiName, function: setterLines) } } @@ -3404,6 +3434,8 @@ extension BridgeJSLink { method: ExportedFunction ) throws { let thunkBuilder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + returnType: method.returnType, context: .exportSwift, intrinsicRegistry: intrinsicRegistry ) @@ -3411,12 +3443,8 @@ extension BridgeJSLink { for param in method.parameters { try thunkBuilder.liftParameter(param: param) } - let returnExpr = try thunkBuilder.callMethod(name: method.name, returnType: method.returnType) - let funcLines = thunkBuilder.renderFunction( - name: method.abiName, - returnExpr: returnExpr, - returnType: method.returnType - ) + try thunkBuilder.callMethod(name: method.name) + let funcLines = thunkBuilder.renderFunction(name: method.abiName) importObjectBuilder.assignToImportObject(name: method.abiName, function: funcLines) } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 1f03e09ba..c5672c79c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -101,24 +101,31 @@ public struct ClosureSignature: Codable, Equatable, Hashable, Sendable { public let isAsync: Bool public let isThrows: Bool public let moduleName: String + /// When true, closure parameters are annotated with `sending` in Swift. + /// Used for async Promise resolve/reject callbacks where values are + /// transferred through a continuation. + public let sendingParameters: Bool public init( parameters: [BridgeType], returnType: BridgeType, moduleName: String, isAsync: Bool = false, - isThrows: Bool = false + isThrows: Bool = false, + sendingParameters: Bool = false ) { self.parameters = parameters self.returnType = returnType self.moduleName = moduleName self.isAsync = isAsync self.isThrows = isThrows + self.sendingParameters = sendingParameters let paramPart = parameters.isEmpty ? "y" : parameters.map { $0.mangleTypeName }.joined() - let signaturePart = "\(paramPart)_\(returnType.mangleTypeName)" + let sendingPart = sendingParameters ? "s" : "" + let signaturePart = "\(sendingPart)\(paramPart)_\(returnType.mangleTypeName)" self.mangleName = "\(moduleName.count)\(moduleName)\(signaturePart)" } } @@ -388,13 +395,19 @@ public struct Parameter: Codable, Equatable, Sendable { } } -// MARK: - BridgeType Visitor +// MARK: - BridgeSkeleton Visitor -public protocol BridgeTypeVisitor { +public protocol BridgeSkeletonVisitor { mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) + mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) } -public struct BridgeTypeWalker { +public extension BridgeSkeletonVisitor { + mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) {} + mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) {} +} + +public struct BridgeSkeletonWalker { public var visitor: Visitor public init(visitor: Visitor) { @@ -480,6 +493,7 @@ public struct BridgeTypeWalker { } } public mutating func walk(_ function: ImportedFunctionSkeleton) { + visitor.visitImportedFunction(function) walk(function.parameters) walk(function.returnType) } @@ -923,6 +937,7 @@ public struct ImportedFunctionSkeleton: Codable { public let from: JSImportFrom? public let parameters: [Parameter] public let returnType: BridgeType + public let effects: Effects public let documentation: String? public init( @@ -931,6 +946,7 @@ public struct ImportedFunctionSkeleton: Codable { from: JSImportFrom? = nil, parameters: [Parameter], returnType: BridgeType, + effects: Effects = Effects(isAsync: false, isThrows: true), documentation: String? = nil ) { self.name = name @@ -938,6 +954,7 @@ public struct ImportedFunctionSkeleton: Codable { self.from = from self.parameters = parameters self.returnType = returnType + self.effects = effects self.documentation = documentation } @@ -1150,16 +1167,57 @@ public struct ImportedModuleSkeleton: Codable { // MARK: - Closure signature collection visitor -public struct ClosureSignatureCollectorVisitor: BridgeTypeVisitor { +public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { public var signatures: Set = [] + let moduleName: String - public init(signatures: Set = []) { + public init(moduleName: String, signatures: Set = []) { + self.moduleName = moduleName self.signatures = signatures } public mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) { signatures.insert(signature) } + 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. + + // Reject callback + signatures.insert( + ClosureSignature( + parameters: [.jsValue], + returnType: .void, + moduleName: moduleName, + sendingParameters: true + ) + ) + // Resolve callback (typed per return type) + if function.returnType == .void { + signatures.insert( + ClosureSignature( + parameters: [], + returnType: .void, + moduleName: moduleName + ) + ) + } else { + signatures.insert( + ClosureSignature( + parameters: [function.returnType], + returnType: .void, + moduleName: moduleName, + sendingParameters: true + ) + ) + } + } } // MARK: - Unified Skeleton diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js index 9617a5261..91a42a9ef 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js @@ -313,8 +313,8 @@ export class TypeProcessor { const parameters = signature.getParameters(); const parameterNameMap = this.buildParameterNameMap(parameters); const params = this.renderParameters(parameters, decl); - const returnType = this.visitType(signature.getReturnType(), decl); - const effects = this.renderEffects({ isAsync: false }); + const { returnType, isAsync } = this.unwrapPromiseReturnType(signature.getReturnType(), decl); + const effects = this.renderEffects({ isAsync }); const annotation = this.renderMacroAnnotation("JSFunction", args); this.emitDocComment(decl, { indent: "", parameterNameMap }); @@ -581,8 +581,8 @@ export class TypeProcessor { const parameters = signature.getParameters(); const parameterNameMap = this.buildParameterNameMap(parameters); const params = this.renderParameters(parameters, node); - const returnType = this.visitType(signature.getReturnType(), node); - const effects = this.renderEffects({ isAsync: false }); + const { returnType, isAsync } = this.unwrapPromiseReturnType(signature.getReturnType(), node); + const effects = this.renderEffects({ isAsync }); const swiftFuncName = this.renderIdentifier(swiftName); this.emitDocComment(node, { parameterNameMap }); @@ -1210,8 +1210,8 @@ export class TypeProcessor { const parameters = signature.getParameters(); const parameterNameMap = this.buildParameterNameMap(parameters); const params = this.renderParameters(parameters, node); - const returnType = this.visitType(signature.getReturnType(), node); - const effects = this.renderEffects({ isAsync: false }); + const { returnType, isAsync } = this.unwrapPromiseReturnType(signature.getReturnType(), node); + const effects = this.renderEffects({ isAsync }); const swiftMethodName = this.renderIdentifier(swiftName); const isStatic = node.modifiers?.some( (modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword @@ -1281,6 +1281,27 @@ export class TypeProcessor { return parts.join(" "); } + /** + * Check if a type is Promise and extract the return type and async flag. + * @param {ts.Type} type - The return type to check + * @param {ts.Node} node - The node for type visiting context + * @returns {{ returnType: string, isAsync: boolean }} + * @private + */ + unwrapPromiseReturnType(type, node) { + if (isTypeReference(type)) { + const symbol = type.target?.getSymbol(); + if (symbol?.name === "Promise") { + const typeArgs = this.checker.getTypeArguments(/** @type {ts.TypeReference} */ (type)); + const innerType = typeArgs && typeArgs.length > 0 + ? this.visitType(typeArgs[0], node) + : "Void"; + return { returnType: innerType, isAsync: true }; + } + } + return { returnType: this.visitType(type, node), isAsync: false }; + } + /** * @param {ts.Node} node * @returns {boolean} diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap index 4122f4148..643ac8441 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap @@ -32,19 +32,19 @@ exports[`ts2swift > snapshots Swift output for Async.d.ts > Async 1`] = ` @_spi(BridgeJS) import JavaScriptKit -@JSFunction func asyncReturnVoid() throws(JSException) -> JSPromise +@JSFunction func asyncReturnVoid() async throws(JSException) -> Void -@JSFunction func asyncRoundTripInt(_ v: Double) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripInt(_ v: Double) async throws(JSException) -> Double -@JSFunction func asyncRoundTripString(_ v: String) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripString(_ v: String) async throws(JSException) -> String -@JSFunction func asyncRoundTripBool(_ v: Bool) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool -@JSFunction func asyncRoundTripFloat(_ v: Double) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripFloat(_ v: Double) async throws(JSException) -> Double -@JSFunction func asyncRoundTripDouble(_ v: Double) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripDouble(_ v: Double) async throws(JSException) -> Double -@JSFunction func asyncRoundTripJSObject(_ v: JSValue) throws(JSException) -> JSPromise +@JSFunction func asyncRoundTripJSObject(_ v: JSValue) async throws(JSException) -> JSValue " `; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncImport.swift new file mode 100644 index 000000000..02563cbdf --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncImport.swift @@ -0,0 +1,6 @@ +@JSFunction func asyncReturnVoid() async throws(JSException) +@JSFunction func asyncRoundTripInt(_ v: Int) async throws(JSException) -> Int +@JSFunction func asyncRoundTripString(_ v: String) async throws(JSException) -> String +@JSFunction func asyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool +@JSFunction func asyncRoundTripDouble(_ v: Double) async throws(JSException) -> Double +@JSFunction func asyncRoundTripJSObject(_ v: JSObject) async throws(JSException) -> JSObject diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncStaticImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncStaticImport.swift new file mode 100644 index 000000000..1afd758bf --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncStaticImport.swift @@ -0,0 +1,4 @@ +@JSClass struct AsyncBox { + @JSFunction static func asyncStaticRoundTrip(_ v: Double) async throws(JSException) -> Double + @JSFunction static func asyncStaticVoid() async throws(JSException) +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json index 3664fa339..d071d8c52 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -1331,6 +1331,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkArray", "parameters" : [ { @@ -1349,6 +1354,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkArrayWithLength", "parameters" : [ { @@ -1375,6 +1385,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importProcessNumbers", "parameters" : [ { @@ -1397,6 +1412,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importGetNumbers", "parameters" : [ @@ -1412,6 +1432,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importTransformNumbers", "parameters" : [ { @@ -1438,6 +1463,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importProcessStrings", "parameters" : [ { @@ -1464,6 +1494,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importProcessBooleans", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json new file mode 100644 index 000000000..263578d20 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json @@ -0,0 +1,151 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncReturnVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripInt", + "parameters" : [ + { + "name" : "v", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripString", + "parameters" : [ + { + "name" : "v", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripBool", + "parameters" : [ + { + "name" : "v", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripDouble", + "parameters" : [ + { + "name" : "v", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripJSObject", + "parameters" : [ + { + "name" : "v", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ 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 new file mode 100644 index 000000000..7a60bc6b7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift @@ -0,0 +1,569 @@ +#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_10TestModules8JSObjectC_y") +fileprivate func invoke_js_callback_TestModule_10TestModules8JSObjectC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModules8JSObjectC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModules8JSObjectC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModules8JSObjectC_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModules8JSObjectC_y") +fileprivate func make_swift_closure_TestModule_10TestModules8JSObjectC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModules8JSObjectC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModules8JSObjectC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModules8JSObjectC_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModules8JSObjectC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending JSObject) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModules8JSObjectC_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending JSObject) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSObject) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModules8JSObjectC_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModules8JSObjectC_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModules8JSObjectC_y") +public func _invoke_swift_closure_TestModule_10TestModules8JSObjectC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSObject) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSObject.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 +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModulesSb_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSb_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSb_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSb_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSb_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSb_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_TestModule_10TestModulesSb_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_TestModule_10TestModulesSb_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSb_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSb_y") +public func _invoke_swift_closure_TestModule_10TestModulesSb_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_TestModule_10TestModulesSd_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_TestModule_10TestModulesSd_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSd_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSd_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSd_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_TestModule_10TestModulesSd_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_TestModule_10TestModulesSd_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSd_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSd_y") +public func _invoke_swift_closure_TestModule_10TestModulesSd_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_TestModule_10TestModulesSi_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSi_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSi_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSi_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSi_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSi_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Int) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModulesSi_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending Int) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Int) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModulesSi_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSi_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSi_y") +public func _invoke_swift_closure_TestModule_10TestModulesSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Int.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuley_y") +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_y(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuley_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_y") +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_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_TestModule_10TestModuley_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_y") +public func _invoke_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncReturnVoid") +fileprivate func bjs_asyncReturnVoid_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_asyncReturnVoid_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncReturnVoid(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_asyncReturnVoid_extern(resolveRef, rejectRef) +} + +func _$asyncReturnVoid() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_asyncReturnVoid(resolveRef, rejectRef) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripInt") +fileprivate func bjs_asyncRoundTripInt_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_asyncRoundTripInt_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncRoundTripInt(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_asyncRoundTripInt_extern(resolveRef, rejectRef, v) +} + +func _$asyncRoundTripInt(_ v: Int) async throws(JSException) -> Int { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Int) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_asyncRoundTripInt(resolveRef, rejectRef, vValue) + } + return resolved +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripString") +fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +#else +fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncRoundTripString(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + return bjs_asyncRoundTripString_extern(resolveRef, rejectRef, vBytes, vLength) +} + +func _$asyncRoundTripString(_ v: String) async throws(JSException) -> String { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + v.bridgeJSWithLoweredParameter { (vBytes, vLength) in + bjs_asyncRoundTripString(resolveRef, rejectRef, vBytes, vLength) + } + } + return resolved +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripBool") +fileprivate func bjs_asyncRoundTripBool_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_asyncRoundTripBool_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncRoundTripBool(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_asyncRoundTripBool_extern(resolveRef, rejectRef, v) +} + +func _$asyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Bool) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_asyncRoundTripBool(resolveRef, rejectRef, vValue) + } + return resolved +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripDouble") +fileprivate func bjs_asyncRoundTripDouble_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void +#else +fileprivate func bjs_asyncRoundTripDouble_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncRoundTripDouble(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + return bjs_asyncRoundTripDouble_extern(resolveRef, rejectRef, v) +} + +func _$asyncRoundTripDouble(_ v: Double) async throws(JSException) -> Double { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Double) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_asyncRoundTripDouble(resolveRef, rejectRef, vValue) + } + return resolved +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripJSObject") +fileprivate func bjs_asyncRoundTripJSObject_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_asyncRoundTripJSObject_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_asyncRoundTripJSObject(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_asyncRoundTripJSObject_extern(resolveRef, rejectRef, v) +} + +func _$asyncRoundTripJSObject(_ v: JSObject) async throws(JSException) -> JSObject { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending JSObject) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_asyncRoundTripJSObject(resolveRef, rejectRef, vValue) + } + return resolved +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json new file mode 100644 index 000000000..972a532c6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json @@ -0,0 +1,67 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "AsyncBox", + "setters" : [ + + ], + "staticMethods" : [ + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncStaticRoundTrip", + "parameters" : [ + { + "name" : "v", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncStaticVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift new file mode 100644 index 000000000..ee7dc73e7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift @@ -0,0 +1,227 @@ +#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_10TestModulesSd_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSd_y(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_TestModule_10TestModulesSd_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSd_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSd_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSd_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_TestModule_10TestModulesSd_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_TestModule_10TestModulesSd_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSd_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSd_y") +public func _invoke_swift_closure_TestModule_10TestModulesSd_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_TestModule_10TestModuley_y") +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_y(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuley_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_y") +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_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_TestModule_10TestModuley_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_y") +public func _invoke_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_AsyncBox_asyncStaticRoundTrip_static") +fileprivate func bjs_AsyncBox_asyncStaticRoundTrip_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void +#else +fileprivate func bjs_AsyncBox_asyncStaticRoundTrip_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncBox_asyncStaticRoundTrip_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + return bjs_AsyncBox_asyncStaticRoundTrip_static_extern(resolveRef, rejectRef, v) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_AsyncBox_asyncStaticVoid_static") +fileprivate func bjs_AsyncBox_asyncStaticVoid_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_AsyncBox_asyncStaticVoid_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncBox_asyncStaticVoid_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_AsyncBox_asyncStaticVoid_static_extern(resolveRef, rejectRef) +} + +func _$AsyncBox_asyncStaticRoundTrip(_ v: Double) async throws(JSException) -> Double { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Double) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_AsyncBox_asyncStaticRoundTrip_static(resolveRef, rejectRef, vValue) + } + return resolved +} + +func _$AsyncBox_asyncStaticVoid() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_AsyncBox_asyncStaticVoid_static(resolveRef, rejectRef) + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json index 4d7495a7c..a0c2c80c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "fetchNumber", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index c740dc46f..ea707098d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -235,6 +235,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "importMirrorDictionary", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json index ba36405ba..fc4a7ae52 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json @@ -1526,6 +1526,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "takesFeatureFlag", "parameters" : [ { @@ -1545,6 +1550,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "returnsFeatureFlag", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json index bef9cbc88..15a20f72e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json @@ -269,6 +269,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripInt8", "parameters" : [ { @@ -293,6 +298,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripUInt8", "parameters" : [ { @@ -317,6 +327,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripInt16", "parameters" : [ { @@ -341,6 +356,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripUInt16", "parameters" : [ { @@ -365,6 +385,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripInt32", "parameters" : [ { @@ -389,6 +414,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripUInt32", "parameters" : [ { @@ -413,6 +443,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripInt64", "parameters" : [ { @@ -437,6 +472,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripUInt64", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json index 55ac7dd70..f750fc6a5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json @@ -22,6 +22,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "log", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json index 5e002e34f..809a9ad99 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "from" : "global", "jsName" : "parseInt", "name" : "parseInt", @@ -42,6 +47,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "log", "parameters" : [ { @@ -87,6 +97,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "close", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json index 7f79a8146..3f9cb8e32 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundtrip", "parameters" : [ { @@ -36,6 +41,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "logStrings", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json index 935f7a7f2..1ad99f397 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "createWeirdObject", "parameters" : [ @@ -15,6 +20,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "createWeirdClass", "parameters" : [ @@ -100,6 +110,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "as", "parameters" : [ @@ -111,6 +126,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "try", "parameters" : [ @@ -218,6 +238,11 @@ "jsName" : "$Weird", "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "jsName" : "method-with-dashes", "name" : "method_with_dashes", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json index 689e86150..ef8eba9ba 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "returnAnimatable", "parameters" : [ @@ -49,6 +54,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "greet", "parameters" : [ @@ -60,6 +70,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "changeName", "parameters" : [ { @@ -100,6 +115,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "animate", "parameters" : [ { @@ -126,6 +146,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "getAnimations", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json index a8b64558f..18f7cfaac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json @@ -12,6 +12,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "value", "parameters" : [ @@ -29,6 +34,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "create", "parameters" : [ { @@ -47,6 +57,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "value", "parameters" : [ @@ -58,6 +73,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "makeDefault", "parameters" : [ @@ -69,6 +89,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "jsName" : "with-dashes", "name" : "dashed", "parameters" : [ @@ -107,6 +132,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "create", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json index 5bd83be27..fb8601ae7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json @@ -321,6 +321,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsEchoJSValue", "parameters" : [ { @@ -339,6 +344,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsEchoJSValueArray", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 67d97821c..3e6d6c60c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -1152,6 +1152,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripStringOrNull", "parameters" : [ { @@ -1180,6 +1185,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripStringOrUndefined", "parameters" : [ { @@ -1208,6 +1218,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripDoubleOrNull", "parameters" : [ { @@ -1236,6 +1251,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripDoubleOrUndefined", "parameters" : [ { @@ -1264,6 +1284,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripBoolOrNull", "parameters" : [ { @@ -1292,6 +1317,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripBoolOrUndefined", "parameters" : [ { @@ -1320,6 +1350,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripIntOrNull", "parameters" : [ { @@ -1354,6 +1389,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "roundTripIntOrUndefined", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json index f75bf7610..cf76f3878 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -88,6 +88,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "check", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json index cded9a973..b0398c161 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -112,6 +112,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkNumber", "parameters" : [ @@ -123,6 +128,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkBoolean", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json index 4ba7ba9a5..36d6941d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json @@ -84,7 +84,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -130,7 +131,8 @@ "swiftProtocol" : { "_0" : "Renderable" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -166,7 +168,8 @@ "swiftProtocol" : { "_0" : "Renderable" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -191,7 +194,8 @@ "swiftProtocol" : { "_0" : "Renderable" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -232,7 +236,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json index b0aa8c35b..75462af81 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json @@ -71,6 +71,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkString", "parameters" : [ { @@ -89,6 +94,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkStringWithLength", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json index 3f9271592..1088a5cab 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json @@ -38,6 +38,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "checkString", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index 6ab78c82c..ceda64904 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -213,6 +213,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripGreeter", "parameters" : [ { @@ -231,6 +236,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalGreeter", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index f610d4bde..41662e48b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -61,7 +61,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -313,7 +314,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -338,7 +340,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -380,7 +383,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -411,7 +415,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -447,7 +452,8 @@ "bool" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -472,7 +478,8 @@ "bool" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -508,7 +515,8 @@ "float" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -533,7 +541,8 @@ "float" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -569,7 +578,8 @@ "double" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -594,7 +604,8 @@ "double" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -640,7 +651,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -675,7 +687,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -727,7 +740,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -768,7 +782,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -814,7 +829,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -849,7 +865,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -895,7 +912,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -930,7 +948,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -976,7 +995,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1011,7 +1031,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1047,7 +1068,8 @@ "swiftHeapObject" : { "_0" : "Person" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1072,7 +1094,8 @@ "swiftHeapObject" : { "_0" : "Person" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1118,7 +1141,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1153,7 +1177,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1189,7 +1214,8 @@ "caseEnum" : { "_0" : "Direction" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1214,7 +1240,8 @@ "caseEnum" : { "_0" : "Direction" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1252,7 +1279,8 @@ "_0" : "Theme", "_1" : "String" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1279,7 +1307,8 @@ "_0" : "Theme", "_1" : "String" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1317,7 +1346,8 @@ "_0" : "HttpStatus", "_1" : "Int" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1344,7 +1374,8 @@ "_0" : "HttpStatus", "_1" : "Int" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1380,7 +1411,8 @@ "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1405,7 +1437,8 @@ "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1451,7 +1484,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1486,7 +1520,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1534,7 +1569,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1571,7 +1607,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1619,7 +1656,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1656,7 +1694,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1702,7 +1741,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1737,7 +1777,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1783,7 +1824,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -1818,7 +1860,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json index 4359b50ec..a78b1bf5d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -4,6 +4,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "applyInt", "parameters" : [ { @@ -43,7 +48,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -60,6 +66,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "makeAdder", "parameters" : [ { @@ -98,7 +109,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index c1329cd79..ccd3043ac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -56,6 +56,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "translate", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json index 14da32841..7f19c18bf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json @@ -38,6 +38,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "check", "parameters" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts new file mode 100644 index 000000000..e612ae1e1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts @@ -0,0 +1,23 @@ +// 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 = { + asyncReturnVoid(): Promise; + asyncRoundTripInt(v: number): Promise; + asyncRoundTripString(v: string): Promise; + asyncRoundTripBool(v: boolean): Promise; + asyncRoundTripDouble(v: number): Promise; + asyncRoundTripJSObject(v: any): Promise; +} +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/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js new file mode 100644 index 000000000..89ab29827 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -0,0 +1,507 @@ +// 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 = []; + 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 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; + 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(); + } + 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_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_10TestModules8JSObjectC_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(swift.memory.getObject(param0)); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModules8JSObjectC_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModules8JSObjectC_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModules8JSObjectC_y(boxPtr, swift.memory.retain(param0)); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules8JSObjectC_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); + } + bjs["invoke_js_callback_TestModule_10TestModulesSb_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(param0 !== 0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSb_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSb_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModulesSb_y(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSb_y); + } + bjs["invoke_js_callback_TestModule_10TestModulesSd_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(param0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSd_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSd_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModulesSd_y(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSd_y); + } + bjs["invoke_js_callback_TestModule_10TestModulesSi_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(param0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSi_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSi_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModulesSi_y(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSi_y); + } + bjs["invoke_js_callback_TestModule_10TestModuley_y"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + callback(); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuley_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_y = function() { + instance.exports.invoke_swift_closure_TestModule_10TestModuley_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_10TestModuley_y); + } + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_asyncReturnVoid"] = function bjs_asyncReturnVoid(resolveRef, rejectRef) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.asyncReturnVoid().then(resolve, reject); + } + TestModule["bjs_asyncRoundTripInt"] = function bjs_asyncRoundTripInt(resolveRef, rejectRef, v) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.asyncRoundTripInt(v).then(resolve, reject); + } + TestModule["bjs_asyncRoundTripString"] = function bjs_asyncRoundTripString(resolveRef, rejectRef, vBytes, vCount) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const string = decodeString(vBytes, vCount); + imports.asyncRoundTripString(string).then(resolve, reject); + } + TestModule["bjs_asyncRoundTripBool"] = function bjs_asyncRoundTripBool(resolveRef, rejectRef, v) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.asyncRoundTripBool(v !== 0).then(resolve, reject); + } + TestModule["bjs_asyncRoundTripDouble"] = function bjs_asyncRoundTripDouble(resolveRef, rejectRef, v) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.asyncRoundTripDouble(v).then(resolve, reject); + } + TestModule["bjs_asyncRoundTripJSObject"] = function bjs_asyncRoundTripJSObject(resolveRef, rejectRef, v) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.asyncRoundTripJSObject(swift.memory.getObject(v)).then(resolve, reject); + } + }, + 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/AsyncStaticImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts new file mode 100644 index 000000000..491a66795 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts @@ -0,0 +1,23 @@ +// 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 AsyncBox { +} +export type Exports = { +} +export type Imports = { + AsyncBox: { + asyncStaticRoundTrip(v: number): Promise; + asyncStaticVoid(): Promise; + } +} +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/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js new file mode 100644 index 000000000..7fd6a0d6b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -0,0 +1,402 @@ +// 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 = []; + 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 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(); + } + 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_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_10TestModulesSd_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(param0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSd_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSd_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModulesSd_y(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSd_y); + } + bjs["invoke_js_callback_TestModule_10TestModuley_y"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + callback(); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuley_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_y = function() { + instance.exports.invoke_swift_closure_TestModule_10TestModuley_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_10TestModuley_y); + } + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_AsyncBox_asyncStaticRoundTrip_static"] = function bjs_AsyncBox_asyncStaticRoundTrip_static(resolveRef, rejectRef, v) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.AsyncBox.asyncStaticRoundTrip(v).then(resolve, reject); + } + TestModule["bjs_AsyncBox_asyncStaticVoid_static"] = function bjs_AsyncBox_asyncStaticVoid_static(resolveRef, rejectRef) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + imports.AsyncBox.asyncStaticVoid().then(resolve, reject); + } + }, + 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/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 180567ed1..867d0e835 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -4,6 +4,7 @@ /// by the BridgeJS system. import _CJavaScriptKit +import _Concurrency #if !arch(wasm32) @usableFromInline func _onlyAvailableOnWasm() -> Never { @@ -2083,3 +2084,91 @@ extension _BridgedAsOptional { Wrapped.bridgeJSStackPushAsOptional(asOptional) } } + +// MARK: Async Promise Awaiting + +/// Protocol for type-erasing `JSTypedClosure` in `_bjs_awaitPromise`. +/// +/// The library cannot name concrete `JSTypedClosure<(Int) -> Void>` etc. because +/// those require per-module generated convenience inits. This protocol provides +/// access to the underlying JS object ref and cleanup. +@_spi(BridgeJS) public protocol _BridgeJSReleasableClosure { + var jsObject: JSObject { get } + func release() +} + +@_spi(BridgeJS) extension JSTypedClosure: _BridgeJSReleasableClosure {} + +/// Awaits a JavaScript Promise using typed resolve/reject `JSTypedClosure` callbacks. +/// +/// The closure factories are dependency-injected because this library cannot +/// reference per-module generated `make_swift_closure_*` externs. The generated +/// code passes `{ JSTypedClosure<(T) -> Void>($0) }` which uses the per-module +/// convenience init. +/// +/// - Parameters: +/// - makeResolveClosure: A factory that wraps a `(T) -> Void` Swift closure +/// into a typed `JSTypedClosure`, creating the corresponding JS function. +/// - makeRejectClosure: A factory that wraps a `(JSValue) -> Void` Swift closure +/// into a `JSTypedClosure`, for the rejection path. +/// - body: A closure that receives the resolve and reject JS object refs +/// (as `Int32`) and should pass them to the appropriate JS extern function. +/// - Returns: The resolved value of type `T` from the Promise. +/// - Throws: `JSException` if the Promise rejects. +@_spi(BridgeJS) public func _bjs_awaitPromise( + makeResolveClosure: (@escaping (sending T) -> Void) -> R, + makeRejectClosure: (@escaping (sending JSValue) -> Void) -> E, + _ body: (_ resolveRef: Int32, _ rejectRef: Int32) -> Void +) async throws(JSException) -> T { + var resolveClosure: R? + var rejectClosure: E? + let result: Result = await withCheckedContinuation { continuation in + let resolve = makeResolveClosure { value in + continuation.resume(returning: .success(value)) + } + let reject = makeRejectClosure { value in + continuation.resume(returning: .failure(JSException(value))) + } + resolveClosure = resolve + rejectClosure = reject + body( + Int32(bitPattern: resolve.jsObject.id), + Int32(bitPattern: reject.jsObject.id) + ) + } + resolveClosure?.release() + rejectClosure?.release() + return try result.get() +} + +/// Void-returning overload of `_bjs_awaitPromise`. +/// +/// Needed because `(Void) -> Void` is not the same as `() -> Void` in Swift (SE-0110), +/// so the generic overload cannot handle void returns. +@_spi(BridgeJS) public func _bjs_awaitPromise( + makeResolveClosure: (@escaping () -> Void) -> R, + makeRejectClosure: (@escaping (sending JSValue) -> Void) -> E, + _ body: (_ resolveRef: Int32, _ rejectRef: Int32) -> Void +) async throws(JSException) { + var resolveClosure: R? + var rejectClosure: E? + let error: JSException? = await withCheckedContinuation { continuation in + let resolve = makeResolveClosure { + continuation.resume(returning: nil) + } + let reject = makeRejectClosure { value in + continuation.resume(returning: JSException(value)) + } + resolveClosure = resolve + rejectClosure = reject + body( + Int32(bitPattern: resolve.jsObject.id), + Int32(bitPattern: reject.jsObject.id) + ) + } + resolveClosure?.release() + rejectClosure?.release() + if let error { + throw error + } +} diff --git a/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift new file mode 100644 index 000000000..041f251f4 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift @@ -0,0 +1,85 @@ +import Testing +import JavaScriptKit + +@JSClass struct AsyncImportImports { + @JSFunction static func jsAsyncRoundTripVoid() async throws(JSException) + @JSFunction static func jsAsyncRoundTripNumber(_ v: Double) async throws(JSException) -> Double + @JSFunction static func jsAsyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool + @JSFunction static func jsAsyncRoundTripString(_ v: String) async throws(JSException) -> String + @JSFunction static func jsAsyncRoundTripOptionalString(_ v: String?) async throws(JSException) -> String? + @JSFunction static func jsAsyncRoundTripOptionalNumber(_ v: Double?) async throws(JSException) -> Double? + @JSFunction static func jsAsyncRoundTripBoolArray(_ values: [Bool]) async throws(JSException) -> [Bool] + @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 +} + +@Suite struct AsyncImportTests { + @Test func asyncRoundTripVoid() async throws { + try await AsyncImportImports.jsAsyncRoundTripVoid() + } + + @Test(arguments: [0.0, 1.0, -1.0, Double.pi, Double.infinity]) + func asyncRoundTripNumber(v: Double) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripNumber(v) == v) + } + + @Test(arguments: [true, false]) + func asyncRoundTripBool(v: Bool) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripBool(v) == v) + } + + @Test(arguments: ["", "Hello, world!", "🧑‍🧑‍🧒"]) + func asyncRoundTripString(v: String) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripString(v) == v) + } + + // MARK: - Stack ABI types + + @Test(arguments: ["hello" as String?, nil, "🧑‍🧑‍🧒" as String?]) + func asyncRoundTripOptionalString(v: String?) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripOptionalString(v) == v) + } + + @Test(arguments: [42.0 as Double?, nil, 0.0 as Double?]) + func asyncRoundTripOptionalNumber(v: Double?) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripOptionalNumber(v) == v) + } + + @Test func asyncRoundTripBoolArray() async throws { + let values: [Bool] = [true, false, true] + try #expect(await AsyncImportImports.jsAsyncRoundTripBoolArray(values) == values) + try #expect(await AsyncImportImports.jsAsyncRoundTripBoolArray([]) == []) + } + + @Test func asyncRoundTripIntArray() async throws { + let values: [Double] = [1, 2, 3, 4, 5] + try #expect(await AsyncImportImports.jsAsyncRoundTripIntArray(values) == values) + try #expect(await AsyncImportImports.jsAsyncRoundTripIntArray([]) == []) + } + + @Test func asyncRoundTripStringArray() async throws { + let values = ["Hello", "World", "🎉"] + try #expect(await AsyncImportImports.jsAsyncRoundTripStringArray(values) == values) + try #expect(await AsyncImportImports.jsAsyncRoundTripStringArray([]) == []) + } + + @Test(arguments: [FeatureFlag.foo, .bar]) + func asyncRoundTripFeatureFlag(v: FeatureFlag) async throws { + try #expect(await AsyncImportImports.jsAsyncRoundTripFeatureFlag(v) == v) + } + + // MARK: - Structured return type + + @Test func fetchWeatherData() async throws { + let weather = try await BridgeJSRuntimeTests.fetchWeatherData("London") + #expect(try weather.temperature == 15.5) + #expect(try weather.description == "Cloudy") + #expect(try weather.humidity == 80) + + let weather2 = try await BridgeJSRuntimeTests.fetchWeatherData("Tokyo") + #expect(try weather2.temperature == 25.0) + #expect(try weather2.description == "Sunny") + #expect(try weather2.humidity == 40) + } +} diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 171d0dd3a..3db9497fc 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1301,6 +1301,6 @@ class ExportAPITests: XCTestCase { } func testAllAsync() async throws { - _ = try await runAsyncWorks().value() + try await runAsyncWorks() } } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift index ac9ad0bc6..e3a6eec61 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift @@ -41,7 +41,18 @@ extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} @JSFunction func changeName(_ name: String) throws(JSException) -> Void } -@JSFunction func runAsyncWorks() throws(JSException) -> JSPromise +@JSFunction func runAsyncWorks() async throws(JSException) -> Void + +@JSFunction func fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData + +@JSClass struct WeatherData { + @JSGetter var temperature: Double + @JSSetter func setTemperature(_ value: Double) throws(JSException) + @JSGetter var description: String + @JSSetter func setDescription(_ value: String) throws(JSException) + @JSGetter var humidity: Double + @JSSetter func setHumidity(_ value: Double) throws(JSException) +} @JSFunction(jsName: "$jsWeirdFunction") func _jsWeirdFunction() throws(JSException) -> Double diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index b54106be9..71e5ef537 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -1674,6 +1674,680 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS #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 +#else +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_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_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_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(boxPtr, file, line) +} + +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() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +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_20BridgeJSRuntimeTestss11FeatureFlagO_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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 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_20BridgeJSRuntimeTestss11WeatherDataC_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +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_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_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_20BridgeJSRuntimeTestss11WeatherDataC_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) +} + +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 param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +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_20BridgeJSRuntimeTestss11WeatherDataC_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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 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_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_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_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_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_20BridgeJSRuntimeTestss7JSValueV_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) +} + +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() + let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_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_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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 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_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_20BridgeJSRuntimeTestssSS_y_extern(_ 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) +} + +#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 +#else +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_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_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_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_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_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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<(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_20BridgeJSRuntimeTestssSaSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void +#else +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_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_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_20BridgeJSRuntimeTestssSaSS_y_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) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_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() + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) + #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_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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<(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_20BridgeJSRuntimeTestssSaSb_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void +#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_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 @@ -10489,6 +11163,247 @@ func _$ArraySupportImports_runJsArraySupportTests() throws(JSException) -> Void } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripVoid_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripVoid_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripVoid_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripVoid_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripVoid_static_extern(resolveRef, rejectRef) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripNumber_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripNumber_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripNumber_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripNumber_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripNumber_static_extern(resolveRef, rejectRef, v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripBool_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBool_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBool_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBool_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripBool_static_extern(resolveRef, rejectRef, v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripString_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(resolveRef, rejectRef, vBytes, vLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(resolveRef, rejectRef, vIsSome, vBytes, vLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vValue: Float64) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vValue: Float64) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static_extern(resolveRef, rejectRef, vIsSome, vValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static_extern(resolveRef, rejectRef) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static_extern(resolveRef, rejectRef) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static_extern(resolveRef, rejectRef) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vBytes, vLength) +} + +func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_AsyncImportImports_jsAsyncRoundTripVoid_static(resolveRef, rejectRef) + } +} + +func _$AsyncImportImports_jsAsyncRoundTripNumber(_ v: Double) async throws(JSException) -> Double { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Double) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripNumber_static(resolveRef, rejectRef, vValue) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Bool) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripBool_static(resolveRef, rejectRef, vValue) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripString(_ v: String) async throws(JSException) -> String { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + v.bridgeJSWithLoweredParameter { (vBytes, vLength) in + bjs_AsyncImportImports_jsAsyncRoundTripString_static(resolveRef, rejectRef, vBytes, vLength) + } + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripOptionalString(_ 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 + v.bridgeJSWithLoweredParameter { (vIsSome, vBytes, vLength) in + bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(resolveRef, rejectRef, vIsSome, vBytes, vLength) + } + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripOptionalNumber(_ 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, vValue) = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static(resolveRef, rejectRef, vIsSome, vValue) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripBoolArray(_ values: [Bool]) async throws(JSException) -> [Bool] { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending [Bool]) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let _ = values.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static(resolveRef, rejectRef) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripIntArray(_ values: [Double]) async throws(JSException) -> [Double] { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending [Double]) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let _ = values.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static(resolveRef, rejectRef) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripStringArray(_ values: [String]) async throws(JSException) -> [String] { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending [String]) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let _ = values.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static(resolveRef, rejectRef) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async throws(JSException) -> FeatureFlag { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending FeatureFlag) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + v.bridgeJSWithLoweredParameter { (vBytes, vLength) in + bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(resolveRef, rejectRef, vBytes, vLength) + } + } + return resolved +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void @@ -11296,22 +12211,49 @@ func _$jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Featur #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runAsyncWorks") -fileprivate func bjs_runAsyncWorks_extern() -> Int32 +fileprivate func bjs_runAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void #else -fileprivate func bjs_runAsyncWorks_extern() -> Int32 { +fileprivate func bjs_runAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_runAsyncWorks() -> Int32 { - return bjs_runAsyncWorks_extern() +@inline(never) fileprivate func bjs_runAsyncWorks(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_runAsyncWorks_extern(resolveRef, rejectRef) } -func _$runAsyncWorks() throws(JSException) -> JSPromise { - let ret = bjs_runAsyncWorks() - if let error = _swift_js_take_exception() { - throw error +func _$runAsyncWorks() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_runAsyncWorks(resolveRef, rejectRef) } - return JSPromise.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_fetchWeatherData") +fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void +#else +fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_fetchWeatherData(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void { + return bjs_fetchWeatherData_extern(resolveRef, rejectRef, cityBytes, cityLength) +} + +func _$fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending WeatherData) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + city.bridgeJSWithLoweredParameter { (cityBytes, cityLength) in + bjs_fetchWeatherData(resolveRef, rejectRef, cityBytes, cityLength) + } + } + return resolved } #if arch(wasm32) @@ -11492,6 +12434,133 @@ func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_temperature_get") +fileprivate func bjs_WeatherData_temperature_get_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_WeatherData_temperature_get_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_temperature_get(_ self: Int32) -> Float64 { + return bjs_WeatherData_temperature_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_description_get") +fileprivate func bjs_WeatherData_description_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeatherData_description_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_description_get(_ self: Int32) -> Int32 { + return bjs_WeatherData_description_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_humidity_get") +fileprivate func bjs_WeatherData_humidity_get_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_WeatherData_humidity_get_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_humidity_get(_ self: Int32) -> Float64 { + return bjs_WeatherData_humidity_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_temperature_set") +fileprivate func bjs_WeatherData_temperature_set_extern(_ self: Int32, _ newValue: Float64) -> Void +#else +fileprivate func bjs_WeatherData_temperature_set_extern(_ self: Int32, _ newValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_temperature_set(_ self: Int32, _ newValue: Float64) -> Void { + return bjs_WeatherData_temperature_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_description_set") +fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +#else +fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_description_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_WeatherData_description_set_extern(self, newValueBytes, newValueLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_humidity_set") +fileprivate func bjs_WeatherData_humidity_set_extern(_ self: Int32, _ newValue: Float64) -> Void +#else +fileprivate func bjs_WeatherData_humidity_set_extern(_ self: Int32, _ newValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeatherData_humidity_set(_ self: Int32, _ newValue: Float64) -> Void { + return bjs_WeatherData_humidity_set_extern(self, newValue) +} + +func _$WeatherData_temperature_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeatherData_temperature_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$WeatherData_description_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeatherData_description_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeatherData_humidity_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeatherData_humidity_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$WeatherData_temperature_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeatherData_temperature_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeatherData_description_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + bjs_WeatherData_description_set(selfValue, newValueBytes, newValueLength) + } + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeatherData_humidity_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeatherData_humidity_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__WeirdClass_init") fileprivate func bjs__WeirdClass_init_extern() -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 842bcff24..60b02020d 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -49,7 +49,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -97,7 +98,8 @@ "double" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -145,7 +147,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -202,7 +205,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -250,7 +254,8 @@ "double" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -298,7 +303,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -591,7 +597,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -641,7 +648,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -684,7 +692,8 @@ "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -724,7 +733,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -2931,7 +2941,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3017,7 +3028,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3059,7 +3071,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3100,7 +3113,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3151,7 +3165,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3199,7 +3214,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3246,7 +3262,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3282,7 +3299,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3318,7 +3336,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3362,7 +3381,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3409,7 +3429,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3455,7 +3476,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3497,7 +3519,8 @@ "bool" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3533,7 +3556,8 @@ "bool" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3572,7 +3596,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3607,7 +3632,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3648,7 +3674,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3697,7 +3724,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3745,7 +3773,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3792,7 +3821,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3828,7 +3858,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3866,7 +3897,8 @@ "swiftProtocol" : { "_0" : "DataProcessor" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3902,7 +3934,8 @@ "swiftProtocol" : { "_0" : "DataProcessor" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3927,7 +3960,8 @@ "swiftProtocol" : { "_0" : "DataProcessor" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -3968,7 +4002,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -10604,7 +10639,8 @@ }, "_1" : "null" } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -13606,7 +13642,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -13656,7 +13693,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -13708,7 +13746,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } @@ -16372,6 +16411,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsIntArrayLength", "parameters" : [ { @@ -16400,6 +16444,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripIntArray", "parameters" : [ { @@ -16432,6 +16481,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripNumberArray", "parameters" : [ { @@ -16458,6 +16512,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripStringArray", "parameters" : [ { @@ -16484,6 +16543,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripBoolArray", "parameters" : [ { @@ -16510,6 +16574,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripJSValueArray", "parameters" : [ { @@ -16536,6 +16605,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripJSObjectArray", "parameters" : [ { @@ -16562,6 +16636,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripJSClassArray", "parameters" : [ { @@ -16588,6 +16667,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalIntArray", "parameters" : [ { @@ -16630,6 +16714,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalStringArray", "parameters" : [ { @@ -16666,6 +16755,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalBoolArray", "parameters" : [ { @@ -16702,6 +16796,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalJSValueArray", "parameters" : [ { @@ -16738,6 +16837,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalJSObjectArray", "parameters" : [ { @@ -16774,6 +16878,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalJSClassArray", "parameters" : [ { @@ -16810,6 +16919,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsSumNumberArray", "parameters" : [ { @@ -16832,6 +16946,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCreateNumberArray", "parameters" : [ @@ -16847,6 +16966,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "runJsArraySupportTests", "parameters" : [ @@ -16873,36 +16997,20 @@ "methods" : [ ], - "name" : "ClosureSupportImports", + "name" : "AsyncImportImports", "setters" : [ ], "staticMethods" : [ { - "name" : "jsApplyVoid", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripVoid", "parameters" : [ - { - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsy_y", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - - ], - "returnType" : { - "void" : { - } - } - }, - "useJSTypedClosure" : true - } - } - } ], "returnType" : { "void" : { @@ -16911,139 +17019,474 @@ } }, { - "name" : "jsApplyBool", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripNumber", "parameters" : [ { - "name" : "callback", + "name" : "v", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsy_Sb", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - - ], - "returnType" : { - "bool" : { + "double" : { - } - } - }, - "useJSTypedClosure" : true } } } ], "returnType" : { - "bool" : { + "double" : { } } }, { - "name" : "jsApplyInt", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripBool", "parameters" : [ { - "name" : "value", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - { - "name" : "transform", + "name" : "v", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - ], - "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - "useJSTypedClosure" : true + "bool" : { + } } } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "bool" : { + } } }, { - "name" : "jsApplyDouble", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripString", "parameters" : [ { - "name" : "value", + "name" : "v", "type" : { - "double" : { + "string" : { } } - }, + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripOptionalString", + "parameters" : [ { - "name" : "transform", + "name" : "v", "type" : { - "closure" : { + "nullable" : { "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "double" : { - - } - } - ], - "returnType" : { - "double" : { + "string" : { - } } }, - "useJSTypedClosure" : true + "_1" : "null" } } } ], "returnType" : { - "double" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" } } }, { - "name" : "jsApplyString", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripOptionalNumber", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripBoolArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripIntArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripStringArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripFeatureFlag", + "parameters" : [ + { + "name" : "v", + "type" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ] + } + ] + }, + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureSupportImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyVoid", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyBool", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_Sb", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyInt", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyDouble", + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyString", "parameters" : [ { "name" : "value", @@ -17073,7 +17516,8 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17087,6 +17531,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsApplyJSObject", "parameters" : [ { @@ -17117,7 +17566,8 @@ "jsObject" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17131,6 +17581,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsMakeIntToInt", "parameters" : [ { @@ -17169,13 +17624,19 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsMakeDoubleToDouble", "parameters" : [ { @@ -17205,13 +17666,19 @@ "double" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsMakeStringToString", "parameters" : [ { @@ -17241,13 +17708,19 @@ "string" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : false } } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCallTwice", "parameters" : [ { @@ -17284,7 +17757,8 @@ "void" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17301,6 +17775,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCallBinary", "parameters" : [ { @@ -17337,7 +17816,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17354,6 +17834,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCallTriple", "parameters" : [ { @@ -17398,7 +17883,8 @@ "width" : "word" } } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17415,6 +17901,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCallAfterRelease", "parameters" : [ { @@ -17433,7 +17924,8 @@ "void" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17447,6 +17939,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsOptionalInvoke", "parameters" : [ { @@ -17467,7 +17964,8 @@ "bool" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17484,6 +17982,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsStoreClosure", "parameters" : [ { @@ -17502,7 +18005,8 @@ "void" : { } - } + }, + "sendingParameters" : false }, "useJSTypedClosure" : true } @@ -17516,6 +18020,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsCallStoredClosure", "parameters" : [ @@ -17527,6 +18036,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsHeapCount", "parameters" : [ @@ -17541,6 +18055,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "runJsClosureSupportTests", "parameters" : [ @@ -17573,6 +18092,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "runJsDefaultArgumentTests", "parameters" : [ @@ -17605,6 +18129,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryInt", "parameters" : [ { @@ -17637,6 +18166,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryBool", "parameters" : [ { @@ -17663,6 +18197,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryDouble", "parameters" : [ { @@ -17689,6 +18228,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryJSObject", "parameters" : [ { @@ -17715,6 +18259,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryJSValue", "parameters" : [ { @@ -17741,6 +18290,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripDictionaryDoubleArray", "parameters" : [ { @@ -17822,6 +18376,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripVoid", "parameters" : [ @@ -17833,6 +18392,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripNumber", "parameters" : [ { @@ -17851,6 +18415,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripBool", "parameters" : [ { @@ -17869,6 +18438,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripString", "parameters" : [ { @@ -17887,6 +18461,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripJSValue", "parameters" : [ { @@ -17905,6 +18484,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsThrowOrVoid", "parameters" : [ { @@ -17923,6 +18507,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsThrowOrNumber", "parameters" : [ { @@ -17941,6 +18530,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsThrowOrBool", "parameters" : [ { @@ -17959,6 +18553,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsThrowOrString", "parameters" : [ { @@ -17977,6 +18576,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripFeatureFlag", "parameters" : [ { @@ -17997,17 +18601,50 @@ } }, { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, "name" : "runAsyncWorks", "parameters" : [ + ], + "returnType" : { + "void" : { + + } + } + }, + { + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "fetchWeatherData", + "parameters" : [ + { + "name" : "city", + "type" : { + "string" : { + + } + } + } ], "returnType" : { "jsObject" : { - "_0" : "JSPromise" + "_0" : "WeatherData" } } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "jsName" : "$jsWeirdFunction", "name" : "_jsWeirdFunction", "parameters" : [ @@ -18020,6 +18657,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "from" : "global", "name" : "parseInt", "parameters" : [ @@ -18092,6 +18734,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "greet", "parameters" : [ @@ -18103,6 +18750,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "changeName", "parameters" : [ { @@ -18137,6 +18789,70 @@ ] }, + { + "getters" : [ + { + "name" : "temperature", + "type" : { + "double" : { + + } + } + }, + { + "name" : "description", + "type" : { + "string" : { + + } + } + }, + { + "name" : "humidity", + "type" : { + "double" : { + + } + } + } + ], + "methods" : [ + + ], + "name" : "WeatherData", + "setters" : [ + { + "functionName" : "temperature_set", + "name" : "temperature", + "type" : { + "double" : { + + } + } + }, + { + "functionName" : "description_set", + "name" : "description", + "type" : { + "string" : { + + } + } + }, + { + "functionName" : "humidity_set", + "name" : "humidity", + "type" : { + "double" : { + + } + } + } + ], + "staticMethods" : [ + + ] + }, { "constructor" : { "parameters" : [ @@ -18149,6 +18865,11 @@ "jsName" : "$WeirdClass", "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "jsName" : "method-with-dashes", "name" : "method_with_dashes", "parameters" : [ @@ -18187,6 +18908,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "value", "parameters" : [ @@ -18204,6 +18930,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "create", "parameters" : [ { @@ -18222,6 +18953,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "value", "parameters" : [ @@ -18233,6 +18969,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "makeDefault", "parameters" : [ @@ -18244,6 +18985,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "jsName" : "with-dashes", "name" : "with_dashes", "parameters" : [ @@ -18315,6 +19061,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "bark", "parameters" : [ @@ -18326,6 +19077,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "getIsCat", "parameters" : [ @@ -18376,6 +19132,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsTranslatePoint", "parameters" : [ { @@ -18438,6 +19199,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripInt", "parameters" : [ { @@ -18462,6 +19228,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUInt", "parameters" : [ { @@ -18486,6 +19257,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripInt8", "parameters" : [ { @@ -18510,6 +19286,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUInt8", "parameters" : [ { @@ -18534,6 +19315,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripInt16", "parameters" : [ { @@ -18558,6 +19344,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUInt16", "parameters" : [ { @@ -18582,6 +19373,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripInt32", "parameters" : [ { @@ -18606,6 +19402,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUInt32", "parameters" : [ { @@ -18630,6 +19431,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripInt64", "parameters" : [ { @@ -18654,6 +19460,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUInt64", "parameters" : [ { @@ -18678,6 +19489,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "runJsIntegerTypesSupportTests", "parameters" : [ @@ -18760,6 +19576,11 @@ ], "methods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "concatNumbers", "parameters" : [ { @@ -18792,6 +19613,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "concatLabels", "parameters" : [ { @@ -18818,6 +19644,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "firstLabel", "parameters" : [ { @@ -18889,6 +19720,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "makeJSClassWithArrayMembers", "parameters" : [ { @@ -19002,6 +19838,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsFunctionWithPackageAccess", "parameters" : [ @@ -19013,6 +19854,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsFunctionWithPublicAccess", "parameters" : [ @@ -19024,6 +19870,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsFunctionWithInternalAccess", "parameters" : [ @@ -19035,6 +19886,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsFunctionWithFilePrivateAccess", "parameters" : [ @@ -19046,6 +19902,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsFunctionWithPrivateAccess", "parameters" : [ @@ -19079,6 +19940,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalNumberNull", "parameters" : [ { @@ -19113,6 +19979,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalNumberUndefined", "parameters" : [ { @@ -19147,6 +20018,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalStringNull", "parameters" : [ { @@ -19175,6 +20051,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalStringUndefined", "parameters" : [ { @@ -19203,6 +20084,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalJSValueArrayNull", "parameters" : [ { @@ -19239,6 +20125,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalJSValueArrayUndefined", "parameters" : [ { @@ -19275,6 +20166,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalStringToStringDictionaryNull", "parameters" : [ { @@ -19311,6 +20207,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalStringToStringDictionaryUndefined", "parameters" : [ { @@ -19347,6 +20248,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "runJsOptionalSupportTests", "parameters" : [ @@ -19364,6 +20270,11 @@ { "functions" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "from" : "global", "name" : "gc", "parameters" : [ @@ -19390,6 +20301,11 @@ ], "staticMethods" : [ { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripGreeter", "parameters" : [ { @@ -19408,6 +20324,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripUUID", "parameters" : [ { @@ -19426,6 +20347,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsRoundTripOptionalGreeter", "parameters" : [ { @@ -19454,6 +20380,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsConsumeLeakCheck", "parameters" : [ { @@ -19472,6 +20403,11 @@ } }, { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, "name" : "jsConsumeOptionalLeakCheck", "parameters" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs new file mode 100644 index 000000000..f64531d4a --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs @@ -0,0 +1,46 @@ +// @ts-check + +import assert from 'node:assert'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["AsyncImportImports"]} + */ +export function getImports(importsContext) { + return { + jsAsyncRoundTripVoid: () => { + return Promise.resolve(); + }, + jsAsyncRoundTripNumber: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripBool: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripString: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripOptionalString: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripOptionalNumber: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripBoolArray: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripIntArray: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripStringArray: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripFeatureFlag: (v) => { + return Promise.resolve(v); + }, + }; +} + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export async function runAsyncWorksTests(exports) { + await exports.asyncRoundTripVoid(); +} diff --git a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts index e8533a3d8..9fef391c1 100644 --- a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts +++ b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts @@ -26,6 +26,13 @@ export class JsGreeter { export function runAsyncWorks(): Promise; +export interface WeatherData { + temperature: number; + description: string; + humidity: number; +} +export function fetchWeatherData(city: string): Promise; + // jsName tests export function $jsWeirdFunction(): number; diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 8eb9a0270..bb285aaee 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -13,6 +13,7 @@ import { getImports as getDictionarySupportImports } from './BridgeJSRuntimeTest import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs'; import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; import { getImports as getIntegerTypesSupportImports } from './BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs'; +import { getImports as getAsyncImportImports, runAsyncWorksTests } from './BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { @@ -124,9 +125,17 @@ export async function setupOptions(options, context) { if (!exports) { throw new Error("No exports!?"); } - BridgeJSRuntimeTests_runAsyncWorks(exports); + await runAsyncWorksTests(exports); return; }, + AsyncImportImports: getAsyncImportImports(importsContext), + fetchWeatherData: (city) => { + return Promise.resolve({ + temperature: city === "London" ? 15.5 : 25.0, + description: city === "London" ? "Cloudy" : "Sunny", + humidity: city === "London" ? 80 : 40, + }); + }, jsTranslatePoint: (point, dx, dy) => { return { x: (point.x | 0) + (dx | 0), y: (point.y | 0) + (dy | 0) }; }, @@ -1009,11 +1018,6 @@ function testStructSupport(exports) { assert.equal(fooContainerResult2.optionalFoo, null); } -/** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ -async function BridgeJSRuntimeTests_runAsyncWorks(exports) { - await exports.asyncRoundTripVoid(); -} - /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function BridgeJSRuntimeTests_runJsStructWorks(exports) { testStructSupport(exports); From df32a66879cd5e1bbd12308d2fc248cf84fef5d3 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Thu, 2 Apr 2026 17:27:37 +0100 Subject: [PATCH 033/140] Add JSRemote (#711) Add `JSRemote` API for accessing JSObjects without transfer The new API allows creating a handle for a `JSObject` that remains on its original JavaScript thread and hopping back to that thread to access the object when needed. This is useful for cases where the object cannot be transferred to another thread, but occasional access is still required or when we want to guarantee that an object is always accessed on the same thread for safety (it should be statically guaranteed with strict Sendable checking, but modules with language mode 5 don't have that). Example: ```swift let document = JSObject.global.document.object! let remoteDocument = JSRemote(document) let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) let title = try await Task(executorPreference: executor) { try await remoteDocument.withJSObject { document in document.title.string ?? "" } }.value ``` --- Examples/ActorOnWebWorker/Package.swift | 2 +- Examples/Multithreading/Package.swift | 2 +- Examples/OffscrenCanvas/Package.swift | 2 +- Plugins/PackageToJS/Templates/runtime.d.ts | 6 + Plugins/PackageToJS/Templates/runtime.mjs | 80 +++++++-- Runtime/src/index.ts | 125 +++++++++++--- Runtime/src/itc.ts | 9 + Runtime/src/types.ts | 1 + Sources/JavaScriptEventLoop/JSRemote.swift | 155 ++++++++++++++++++ .../_CJavaScriptKit/include/_CJavaScriptKit.h | 5 + .../WebWorkerTaskExecutorTests.swift | 146 +++++++++++++++++ 11 files changed, 495 insertions(+), 38 deletions(-) create mode 100644 Sources/JavaScriptEventLoop/JSRemote.swift diff --git a/Examples/ActorOnWebWorker/Package.swift b/Examples/ActorOnWebWorker/Package.swift index 82e87dfdc..04441a9a3 100644 --- a/Examples/ActorOnWebWorker/Package.swift +++ b/Examples/ActorOnWebWorker/Package.swift @@ -6,7 +6,7 @@ let package = Package( name: "Example", platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")], dependencies: [ - .package(path: "../../") + .package(name: "JavaScriptKit", path: "../../") ], targets: [ .executableTarget( diff --git a/Examples/Multithreading/Package.swift b/Examples/Multithreading/Package.swift index 4d1ebde70..ca147c5d8 100644 --- a/Examples/Multithreading/Package.swift +++ b/Examples/Multithreading/Package.swift @@ -6,7 +6,7 @@ let package = Package( name: "Example", platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")], dependencies: [ - .package(path: "../../"), + .package(name: "JavaScriptKit", path: "../../"), .package( url: "https://github.com/kateinoigakukun/chibi-ray", revision: "c8cab621a3338dd2f8e817d3785362409d3b8cf1" diff --git a/Examples/OffscrenCanvas/Package.swift b/Examples/OffscrenCanvas/Package.swift index ca6d7357f..54fa57747 100644 --- a/Examples/OffscrenCanvas/Package.swift +++ b/Examples/OffscrenCanvas/Package.swift @@ -6,7 +6,7 @@ let package = Package( name: "Example", platforms: [.macOS("15"), .iOS("18"), .watchOS("11"), .tvOS("18"), .visionOS("2")], dependencies: [ - .package(path: "../../") + .package(name: "JavaScriptKit", path: "../../") ], targets: [ .executableTarget( diff --git a/Plugins/PackageToJS/Templates/runtime.d.ts b/Plugins/PackageToJS/Templates/runtime.d.ts index 353db3894..87cbeea72 100644 --- a/Plugins/PackageToJS/Templates/runtime.d.ts +++ b/Plugins/PackageToJS/Templates/runtime.d.ts @@ -97,6 +97,10 @@ declare class ITCInterface { sendingContext: pointer; transfer: Transferable[]; }; + invokeRemoteJSObjectBody(invocationContext: pointer): { + object: undefined; + transfer: Transferable[]; + }; release(objectRef: ref): { object: undefined; transfer: Transferable[]; @@ -140,6 +144,8 @@ type ResponseMessage = { sourceTid: number; /** The context pointer of the request */ context: pointer; + /** The request method this response corresponds to */ + requestMethod: keyof ITCInterface; /** The response content */ response: { ok: true; diff --git a/Plugins/PackageToJS/Templates/runtime.mjs b/Plugins/PackageToJS/Templates/runtime.mjs index d79275476..ab85e7893 100644 --- a/Plugins/PackageToJS/Templates/runtime.mjs +++ b/Plugins/PackageToJS/Templates/runtime.mjs @@ -135,6 +135,9 @@ class ITCInterface { const transfer = transferringObjects.map((ref) => this.memory.getObject(ref)); return { object: objects, sendingContext, transfer }; } + invokeRemoteJSObjectBody(invocationContext) { + return { object: undefined, transfer: [] }; + } release(objectRef) { this.memory.release(objectRef); return { object: undefined, transfer: [] }; @@ -455,13 +458,51 @@ class SwiftRuntime { if (broker) return broker; const itcInterface = new ITCInterface(this.memory); + const defaultRequestHandler = (message) => { + const request = message.data.request; + // @ts-ignore dynamic dispatch by method name + const result = itcInterface[request.method].apply(itcInterface, request.parameters); + return { ok: true, value: result }; + }; + const requestHandlers = { + invokeRemoteJSObjectBody: (message) => { + const invocationContext = message.data.request + .parameters[0]; + const hasError = this.exports.swjs_invoke_remote_jsobject_body(invocationContext); + return { + ok: true, + value: { + object: hasError, + sendingContext: message.data.context, + transfer: [], + }, + }; + }, + }; + const defaultResponseHandler = (message) => { + if (message.data.response.ok) { + const object = this.memory.retain(message.data.response.value.object); + this.exports.swjs_receive_response(object, message.data.context); + } + else { + const error = deserializeError(message.data.response.error); + const errorObject = this.memory.retain(error); + this.exports.swjs_receive_error(errorObject, message.data.context); + } + }; + const responseHandlers = { + invokeRemoteJSObjectBody: (_message) => { + // Swift continuation is resumed on the owner thread. + }, + }; const newBroker = new MessageBroker((_a = this.tid) !== null && _a !== void 0 ? _a : -1, threadChannel, { onRequest: (message) => { + var _a; let returnValue; try { - // @ts-ignore - const result = itcInterface[message.data.request.method](...message.data.request.parameters); - returnValue = { ok: true, value: result }; + const method = message.data.request.method; + const handler = (_a = requestHandlers[method]) !== null && _a !== void 0 ? _a : defaultRequestHandler; + returnValue = handler(message); } catch (error) { returnValue = { @@ -474,6 +515,7 @@ class SwiftRuntime { data: { sourceTid: message.data.sourceTid, context: message.data.context, + requestMethod: message.data.request.method, response: returnValue, }, }; @@ -489,15 +531,10 @@ class SwiftRuntime { } }, onResponse: (message) => { - if (message.data.response.ok) { - const object = this.memory.retain(message.data.response.value.object); - this.exports.swjs_receive_response(object, message.data.context); - } - else { - const error = deserializeError(message.data.response.error); - const errorObject = this.memory.retain(error); - this.exports.swjs_receive_error(errorObject, message.data.context); - } + var _a; + const method = message.data.requestMethod; + const handler = (_a = responseHandlers[method]) !== null && _a !== void 0 ? _a : defaultResponseHandler; + handler(message); }, }); broker = newBroker; @@ -842,6 +879,25 @@ class SwiftRuntime { }, }); }, + swjs_request_remote_jsobject_body: (object_source_tid, invocation_context) => { + var _a; + if (!this.options.threadChannel) { + throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request remote JSObject access."); + } + const broker = getMessageBroker(this.options.threadChannel); + broker.request({ + type: "request", + data: { + sourceTid: (_a = this.tid) !== null && _a !== void 0 ? _a : MAIN_THREAD_TID, + targetTid: object_source_tid, + context: invocation_context, + request: { + method: "invokeRemoteJSObjectBody", + parameters: [invocation_context], + }, + }, + }); + }, }; } postMessageToMainThread(message, transfer = []) { diff --git a/Runtime/src/index.ts b/Runtime/src/index.ts index 5d6fe258f..7d75a6801 100644 --- a/Runtime/src/index.ts +++ b/Runtime/src/index.ts @@ -11,6 +11,7 @@ import { deserializeError, MainToWorkerMessage, MessageBroker, + RequestMessage, ResponseMessage, ITCInterface, serializeError, @@ -265,29 +266,98 @@ export class SwiftRuntime { const getMessageBroker = (threadChannel: SwiftRuntimeThreadChannel) => { if (broker) return broker; const itcInterface = new ITCInterface(this.memory); + type ITCMethodName = keyof ITCInterface; + + const defaultRequestHandler = ( + message: RequestMessage, + ): ResponseMessage["data"]["response"] => { + const request = message.data.request; + // @ts-ignore dynamic dispatch by method name + const result = itcInterface[request.method].apply( + itcInterface, + request.parameters as any[], + ); + return { ok: true, value: result }; + }; + + const requestHandlers: Partial< + Record< + ITCMethodName, + ( + message: RequestMessage, + ) => ResponseMessage["data"]["response"] + > + > = { + invokeRemoteJSObjectBody: (message) => { + const invocationContext = message.data.request + .parameters[0] as pointer; + const hasError = + this.exports.swjs_invoke_remote_jsobject_body( + invocationContext, + ); + return { + ok: true, + value: { + object: hasError, + sendingContext: message.data.context, + transfer: [], + }, + }; + }, + }; + + const defaultResponseHandler = (message: ResponseMessage) => { + if (message.data.response.ok) { + const object = this.memory.retain( + message.data.response.value.object, + ); + this.exports.swjs_receive_response( + object, + message.data.context, + ); + } else { + const error = deserializeError(message.data.response.error); + const errorObject = this.memory.retain(error); + this.exports.swjs_receive_error( + errorObject, + message.data.context, + ); + } + }; + + const responseHandlers: Partial< + Record void> + > = { + invokeRemoteJSObjectBody: (_message) => { + // Swift continuation is resumed on the owner thread. + }, + }; + const newBroker = new MessageBroker(this.tid ?? -1, threadChannel, { onRequest: (message) => { let returnValue: ResponseMessage["data"]["response"]; try { - // @ts-ignore - const result = itcInterface[ - message.data.request.method - ](...message.data.request.parameters); - returnValue = { ok: true, value: result }; + const method = message.data.request.method; + const handler = + requestHandlers[method] ?? defaultRequestHandler; + returnValue = handler(message); } catch (error) { returnValue = { ok: false, error: serializeError(error), }; } + const responseMessage: ResponseMessage = { type: "response", data: { sourceTid: message.data.sourceTid, context: message.data.context, + requestMethod: message.data.request.method, response: returnValue, }, }; + try { newBroker.reply(responseMessage); } catch (error) { @@ -303,24 +373,10 @@ export class SwiftRuntime { } }, onResponse: (message) => { - if (message.data.response.ok) { - const object = this.memory.retain( - message.data.response.value.object, - ); - this.exports.swjs_receive_response( - object, - message.data.context, - ); - } else { - const error = deserializeError( - message.data.response.error, - ); - const errorObject = this.memory.retain(error); - this.exports.swjs_receive_error( - errorObject, - message.data.context, - ); - } + const method = message.data.requestMethod; + const handler = + responseHandlers[method] ?? defaultResponseHandler; + handler(message); }, }); broker = newBroker; @@ -934,6 +990,29 @@ export class SwiftRuntime { }, }); }, + swjs_request_remote_jsobject_body: ( + object_source_tid: number, + invocation_context: pointer, + ) => { + if (!this.options.threadChannel) { + throw new Error( + "threadChannel is not set in options given to SwiftRuntime. Please set it to request remote JSObject access.", + ); + } + const broker = getMessageBroker(this.options.threadChannel); + broker.request({ + type: "request", + data: { + sourceTid: this.tid ?? MAIN_THREAD_TID, + targetTid: object_source_tid, + context: invocation_context, + request: { + method: "invokeRemoteJSObjectBody", + parameters: [invocation_context], + }, + }, + }); + }, }; } diff --git a/Runtime/src/itc.ts b/Runtime/src/itc.ts index 9fadff54a..5d110762b 100644 --- a/Runtime/src/itc.ts +++ b/Runtime/src/itc.ts @@ -117,6 +117,13 @@ export class ITCInterface { return { object: objects, sendingContext, transfer }; } + invokeRemoteJSObjectBody(invocationContext: pointer): { + object: undefined; + transfer: Transferable[]; + } { + return { object: undefined, transfer: [] }; + } + release(objectRef: ref): { object: undefined; transfer: Transferable[] } { this.memory.release(objectRef); return { object: undefined, transfer: [] }; @@ -163,6 +170,8 @@ export type ResponseMessage = { sourceTid: number; /** The context pointer of the request */ context: pointer; + /** The request method this response corresponds to */ + requestMethod: keyof ITCInterface; /** The response content */ response: | { diff --git a/Runtime/src/types.ts b/Runtime/src/types.ts index b39e949b2..bc83fcd22 100644 --- a/Runtime/src/types.ts +++ b/Runtime/src/types.ts @@ -22,6 +22,7 @@ export interface ExportedFunctions { swjs_wake_worker_thread(): void; swjs_receive_response(object: ref, transferring: pointer): void; swjs_receive_error(error: ref, context: number): void; + swjs_invoke_remote_jsobject_body(context: pointer): number; } export const enum LibraryFeatures { diff --git a/Sources/JavaScriptEventLoop/JSRemote.swift b/Sources/JavaScriptEventLoop/JSRemote.swift new file mode 100644 index 000000000..4f488d7b8 --- /dev/null +++ b/Sources/JavaScriptEventLoop/JSRemote.swift @@ -0,0 +1,155 @@ +import _Concurrency +@_spi(JSObject_id) import JavaScriptKit +import _CJavaScriptKit + +/// A sendable handle for temporarily accessing a `JSObject` on its owning thread. +/// +/// `JSRemote` lets you share a reference to a JavaScript object across Swift concurrency +/// domains without transferring or cloning the object itself. Instead, the object stays +/// owned by its original JavaScript thread, and `withJSObject(_:)` schedules a closure to +/// run on that owner when needed. +/// +/// This is useful when you need occasional coordinated access to a JavaScript object from +/// another thread, but cannot or should not move the object with `JSSending`. +/// +/// - Note: `JSRemote` does not make the underlying `JSObject` itself thread-safe. The object +/// may only be touched inside `withJSObject(_:)`. +/// +/// ## Example +/// +/// ```swift +/// let document = JSObject.global.document.object! +/// let remoteDocument = JSRemote(document) +/// +/// let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) +/// let title = try await Task(executorPreference: executor) { +/// try await remoteDocument.withJSObject { document in +/// document.title.string ?? "" +/// } +/// }.value +/// ``` +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public struct JSRemote: @unchecked Sendable { + private final class Storage { + let sourceObject: JSObject + let sourceTid: Int32 + + init(sourceObject: JSObject, sourceTid: Int32) { + self.sourceObject = sourceObject + self.sourceTid = sourceTid + } + } + + private let storage: Storage + + fileprivate init(sourceObject: JSObject, sourceTid: Int32) { + self.storage = Storage(sourceObject: sourceObject, sourceTid: sourceTid) + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension JSRemote where T == JSObject { + /// Creates a remote handle for a `JSObject`. + /// + /// The object remains owned by its current JavaScript thread. Access it later by calling + /// `withJSObject(_:)`, which executes the closure on the owning thread when necessary. + /// + /// ## Example + /// + /// ```swift + /// let remoteWindow = JSRemote(JSObject.global) + /// ``` + /// + /// - Parameter object: The JavaScript object to reference remotely. + public init(_ object: JSObject) { + #if compiler(>=6.1) && _runtime(_multithreaded) + self.init(sourceObject: object, sourceTid: object.ownerTid) + #else + self.init(sourceObject: object, sourceTid: -1) + #endif + } + + /// Performs an operation with the underlying `JSObject` on its owning thread. + /// + /// If the caller is already running on the thread that owns the object, `body` executes + /// immediately. Otherwise, this method asynchronously requests execution on the owner and + /// resumes when the closure completes. + /// + /// Use this API when the object must stay on its original thread but a result derived from + /// that object needs to be produced in another Swift concurrency context. + /// + /// ## Example + /// + /// ```swift + /// let location = try await remoteWindow.withJSObject { window in + /// window.location.href.string ?? "" + /// } + /// ``` + /// + /// - Parameter body: A sendable closure that receives the owned `JSObject`. + /// - Returns: The value produced by `body`. + /// - Throws: Any error thrown by `body`. + public func withJSObject( + _ body: @Sendable @escaping (JSObject) throws(E) -> R + ) async throws(E) -> sending R { + #if compiler(>=6.1) && _runtime(_multithreaded) + if storage.sourceTid == swjs_get_worker_thread_id_cached() { + return try body(storage.sourceObject) + } + let result: Result = await withCheckedContinuation { continuation in + let context = _JSRemoteContext( + sourceObject: storage.sourceObject, + body: body, + continuation: continuation + ) + swjs_request_remote_jsobject_body( + storage.sourceTid, + Unmanaged.passRetained(context).toOpaque() + ) + } + return try result.get() + #else + return try body(storage.sourceObject) + #endif + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +private final class _JSRemoteContext: @unchecked Sendable { + let invokeBody: () -> Bool + + init( + sourceObject: JSObject, + body: @escaping @Sendable (JSObject) throws(E) -> R, + continuation: CheckedContinuation, Never> + ) { + self.invokeBody = { + // NOTE: Sendability violation here for `sourceObject` + // Even though `JSObject` is not Sendable, it is safe to access it here + // because this invokeBody closure will only be executed on the owning thread. + do throws(E) { + continuation.resume(returning: .success(try body(sourceObject))) + } catch { + continuation.resume(returning: .failure(error)) + } + return false + } + } +} + +#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) + guard let contextPtr else { return true } + let context = Unmanaged<_JSRemoteContext>.fromOpaque(contextPtr).takeRetainedValue() + + return context.invokeBody() + #else + _ = contextPtr + return true + #endif +} diff --git a/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h b/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h index 28e7b5e3d..3800a6d9e 100644 --- a/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h +++ b/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h @@ -355,4 +355,9 @@ IMPORT_JS_FUNCTION(swjs_request_sending_objects, void, (const JavaScriptObjectRe int object_source_tid, void * _Nonnull sending_context)) +/// Requests invoking a Swift closure associated with `invocation_context` on `object_source_tid`. +/// This must be called from a non-owner thread and will asynchronously notify completion. +IMPORT_JS_FUNCTION(swjs_request_remote_jsobject_body, void, (int object_source_tid, + void * _Nonnull invocation_context)) + #endif /* _CJavaScriptKit_h */ diff --git a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift index f743d8ef0..54559f3d8 100644 --- a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift +++ b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift @@ -618,6 +618,152 @@ final class WebWorkerTaskExecutorTests: XCTestCase { XCTAssertEqual(object["test"].string!, "Hello, World!") } + func testRemoteMainToWorkerAccess() async throws { + let object = JSObject.global.Object.function!.new() + object["value"] = 42 + let remote = JSRemote(object) + + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + let task = Task(executorPreference: executor) { + try await remote.withJSObject { object in + object["value"].number! + } + } + + let value = try await task.value + XCTAssertEqual(value, 42) + } + + func testRemoteWorkerToMainAccess() async throws { + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + let task = Task(executorPreference: executor) { + let object = JSObject.global.Object.function!.new() + object["value"] = 99 + let remote = JSRemote(object) + return remote + } + + let remote = await task.value + let result = try await remote.withJSObject { object in + object["value"].number! + } + XCTAssertEqual(result, 99) + } + + func testRemoteSameThreadFastPath() async throws { + let object = JSObject.global.Object.function!.new() + object["flag"] = 1 + let remote = JSRemote(object) + + let result = try await remote.withJSObject { object in + object["flag"].number! + } + XCTAssertEqual(result, 1) + } + + func testRemoteCanBeUsedMultipleTimesAcrossThreads() async throws { + let object = JSObject.global.Object.function!.new() + object["count"] = 0 + let remote = JSRemote(object) + + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + let task = Task(executorPreference: executor) { + let first = try await remote.withJSObject { object in + let nextValue = object["count"].number! + 1 + object["count"] = .number(nextValue) + return nextValue + } + let second = try await remote.withJSObject { object in + let nextValue = object["count"].number! + 1 + object["count"] = .number(nextValue) + return nextValue + } + return (first, second) + } + + let (first, second) = try await task.value + XCTAssertEqual(first, 1) + XCTAssertEqual(second, 2) + XCTAssertEqual(object["count"].number!, 2) + } + + func testRemoteConcurrentAccessFromWorkerTasks() async throws { + let object = JSObject.global.Object.function!.new() + object["value"] = 42 + let remote = JSRemote(object) + + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 2) + defer { executor.terminate() } + + let results = try await withThrowingTaskGroup(of: Int.self, returning: [Int].self) { group in + for _ in 0..<8 { + group.addTask(executorPreference: executor) { + try await remote.withJSObject { object in + Int(object["value"].number!) + } + } + } + + var results: [Int] = [] + for try await value in group { + results.append(value) + } + return results + } + + XCTAssertEqual(results.count, 8) + XCTAssertEqual(results, Array(repeating: 42, count: 8)) + } + + func testRemoteMutationIsVisibleOnOwnerThread() async throws { + let object = JSObject.global.Object.function!.new() + object["value"] = 10 + let remote = JSRemote(object) + + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + let task = Task(executorPreference: executor) { + try await remote.withJSObject { object in + object["value"] = .number(object["value"].number! + 5) + } + } + + _ = try await task.value + XCTAssertEqual(object["value"].number!, 15) + } + + func testRemoteThrowsTypedError() async throws { + struct TestError: Error, Equatable { + let message: String + } + + let object = JSObject.global.Object.function!.new() + let remote = JSRemote(object) + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + let task = Task(executorPreference: executor) { + do { + _ = try await remote.withJSObject { _ in + throw TestError(message: "boom") + } + return "unexpected" + } catch { + return String(describing: error) + } + } + + let errorDescription = try await task.value + XCTAssertTrue(errorDescription.contains("boom"), errorDescription) + } + func testThrowJSExceptionAcrossThreads() async throws { let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) let task = Task(executorPreference: executor) { From 5ceeb0802d71c59e126d58ea8cea7f97c6c61e35 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 08:56:02 +0000 Subject: [PATCH 034/140] Bump vite from 7.3.1 to 7.3.2 (#712) Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.3.1 to 7.3.2. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 7.3.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5eab62401..1c95a1ce2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1582,9 +1582,9 @@ "dev": true }, "node_modules/vite": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", - "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz", + "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", "dependencies": { From 76543856201aca11bec46c3cb1cbd9c619ac3d4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 10:19:19 +0100 Subject: [PATCH 035/140] Bump actions/deploy-pages from 4 to 5 (#710) Bumps [actions/deploy-pages](https://github.com/actions/deploy-pages) from 4 to 5. - [Release notes](https://github.com/actions/deploy-pages/releases) - [Commits](https://github.com/actions/deploy-pages/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/deploy-pages dependency-version: '5' 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 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 419c772a0..e8118a481 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -199,4 +199,4 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@v5 From af88676816797ac9e4ab68870813999a8267ce28 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 10:19:55 +0100 Subject: [PATCH 036/140] Bump picomatch from 4.0.3 to 4.0.4 (#713) Bumps [picomatch](https://github.com/micromatch/picomatch) from 4.0.3 to 4.0.4. - [Release notes](https://github.com/micromatch/picomatch/releases) - [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md) - [Commits](https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4) --- updated-dependencies: - dependency-name: picomatch dependency-version: 4.0.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1c95a1ce2..ea24d1645 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1289,9 +1289,9 @@ "dev": true }, "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", "engines": { From 9f149ccbae947e79c1d4607a941dba06b5c55947 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 12:35:21 +0200 Subject: [PATCH 037/140] BridgeJS: Fix for-loop emission in stack codegen Three `StackCodegen` helpers built their `for`-loops from separate `CodeBlockItemSyntax` fragments ("for ... {", body, "}"). swift-syntax 603's formatter then renders such partial statements with the closing brace glued to the previous line. Combine each for-loop into a single multi-line `CodeBlockItemSyntax` so the formatter produces consistent output across swift-syntax 600-603. Also fix a latent bug in `StructCodegen.generateStructLowerCode` and `EnumCodegen.generatePayloadPushingCode`: they concatenated lowering statements via `CodeBlockItemListSyntax(statements).description` which does not insert separators between items that lack leading trivia. The thunk builder path was fine because `append` explicitly adds `.newline` trivia, but any multi-statement lowering routed through a struct field or enum payload was silently glued onto a single line. Iterate over the statements and write each one individually through the printer. Add regression coverage for the previously untested codepaths: - `[String: MyProtocol]` as a function return, class property getter, and parameter (exercises `lowerProtocolDictionaryStatements`). - A `@JS struct` field of type `[String: Int?]` (exercises `lowerDictionaryStatementsInline` via `generateStructLowerCode`). --- .../Sources/BridgeJSCore/ExportSwift.swift | 97 +++++++++++-------- .../Inputs/MacroSwift/DictionaryTypes.swift | 6 ++ .../Inputs/MacroSwift/Protocol.swift | 8 ++ .../BridgeJSCodegenTests/DictionaryTypes.json | 65 +++++++++++++ .../DictionaryTypes.swift | 65 +++++++++++++ .../BridgeJSCodegenTests/Protocol.json | 47 +++++++++ .../BridgeJSCodegenTests/Protocol.swift | 46 ++++++++- .../BridgeJSLinkTests/DictionaryTypes.d.ts | 5 + .../BridgeJSLinkTests/DictionaryTypes.js | 56 +++++++++++ .../BridgeJSLinkTests/Protocol.d.ts | 2 + .../BridgeJSLinkTests/Protocol.js | 51 ++++++++++ .../Generated/BridgeJS.swift | 11 ++- 12 files changed, 411 insertions(+), 48 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index ca7bdc3c2..f7824711f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -827,15 +827,15 @@ struct StackCodegen { accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { - var statements: [CodeBlockItemSyntax] = [] let elemVar = "__bjs_elem_\(varPrefix)" - statements.append("for \(raw: elemVar) in \(raw: accessor) {") - statements.append( - " _swift_js_push_i32((\(raw: elemVar) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" - ) - statements.append("}") - statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") - return statements + return [ + """ + for \(raw: elemVar) in \(raw: accessor) { + _swift_js_push_i32((\(raw: elemVar) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } + """, + "_swift_js_push_i32(Int32(\(raw: accessor).count))", + ] } private func lowerDictionaryStatements( @@ -866,49 +866,58 @@ struct StackCodegen { accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { - var statements: [CodeBlockItemSyntax] = [] let pairVarName = "__bjs_kv_\(varPrefix)" - statements.append("for \(raw: pairVarName) in \(raw: accessor) {") - statements.append("let __bjs_key_\(raw: varPrefix) = \(raw: pairVarName).key") - statements.append("let __bjs_value_\(raw: varPrefix) = \(raw: pairVarName).value") - - let keyStatements = lowerStatements( - for: .string, - accessor: "__bjs_key_\(varPrefix)", - varPrefix: "\(varPrefix)_key" + let keyVarName = "__bjs_key_\(varPrefix)" + let valueVarName = "__bjs_value_\(varPrefix)" + + // The dispatch in `lowerDictionaryStatements` routes only .nullable and .closure value + // types into this helper, both of which produce single-line lowering statements, so we can + // join their descriptions into the for-body as plain lines without worrying about nested + // multi-statement lowering. + var bodyLines: [String] = [ + "let \(keyVarName) = \(pairVarName).key", + "let \(valueVarName) = \(pairVarName).value", + ] + bodyLines.append( + contentsOf: lowerStatements( + for: .string, + accessor: keyVarName, + varPrefix: "\(varPrefix)_key" + ).map { $0.description } ) - for stmt in keyStatements { - statements.append(stmt) - } - - let valueStatements = lowerStatements( - for: valueType, - accessor: "__bjs_value_\(varPrefix)", - varPrefix: "\(varPrefix)_value" + bodyLines.append( + contentsOf: lowerStatements( + for: valueType, + accessor: valueVarName, + varPrefix: "\(varPrefix)_value" + ).map { $0.description } ) - for stmt in valueStatements { - statements.append(stmt) - } + let body = bodyLines.joined(separator: "\n ") - statements.append("}") - statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") - return statements + return [ + """ + for \(raw: pairVarName) in \(raw: accessor) { + \(raw: body) + } + """, + "_swift_js_push_i32(Int32(\(raw: accessor).count))", + ] } private func lowerProtocolDictionaryStatements( accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { - var statements: [CodeBlockItemSyntax] = [] let pairVar = "__bjs_kv_\(varPrefix)" - statements.append("for \(raw: pairVar) in \(raw: accessor) {") - statements.append(" \(raw: pairVar).key.bridgeJSStackPush()") - statements.append( - " _swift_js_push_i32((\(raw: pairVar).value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" - ) - statements.append("}") - statements.append("_swift_js_push_i32(Int32(\(raw: accessor).count))") - return statements + return [ + """ + for \(raw: pairVar) in \(raw: accessor) { + \(raw: pairVar).key.bridgeJSStackPush() + _swift_js_push_i32((\(raw: pairVar).value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } + """, + "_swift_js_push_i32(Int32(\(raw: accessor).count))", + ] } } @@ -1073,7 +1082,9 @@ struct EnumCodegen { accessor: paramName, varPrefix: paramName ) - printer.write(multilineString: CodeBlockItemListSyntax(statements).description) + for statement in statements { + printer.write(multilineString: statement.description) + } } } @@ -1207,7 +1218,9 @@ struct StructCodegen { accessor: accessor, varPrefix: property.name ) - printer.write(multilineString: CodeBlockItemListSyntax(statements).description) + for statement in statements { + printer.write(multilineString: statement.description) + } } return printer.lines diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift index c699ea79b..a45bf1dd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift @@ -6,10 +6,16 @@ } } +@JS struct Counters { + var name: String + var counts: [String: Int?] +} + @JS func mirrorDictionary(_ values: [String: Int]) -> [String: Int] @JS func optionalDictionary(_ values: [String: String]?) -> [String: String]? @JS func nestedDictionary(_ values: [String: [Int]]) -> [String: [Int]] @JS func boxDictionary(_ boxes: [String: Box]) -> [String: Box] @JS func optionalBoxDictionary(_ boxes: [String: Box?]) -> [String: Box?] +@JS func roundtripCounters(_ counters: Counters) -> Counters @JSFunction func importMirrorDictionary(_ values: [String: Double]) throws(JSException) -> [String: Double] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift index fbbad0615..bdb700d69 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift @@ -102,8 +102,12 @@ import JavaScriptKit @JS var delegates: [MyViewControllerDelegate] + @JS + var delegatesByName: [String: MyViewControllerDelegate] + @JS init(delegates: [MyViewControllerDelegate]) { self.delegates = delegates + self.delegatesByName = [:] } @JS func notifyAll() { @@ -114,3 +118,7 @@ import JavaScriptKit } @JS func processDelegates(_ delegates: [MyViewControllerDelegate]) -> [MyViewControllerDelegate] + +@JS func processDelegatesByName( + _ delegates: [String: MyViewControllerDelegate] +) -> [String: MyViewControllerDelegate] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index ea707098d..e18586e1c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -221,13 +221,78 @@ } } } + }, + { + "abiName" : "bjs_roundtripCounters", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripCounters", + "parameters" : [ + { + "label" : "_", + "name" : "counters", + "type" : { + "swiftStruct" : { + "_0" : "Counters" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Counters" + } + } } ], "protocols" : [ ], "structs" : [ + { + "methods" : [ + + ], + "name" : "Counters", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "counts", + "type" : { + "dictionary" : { + "_0" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "_1" : "null" + } + } + } + } + } + ], + "swiftCallName" : "Counters" + } ] }, "imported" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index dc0a54bcf..26a4c087e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -1,3 +1,57 @@ +extension Counters: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Counters { + let counts = [String: Optional].bridgeJSStackPop() + let name = String.bridgeJSStackPop() + return Counters(name: name, counts: counts) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + for __bjs_kv_counts in self.counts { + let __bjs_key_counts = __bjs_kv_counts.key + let __bjs_value_counts = __bjs_kv_counts.value + __bjs_key_counts.bridgeJSStackPush() + __bjs_value_counts.bridgeJSStackPush() + } + _swift_js_push_i32(Int32(self.counts.count)) + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Counters(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Counters())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Counters") +fileprivate func _bjs_struct_lower_Counters_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Counters_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Counters(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Counters_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Counters") +fileprivate func _bjs_struct_lift_Counters_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Counters_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Counters() -> Int32 { + return _bjs_struct_lift_Counters_extern() +} + @_expose(wasm, "bjs_mirrorDictionary") @_cdecl("bjs_mirrorDictionary") public func _bjs_mirrorDictionary() -> Void { @@ -53,6 +107,17 @@ public func _bjs_optionalBoxDictionary() -> Void { #endif } +@_expose(wasm, "bjs_roundtripCounters") +@_cdecl("bjs_roundtripCounters") +public func _bjs_roundtripCounters() -> Void { + #if arch(wasm32) + let ret = roundtripCounters(_: Counters.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Box_deinit") @_cdecl("bjs_Box_deinit") public func _bjs_Box_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index 757115c59..b46d1125e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -317,6 +317,20 @@ } } } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "delegatesByName", + "type" : { + "dictionary" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } } ], "swiftCallName" : "DelegateManager" @@ -502,6 +516,39 @@ } } } + }, + { + "abiName" : "bjs_processDelegatesByName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDelegatesByName", + "parameters" : [ + { + "label" : "_", + "name" : "delegates", + "type" : { + "dictionary" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } } ], "protocols" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index cf7464cc3..745ec6cc9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -698,7 +698,23 @@ public func _bjs_processDelegates() -> Void { #if arch(wasm32) let ret = processDelegates(_: [AnyMyViewControllerDelegate].bridgeJSStackPop()) for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())} + _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_processDelegatesByName") +@_cdecl("bjs_processDelegatesByName") +public func _bjs_processDelegatesByName() -> Void { + #if arch(wasm32) + let ret = processDelegatesByName(_: [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter()) + 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") @@ -955,7 +971,8 @@ public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) #if arch(wasm32) let ret = DelegateManager.bridgeJSLiftParameter(_self).delegates for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())} + _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -972,6 +989,31 @@ public func _bjs_DelegateManager_delegates_set(_ _self: UnsafeMutableRawPointer) #endif } +@_expose(wasm, "bjs_DelegateManager_delegatesByName_get") +@_cdecl("bjs_DelegateManager_delegatesByName_get") +public func _bjs_DelegateManager_delegatesByName_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = DelegateManager.bridgeJSLiftParameter(_self).delegatesByName + 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_DelegateManager_delegatesByName_set") +@_cdecl("bjs_DelegateManager_delegatesByName_set") +public func _bjs_DelegateManager_delegatesByName_set(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + DelegateManager.bridgeJSLiftParameter(_self).delegatesByName = [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_DelegateManager_deinit") @_cdecl("bjs_DelegateManager_deinit") public func _bjs_DelegateManager_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts index dadcc74ba..f14b29aa4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts @@ -4,6 +4,10 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export interface Counters { + name: string; + counts: Record; +} /// Represents a Swift heap object like a class instance or an actor instance. export interface SwiftHeapObject { /// Release the heap object. @@ -21,6 +25,7 @@ export type Exports = { nestedDictionary(values: Record): Record; boxDictionary(boxes: Record): Record; optionalBoxDictionary(boxes: Record): Record; + roundtripCounters(counters: Counters): Counters; } 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 1e9059e34..b6cf2c253 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -30,6 +30,46 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + 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); + }, + 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 }; + } + }); return { /** @@ -99,6 +139,13 @@ export async function createInstantiator(options, swift) { bjs["swift_js_pop_i64"] = function() { return i64Stack.pop(); } + bjs["swift_js_struct_lower_Counters"] = function(objectId) { + structHelpers.Counters.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Counters"] = function() { + const value = structHelpers.Counters.lift(); + return swift.memory.retain(value); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -271,6 +318,9 @@ export async function createInstantiator(options, swift) { } } + const CountersHelpers = __bjs_createCountersHelpers(); + structHelpers.Counters = CountersHelpers; + const exports = { Box, mirrorDictionary: function bjs_mirrorDictionary(values) { @@ -414,6 +464,12 @@ export async function createInstantiator(options, swift) { } return dictResult; }, + roundtripCounters: function bjs_roundtripCounters(counters) { + structHelpers.Counters.lower(counters); + instance.exports.bjs_roundtripCounters(); + const structValue = structHelpers.Counters.lift(); + return structValue; + }, }; _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 4c09ad85f..27cd9212b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -93,6 +93,7 @@ export interface MyViewController extends SwiftHeapObject { export interface DelegateManager extends SwiftHeapObject { notifyAll(): void; delegates: MyViewControllerDelegate[]; + delegatesByName: Record; } export type Exports = { Helper: { @@ -105,6 +106,7 @@ export type Exports = { new(delegates: MyViewControllerDelegate[]): DelegateManager; } processDelegates(delegates: MyViewControllerDelegate[]): MyViewControllerDelegate[]; + processDelegatesByName(delegates: Record): Record; Direction: DirectionObject ExampleEnum: ExampleEnumObject Result: ResultObject diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index e606c3a77..f82e41703 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -718,6 +718,33 @@ export async function createInstantiator(options, swift) { i32Stack.push(value.length); 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; + } + 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); + instance.exports.bjs_DelegateManager_delegatesByName_set(this.pointer); + } } const ResultHelpers = __bjs_createResultValuesHelpers(); enumHelpers.Result = ResultHelpers; @@ -744,6 +771,30 @@ export async function createInstantiator(options, swift) { arrayResult.reverse(); 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); + 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; + } + return dictResult; + }, Direction: DirectionValues, ExampleEnum: ExampleEnumValues, Result: ResultValues, diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 71e5ef537..4f5b6e477 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3420,7 +3420,8 @@ public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { #if arch(wasm32) let ret = ArraySupportExports.roundTripProtocolArray(_: [AnyArrayElementProtocol].bridgeJSStackPop()) for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())} + _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -10089,7 +10090,8 @@ 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((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -10102,8 +10104,9 @@ public func _bjs_ProtocolReturnTests_static_createNativeProcessorDictionary() -> #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())} + __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") From 9f2b43213a5a1b33489a476a01555903f50a32a4 Mon Sep 17 00:00:00 2001 From: Stephan Diederich Date: Thu, 9 Apr 2026 13:32:20 +0200 Subject: [PATCH 038/140] flip `Package.swift` file versioning (#715) makes `Package.swift` be the newest, while supporting older versions with concrete versions baked in as mentioned in https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/swiftversionspecificpackaging/#Version-specific-Manifest-Selection --- Package.swift | 19 +++++++++++++++---- ...swift-6.2.swift => Package@swift-6.1.swift | 19 ++++--------------- 2 files changed, 19 insertions(+), 19 deletions(-) rename Package@swift-6.2.swift => Package@swift-6.1.swift (91%) diff --git a/Package.swift b/Package.swift index 60adb7a5f..20583865b 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.1 +// swift-tools-version:6.2 import CompilerPluginSupport import PackageDescription @@ -7,6 +7,13 @@ import PackageDescription 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 enableTracingByEnv = Context.environment["JAVASCRIPTKIT_ENABLE_TRACING"].flatMap(Bool.init) ?? false + +let tracingTrait = Trait( + name: "Tracing", + description: "Enable opt-in Swift <-> JavaScript bridge tracing hooks.", + enabledTraits: [] +) let testingLinkerFlags: [LinkerSetting] = [ .unsafeFlags( @@ -39,6 +46,7 @@ let package = Package( .plugin(name: "BridgeJS", targets: ["BridgeJS"]), .plugin(name: "BridgeJSCommandPlugin", targets: ["BridgeJSCommandPlugin"]), ], + traits: [tracingTrait], dependencies: [ .package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"603.0.0") ], @@ -53,8 +61,10 @@ let package = Package( .unsafeFlags(["-fdeclspec"]) ] : nil, swiftSettings: [ - .enableExperimentalFeature("Extern") + .enableExperimentalFeature("Extern"), + .define("Tracing", .when(traits: ["Tracing"])), ] + + (enableTracingByEnv ? [.define("Tracing")] : []) + (shouldBuildForEmbedded ? [ .enableExperimentalFeature("Embedded"), @@ -74,8 +84,9 @@ let package = Package( name: "JavaScriptKitTests", dependencies: ["JavaScriptKit"], swiftSettings: [ - .enableExperimentalFeature("Extern") - ], + .enableExperimentalFeature("Extern"), + .define("Tracing", .when(traits: ["Tracing"])), + ] + (enableTracingByEnv ? [.define("Tracing")] : []), linkerSettings: testingLinkerFlags ), diff --git a/Package@swift-6.2.swift b/Package@swift-6.1.swift similarity index 91% rename from Package@swift-6.2.swift rename to Package@swift-6.1.swift index 20583865b..60adb7a5f 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.1.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.2 +// swift-tools-version:6.1 import CompilerPluginSupport import PackageDescription @@ -7,13 +7,6 @@ import PackageDescription 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 enableTracingByEnv = Context.environment["JAVASCRIPTKIT_ENABLE_TRACING"].flatMap(Bool.init) ?? false - -let tracingTrait = Trait( - name: "Tracing", - description: "Enable opt-in Swift <-> JavaScript bridge tracing hooks.", - enabledTraits: [] -) let testingLinkerFlags: [LinkerSetting] = [ .unsafeFlags( @@ -46,7 +39,6 @@ let package = Package( .plugin(name: "BridgeJS", targets: ["BridgeJS"]), .plugin(name: "BridgeJSCommandPlugin", targets: ["BridgeJSCommandPlugin"]), ], - traits: [tracingTrait], dependencies: [ .package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"603.0.0") ], @@ -61,10 +53,8 @@ let package = Package( .unsafeFlags(["-fdeclspec"]) ] : nil, swiftSettings: [ - .enableExperimentalFeature("Extern"), - .define("Tracing", .when(traits: ["Tracing"])), + .enableExperimentalFeature("Extern") ] - + (enableTracingByEnv ? [.define("Tracing")] : []) + (shouldBuildForEmbedded ? [ .enableExperimentalFeature("Embedded"), @@ -84,9 +74,8 @@ let package = Package( name: "JavaScriptKitTests", dependencies: ["JavaScriptKit"], swiftSettings: [ - .enableExperimentalFeature("Extern"), - .define("Tracing", .when(traits: ["Tracing"])), - ] + (enableTracingByEnv ? [.define("Tracing")] : []), + .enableExperimentalFeature("Extern") + ], linkerSettings: testingLinkerFlags ), From 6d2c0703c97dd47f1901e4a827416037b40466f6 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 13:51:01 +0200 Subject: [PATCH 039/140] BridgeJS: Emit static methods and properties on namespaced class entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The TypeScript `.d.ts` namespace-entry builder for `@JS(namespace:)` classes only emitted the constructor, silently dropping any `@JS static func` or `@JS static var` declared on the class. The equivalent path for non-namespaced classes (`renderExportedClass` → `dtsExportEntryPrinter`) iterates `klass.methods.filter(\.effects.isStatic)` and the static subset of `klass.properties`, so the output mismatched between the two paths. The generated JS class still carries the static members via `declarationPrefixKeyword: "static"` in `renderExportedClass`, and the namespace tree references it by symbol, so the JavaScript runtime works. TypeScript consumers, however, see an incomplete type and cannot call the static factory through `typeof MyNamespace.MyClass` without a hand-written augmentation. Mirror the non-namespaced path inside the `renderClassEntry` closure in `generateTypeScript` so namespaced classes emit their static methods and static properties alongside `new(...)`. Extended `Namespaces.swift` to exercise the codepath by adding a static factory and a static readonly property on the existing `__Swift.Foundation.Greeter` class. The Namespaces snapshot set captures the fixed output. --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 13 +++++++ .../Inputs/MacroSwift/Namespaces.swift | 11 ++++++ .../Namespaces.Global.json | 36 +++++++++++++++++++ .../Namespaces.Global.swift | 22 ++++++++++++ .../BridgeJSCodegenTests/Namespaces.json | 36 +++++++++++++++++++ .../BridgeJSCodegenTests/Namespaces.swift | 22 ++++++++++++ .../BridgeJSLinkTests/Namespaces.Global.d.ts | 3 ++ .../BridgeJSLinkTests/Namespaces.Global.js | 10 ++++++ .../BridgeJSLinkTests/Namespaces.d.ts | 2 ++ .../BridgeJSLinkTests/Namespaces.js | 10 ++++++ 10 files changed, 165 insertions(+) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 63b628eb3..f7527c600 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -901,6 +901,19 @@ public struct BridgeJSLink { "new\(self.renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.name), effects: constructor.effects));" ) } + // Static methods and static properties belong on the namespace + // entry alongside the constructor (same shape that + // `renderExportedClass` produces for non-namespaced classes via + // `dtsExportEntryPrinter`). + for method in klass.methods where method.effects.isStatic { + printer.write( + "\(method.name)\(self.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("\(readonly)\(property.name): \(property.type.tsType);") + } } printer.write("}") return printer.lines diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift index cbe146ff5..7cd63c698 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift @@ -16,6 +16,17 @@ func changeName(name: String) { self.name = name } + + // Static methods and properties on a namespaced class must land on the + // class's namespace entry (alongside `new`), not on the instance + // interface and not silently dropped. Regression test for the + // `@JS(namespace:)` + `@JS static func` bug where the hierarchical + // exports builder only emitted the constructor. + @JS static func makeDefault() -> Greeter { + return Greeter(name: "World") + } + + @JS static var defaultGreeting: String { "Hello, world!" } } @JS(namespace: "Utils.Converters") class Converter { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json index 9ca72009d..080f9f959 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -38,6 +38,28 @@ } } + }, + { + "abiName" : "bjs___Swift_Foundation_Greeter_static_makeDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "makeDefault", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_Greeter" + } + } } ], "name" : "Greeter", @@ -46,7 +68,21 @@ "Foundation" ], "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_Greeter" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Greeter" }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index 86f0b8478..af7efbecd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -42,6 +42,28 @@ public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPoint #endif } +@_expose(wasm, "bjs___Swift_Foundation_Greeter_static_makeDefault") +@_cdecl("bjs___Swift_Foundation_Greeter_static_makeDefault") +public func _bjs___Swift_Foundation_Greeter_static_makeDefault() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Greeter.makeDefault() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") +@_cdecl("bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") +public func _bjs___Swift_Foundation_Greeter_static_defaultGreeting_get() -> Void { + #if arch(wasm32) + let ret = __Swift_Foundation_Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs___Swift_Foundation_Greeter_deinit") @_cdecl("bjs___Swift_Foundation_Greeter_deinit") public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index 0713a2f30..d471eeaca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -38,6 +38,28 @@ } } + }, + { + "abiName" : "bjs___Swift_Foundation_Greeter_static_makeDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "makeDefault", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_Greeter" + } + } } ], "name" : "Greeter", @@ -46,7 +68,21 @@ "Foundation" ], "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultGreeting", + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_Greeter" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "Greeter" }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index 86f0b8478..af7efbecd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -42,6 +42,28 @@ public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPoint #endif } +@_expose(wasm, "bjs___Swift_Foundation_Greeter_static_makeDefault") +@_cdecl("bjs___Swift_Foundation_Greeter_static_makeDefault") +public func _bjs___Swift_Foundation_Greeter_static_makeDefault() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Greeter.makeDefault() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") +@_cdecl("bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") +public func _bjs___Swift_Foundation_Greeter_static_defaultGreeting_get() -> Void { + #if arch(wasm32) + let ret = __Swift_Foundation_Greeter.defaultGreeting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs___Swift_Foundation_Greeter_deinit") @_cdecl("bjs___Swift_Foundation_Greeter_deinit") public func _bjs___Swift_Foundation_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> 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 4b7851c3e..1353220bc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -34,6 +34,7 @@ declare global { class Greeter { constructor(name: string); greet(): string; + makeDefault(): Greeter; release(): void; } class UUID { @@ -87,6 +88,8 @@ export type Exports = { Foundation: { Greeter: { new(name: string): Greeter; + makeDefault(): Greeter; + readonly defaultGreeting: string; } UUID: { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 4a6ee1990..f4596dba7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -268,6 +268,16 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; } + static makeDefault() { + const ret = instance.exports.bjs___Swift_Foundation_Greeter_static_makeDefault(); + return Greeter.__construct(ret); + } + static get defaultGreeting() { + instance.exports.bjs___Swift_Foundation_Greeter_static_defaultGreeting_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } } class Converter extends SwiftHeapObject { static __construct(ptr) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts index fff65ce6d..6b2d65cd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts @@ -47,6 +47,8 @@ export type Exports = { Foundation: { Greeter: { new(name: string): Greeter; + makeDefault(): Greeter; + readonly defaultGreeting: string; } UUID: { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 267d96152..92ce69cbb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -268,6 +268,16 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; } + static makeDefault() { + const ret = instance.exports.bjs___Swift_Foundation_Greeter_static_makeDefault(); + return Greeter.__construct(ret); + } + static get defaultGreeting() { + instance.exports.bjs___Swift_Foundation_Greeter_static_defaultGreeting_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } } class Converter extends SwiftHeapObject { static __construct(ptr) { From 9a56b282c157bd7cdfcdb30194912f17dae180b1 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 14:07:24 +0200 Subject: [PATCH 040/140] BridgeJS: Consolidate namespaced and non-namespaced class DTS entry rendering The `renderClassEntry` closure passed to `buildHierarchicalExportsType` manually rebuilt the same `ClassName: { new(...); staticMethod(); ... }` block that `renderExportedClass` already produces as its `dtsExportEntry` return value. The two paths had to be kept in sync by hand. Replace the inline closure with a direct call to `renderExportedClass` that discards the JS and DTS-type outputs and returns only the `dtsExportEntry` slice. This makes the class namespace entry for namespaced and non-namespaced classes identical by construction. Thread `throws` through `buildHierarchicalExportsType`, `populateTypeScriptExportLines`, and `generateTypeScript` to accommodate the fact that `renderExportedClass` is throwing. Hoist the `buildHierarchicalExportsType` call out of the `printer.indent` closure so the `try` expression is in a throwing context. --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 63 ++++++------------- 1 file changed, 20 insertions(+), 43 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index f7527c600..26ed8387f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -796,7 +796,7 @@ public struct BridgeJSLink { return printer.lines } - private func generateTypeScript(data: LinkData) -> String { + private func generateTypeScript(data: LinkData) throws -> String { let header = """ // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. @@ -884,45 +884,22 @@ public struct BridgeJSLink { printer.write(lines: generateImportedTypeDefinitions()) // Exports type + let hierarchicalExportLines = try namespaceBuilder.buildHierarchicalExportsType( + exportedSkeletons: exportedSkeletons, + renderClassEntry: { klass in + let (_, _, dtsExportEntry) = try self.renderExportedClass(klass) + return dtsExportEntry + }, + renderFunctionSignature: { function in + "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + } + ) printer.write("export type Exports = {") printer.indent { // Add non-namespaced items printer.write(lines: data.dtsExportLines) - // Add hierarchical namespaced items - let hierarchicalLines = namespaceBuilder.buildHierarchicalExportsType( - exportedSkeletons: exportedSkeletons, - renderClassEntry: { klass in - let printer = CodeFragmentPrinter() - printer.write("\(klass.name): {") - printer.indent { - if let constructor = klass.constructor { - printer.write( - "new\(self.renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.name), effects: constructor.effects));" - ) - } - // Static methods and static properties belong on the namespace - // entry alongside the constructor (same shape that - // `renderExportedClass` produces for non-namespaced classes via - // `dtsExportEntryPrinter`). - for method in klass.methods where method.effects.isStatic { - printer.write( - "\(method.name)\(self.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("\(readonly)\(property.name): \(property.type.tsType);") - } - } - printer.write("}") - return printer.lines - }, - renderFunctionSignature: { function in - "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - } - ) - printer.write(lines: hierarchicalLines) + printer.write(lines: hierarchicalExportLines) } printer.write("}") @@ -1118,7 +1095,7 @@ public struct BridgeJSLink { } let data = try collectLinkData() let outputJs = try generateJavaScript(data: data) - let outputDts = generateTypeScript(data: data) + let outputDts = try generateTypeScript(data: data) return (outputJs, outputDts) } @@ -2670,16 +2647,16 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsType( exportedSkeletons: [ExportedSkeleton], - renderClassEntry: (ExportedClass) -> [String], + renderClassEntry: (ExportedClass) throws -> [String], renderFunctionSignature: (ExportedFunction) -> String - ) -> [String] { + ) throws -> [String] { let printer = CodeFragmentPrinter() let rootNode = NamespaceNode(name: "") buildExportsTree(rootNode: rootNode, exportedSkeletons: exportedSkeletons) for (_, node) in rootNode.children { - populateTypeScriptExportLines( + try populateTypeScriptExportLines( node: node, renderClassEntry: renderClassEntry, renderFunctionSignature: renderFunctionSignature @@ -2693,16 +2670,16 @@ extension BridgeJSLink { private func populateTypeScriptExportLines( node: NamespaceNode, - renderClassEntry: (ExportedClass) -> [String], + renderClassEntry: (ExportedClass) throws -> [String], renderFunctionSignature: (ExportedFunction) -> String - ) { + ) throws { for function in node.content.functions { let signature = renderFunctionSignature(function) node.content.functionDtsLines.append((function.name, [signature])) } for klass in node.content.classes { - let entry = renderClassEntry(klass) + let entry = try renderClassEntry(klass) node.content.classDtsLines.append((klass.name, entry)) } @@ -2711,7 +2688,7 @@ extension BridgeJSLink { } for (_, childNode) in node.children { - populateTypeScriptExportLines( + try populateTypeScriptExportLines( node: childNode, renderClassEntry: renderClassEntry, renderFunctionSignature: renderFunctionSignature From d1ed18594a0a471332b2abca78ceb30ad18275a8 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 14:07:34 +0200 Subject: [PATCH 041/140] BridgeJS: Add e2e test for static method and property on namespaced class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extends the existing `__Swift.Foundation.UUID` class (which already has an `@JS init` and an `@JS func`) with a static factory `fromValue(_:)` and a static readonly property `placeholder`, then asserts both are reachable via `exports.__Swift.Foundation.UUID.fromValue` and `exports.__Swift.Foundation.UUID.placeholder` in `prelude.mjs`. This is the e2e counterpart to the snapshot regression added in the previous commit — it proves the generated JavaScript actually routes calls to the correct static thunks at runtime, not just that the `.d.ts` types are well-formed. --- .../BridgeJSRuntimeTests/ExportAPITests.swift | 6 +++ .../Generated/BridgeJS.swift | 22 ++++++++++ .../Generated/JavaScript/BridgeJS.json | 44 +++++++++++++++++++ Tests/prelude.mjs | 7 +++ 4 files changed, 79 insertions(+) diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 3db9497fc..6bfa40d65 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -433,6 +433,12 @@ class UUID { @JS func uuidString() -> String { return value } + + @JS static func fromValue(_ value: String) -> UUID { + return UUID(value: value) + } + + @JS static var placeholder: String { "00000000-0000-0000-0000-000000000000" } } @JS func createUUID(value: String) -> UUID { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 71e5ef537..676d969ce 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -8602,6 +8602,28 @@ public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPoi #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 { + #if arch(wasm32) + let ret = UUID.fromValue(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + 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 { + #if arch(wasm32) + let ret = __Swift_Foundation_UUID.placeholder + 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 { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 60b02020d..46ae95a32 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -1108,6 +1108,36 @@ } } + }, + { + "abiName" : "bjs___Swift_Foundation_UUID_static_fromValue", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "fromValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "UUID" + } + }, + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_UUID" + } + } } ], "name" : "UUID", @@ -1116,7 +1146,21 @@ "Foundation" ], "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "placeholder", + "staticContext" : { + "className" : { + "_0" : "__Swift_Foundation_UUID" + } + }, + "type" : { + "string" : { + } + } + } ], "swiftCallName" : "UUID" }, diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index bb285aaee..1bc9ae101 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -624,6 +624,13 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { roundTrippedUUID.release(); uuid.release(); + // Static method and property on a namespaced class (@JS(namespace:) + @JS static). + // These must be callable via the namespace path, not as instance members. + const uuidFromStatic = exports.__Swift.Foundation.UUID.fromValue("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); + assert.equal(uuidFromStatic.uuidString(), "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); + uuidFromStatic.release(); + assert.equal(exports.__Swift.Foundation.UUID.placeholder, "00000000-0000-0000-0000-000000000000"); + const createdServer = exports.createHTTPServer(); createdServer.call(exports.Networking.API.Method.Get); createdServer.release(); From 575b2bfa62ffe1d2f4b48c064b924a89e5a21d16 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 14:15:25 +0200 Subject: [PATCH 042/140] BridgeJS: Avoid double-rendering namespaced class DTS export entries `renderExportedClass` was being called twice for every namespaced class: once in `collectLinkData` (to produce the JS body and instance interface) and once more inside the `renderClassEntry` closure (to produce the export-entry for `buildHierarchicalExportsType`), with the JS and instance-interface outputs discarded on the second call. Store the `dtsExportEntry` slice in `LinkData.namespacedClassDtsExportEntries` during the single `collectLinkData` pass, keyed by class name. The `renderClassEntry` closure is now a non-throwing dictionary lookup, so `buildHierarchicalExportsType`, `populateTypeScriptExportLines`, and `generateTypeScript` revert to non-throwing. --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 26ed8387f..60b34ff16 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -130,6 +130,7 @@ 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] = [] @@ -161,13 +162,14 @@ public struct BridgeJSLink { for klass in skeleton.classes { let (jsType, dtsType, dtsExportEntry) = 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 } - - data.dtsClassLines.append(contentsOf: dtsType) } // Process enums - collect top-level definitions and export entries @@ -796,7 +798,7 @@ public struct BridgeJSLink { return printer.lines } - private func generateTypeScript(data: LinkData) throws -> String { + private func generateTypeScript(data: LinkData) -> String { let header = """ // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. @@ -884,11 +886,10 @@ public struct BridgeJSLink { printer.write(lines: generateImportedTypeDefinitions()) // Exports type - let hierarchicalExportLines = try namespaceBuilder.buildHierarchicalExportsType( + let hierarchicalExportLines = namespaceBuilder.buildHierarchicalExportsType( exportedSkeletons: exportedSkeletons, renderClassEntry: { klass in - let (_, _, dtsExportEntry) = try self.renderExportedClass(klass) - return dtsExportEntry + data.namespacedClassDtsExportEntries[klass.name] ?? [] }, renderFunctionSignature: { function in "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" @@ -1095,7 +1096,7 @@ public struct BridgeJSLink { } let data = try collectLinkData() let outputJs = try generateJavaScript(data: data) - let outputDts = try generateTypeScript(data: data) + let outputDts = generateTypeScript(data: data) return (outputJs, outputDts) } @@ -2647,16 +2648,16 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsType( exportedSkeletons: [ExportedSkeleton], - renderClassEntry: (ExportedClass) throws -> [String], + renderClassEntry: (ExportedClass) -> [String], renderFunctionSignature: (ExportedFunction) -> String - ) throws -> [String] { + ) -> [String] { let printer = CodeFragmentPrinter() let rootNode = NamespaceNode(name: "") buildExportsTree(rootNode: rootNode, exportedSkeletons: exportedSkeletons) for (_, node) in rootNode.children { - try populateTypeScriptExportLines( + populateTypeScriptExportLines( node: node, renderClassEntry: renderClassEntry, renderFunctionSignature: renderFunctionSignature @@ -2670,16 +2671,16 @@ extension BridgeJSLink { private func populateTypeScriptExportLines( node: NamespaceNode, - renderClassEntry: (ExportedClass) throws -> [String], + renderClassEntry: (ExportedClass) -> [String], renderFunctionSignature: (ExportedFunction) -> String - ) throws { + ) { for function in node.content.functions { let signature = renderFunctionSignature(function) node.content.functionDtsLines.append((function.name, [signature])) } for klass in node.content.classes { - let entry = try renderClassEntry(klass) + let entry = renderClassEntry(klass) node.content.classDtsLines.append((klass.name, entry)) } @@ -2688,7 +2689,7 @@ extension BridgeJSLink { } for (_, childNode) in node.children { - try populateTypeScriptExportLines( + populateTypeScriptExportLines( node: childNode, renderClassEntry: renderClassEntry, renderFunctionSignature: renderFunctionSignature From 0d6544f95427d6c1689b4908f961c0d5f566d5aa Mon Sep 17 00:00:00 2001 From: Stephan Diederich Date: Thu, 9 Apr 2026 14:46:49 +0200 Subject: [PATCH 043/140] relax swift-syntax version constraint to allow 603 (#714) * relax swift-syntax version constraint to allow 603 Packages are updating to 603 and this can fail the dependency solver. * .. and also test against it --- .github/workflows/test.yml | 2 ++ Package.swift | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e8118a481..c3c19b1c4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -81,6 +81,8 @@ jobs: 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 container: image: ${{ matrix.entry.image }} diff --git a/Package.swift b/Package.swift index 20583865b..820524177 100644 --- a/Package.swift +++ b/Package.swift @@ -48,7 +48,7 @@ let package = Package( ], traits: [tracingTrait], dependencies: [ - .package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"603.0.0") + .package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"604.0.0") ], targets: [ .target( From 57c1fd8300cd888eee1ad965c395d51995ca1c5d Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 9 Apr 2026 15:53:08 +0200 Subject: [PATCH 044/140] BridgeJS: Fix static property call expression for namespaced classes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Static properties on `@JS(namespace:)` classes used `property.callName()` to build the Swift call expression. That method consults `property.staticContext`, which is stored as `.className(abiName)` (e.g. `__Swift_Foundation_UUID`), and emits `\(abiName).\(propertyName)`. The ABI-mangled name is not a valid Swift identifier so the generated thunk failed to compile. Static methods were unaffected because `renderSingleExportedMethod` passes `klass.swiftCallName` directly. Fix `PropertyRenderingContext.callName(for:)` for the `.classStatic` case to bypass `property.callName()` and build the expression directly from `klass.swiftCallName`. This preserves the ABI symbol name (which still comes through `context.className` → `klass.abiName` → `property.getterAbiName(className:)`) while producing a valid Swift call expression in the thunk body. Also remove the now-unnecessary comment from `prelude.mjs` that described what the test was checking (the assertion itself is self-explanatory). --- Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift | 6 +++++- .../BridgeJSCodegenTests/Namespaces.Global.swift | 2 +- .../__Snapshots__/BridgeJSCodegenTests/Namespaces.swift | 2 +- Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift | 2 +- Tests/prelude.mjs | 2 -- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index ca7bdc3c2..9515fd7cf 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -433,7 +433,11 @@ public class ExportSwift { switch self { case .enumStatic(let enumDef): return property.callName(prefix: enumDef.swiftCallName) - case .classStatic, .classInstance: + case .classStatic(let klass): + // property.callName() would use staticContext (the ABI name) as prefix; + // use swiftCallName directly so the emitted expression is valid Swift. + return "\(klass.swiftCallName).\(property.name)" + case .classInstance: return property.callName() case .structStatic(let structDef): return property.callName(prefix: structDef.swiftCallName) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index af7efbecd..baa867eed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -57,7 +57,7 @@ public func _bjs___Swift_Foundation_Greeter_static_makeDefault() -> UnsafeMutabl @_cdecl("bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") public func _bjs___Swift_Foundation_Greeter_static_defaultGreeting_get() -> Void { #if arch(wasm32) - let ret = __Swift_Foundation_Greeter.defaultGreeting + let ret = Greeter.defaultGreeting return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index af7efbecd..baa867eed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -57,7 +57,7 @@ public func _bjs___Swift_Foundation_Greeter_static_makeDefault() -> UnsafeMutabl @_cdecl("bjs___Swift_Foundation_Greeter_static_defaultGreeting_get") public func _bjs___Swift_Foundation_Greeter_static_defaultGreeting_get() -> Void { #if arch(wasm32) - let ret = __Swift_Foundation_Greeter.defaultGreeting + let ret = Greeter.defaultGreeting return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 676d969ce..c91ddb81e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -8617,7 +8617,7 @@ public func _bjs___Swift_Foundation_UUID_static_fromValue(_ valueBytes: Int32, _ @_cdecl("bjs___Swift_Foundation_UUID_static_placeholder_get") public func _bjs___Swift_Foundation_UUID_static_placeholder_get() -> Void { #if arch(wasm32) - let ret = __Swift_Foundation_UUID.placeholder + let ret = UUID.placeholder return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 1bc9ae101..0af033226 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -624,8 +624,6 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { roundTrippedUUID.release(); uuid.release(); - // Static method and property on a namespaced class (@JS(namespace:) + @JS static). - // These must be callable via the namespace path, not as instance members. const uuidFromStatic = exports.__Swift.Foundation.UUID.fromValue("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); assert.equal(uuidFromStatic.uuidString(), "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); uuidFromStatic.release(); From ff90c3e911f68679fa39e885e42a4a438065e6fa Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 14 Apr 2026 15:58:24 +1000 Subject: [PATCH 045/140] BridgeJS: fix code generation for public enums (#719) --- .../Sources/BridgeJSCore/ExportSwift.swift | 4 +-- .../BridgeJSCodegenTests/ArrayTypes.swift | 4 +-- .../DefaultParameters.swift | 4 +-- .../EnumAssociatedValue.swift | 4 +-- .../BridgeJSCodegenTests/EnumCase.swift | 16 +++++------ .../EnumNamespace.Global.swift | 8 +++--- .../BridgeJSCodegenTests/EnumNamespace.swift | 8 +++--- .../BridgeJSCodegenTests/Protocol.swift | 4 +-- .../StaticFunctions.Global.swift | 4 +-- .../StaticFunctions.swift | 4 +-- .../StaticProperties.Global.swift | 4 +-- .../StaticProperties.swift | 4 +-- .../BridgeJSCodegenTests/SwiftClosure.swift | 4 +-- .../Generated/BridgeJS.swift | 8 +++--- .../BridgeJSRuntimeTests/ExportAPITests.swift | 2 +- .../Generated/BridgeJS.swift | 28 +++++++++---------- .../Generated/JavaScript/BridgeJS.json | 1 + 17 files changed, 56 insertions(+), 55 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 07c24dee7..b649b244d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -966,7 +966,7 @@ struct EnumCodegen { ) printer.nextLine() - printer.write("private init?(bridgeJSRawValue: Int32) {") + printer.write("@_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) {") printer.indent { printer.write("switch bridgeJSRawValue {") for (index, enumCase) in enumDef.cases.enumerated() { @@ -984,7 +984,7 @@ struct EnumCodegen { printer.write("}") printer.nextLine() - printer.write("private var bridgeJSRawValue: Int32 {") + printer.write("@_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 {") printer.indent { printer.write("switch self {") for (index, enumCase) in enumDef.cases.enumerated() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index cf65635d9..a058d13a7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -12,7 +12,7 @@ extension Direction: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -27,7 +27,7 @@ extension Direction: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index 4c527315b..507827646 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -12,7 +12,7 @@ extension Status: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .active @@ -25,7 +25,7 @@ extension Status: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .active: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 1112fb5a4..6d5549699 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -203,7 +203,7 @@ extension CardinalDirection: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -218,7 +218,7 @@ extension CardinalDirection: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift index 06c3e1cd8..66692ee14 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift @@ -12,7 +12,7 @@ extension Direction: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -27,7 +27,7 @@ extension Direction: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 @@ -55,7 +55,7 @@ extension Status: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .loading @@ -68,7 +68,7 @@ extension Status: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .loading: return 0 @@ -94,7 +94,7 @@ extension TSDirection: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -109,7 +109,7 @@ extension TSDirection: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 @@ -137,7 +137,7 @@ extension PublicStatus: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .success @@ -146,7 +146,7 @@ extension PublicStatus: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .success: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 1a8608246..5bde4ff93 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -12,7 +12,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -27,7 +27,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 @@ -61,7 +61,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -72,7 +72,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 1a8608246..5bde4ff93 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -12,7 +12,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -27,7 +27,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 @@ -61,7 +61,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -72,7 +72,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 745ec6cc9..e8df6c966 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -633,7 +633,7 @@ extension Direction: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -648,7 +648,7 @@ extension Direction: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index d329c7a96..896258915 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -12,7 +12,7 @@ extension Calculator: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .scientific @@ -23,7 +23,7 @@ extension Calculator: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .scientific: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index d329c7a96..896258915 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -12,7 +12,7 @@ extension Calculator: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .scientific @@ -23,7 +23,7 @@ extension Calculator: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .scientific: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index faec8821b..ded55dbd4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -12,7 +12,7 @@ extension PropertyEnum: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .value1 @@ -23,7 +23,7 @@ extension PropertyEnum: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .value1: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index faec8821b..ded55dbd4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -12,7 +12,7 @@ extension PropertyEnum: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .value1 @@ -23,7 +23,7 @@ extension PropertyEnum: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .value1: return 0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index 472987fee..348f9a788 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -1280,7 +1280,7 @@ extension Direction: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -1295,7 +1295,7 @@ extension Direction: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index 7816681da..862debbf0 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -21,7 +21,7 @@ extension GlobalNetworking.API.CallMethod: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -36,7 +36,7 @@ extension GlobalNetworking.API.CallMethod: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 @@ -70,7 +70,7 @@ extension Internal.SupportedServerMethod: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -81,7 +81,7 @@ extension Internal.SupportedServerMethod: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 6bfa40d65..2562fe18e 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -207,7 +207,7 @@ extension Greeter { // MARK: - Enum Tests -@JS enum Direction { +@JS public enum Direction { case north case south case east diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 13a0f08b7..a37a7e4c5 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -3868,7 +3868,7 @@ extension Direction: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -3883,7 +3883,7 @@ extension Direction: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 @@ -3911,7 +3911,7 @@ extension Status: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .loading @@ -3924,7 +3924,7 @@ extension Status: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .loading: return 0 @@ -3968,7 +3968,7 @@ extension TSDirection: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .north @@ -3983,7 +3983,7 @@ extension TSDirection: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .north: return 0 @@ -4036,7 +4036,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -4051,7 +4051,7 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 @@ -4085,7 +4085,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .get @@ -4096,7 +4096,7 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .get: return 0 @@ -4369,7 +4369,7 @@ extension StaticCalculator: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .scientific @@ -4380,7 +4380,7 @@ extension StaticCalculator: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .scientific: return 0 @@ -4470,7 +4470,7 @@ extension StaticPropertyEnum: _BridgedSwiftCaseEnum { return bridgeJSLowerParameter() } - private init?(bridgeJSRawValue: Int32) { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: self = .option1 @@ -4481,7 +4481,7 @@ extension StaticPropertyEnum: _BridgedSwiftCaseEnum { } } - private var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { case .option1: return 0 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 46ae95a32..dd4362fc1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -7235,6 +7235,7 @@ } ], "emitStyle" : "const", + "explicitAccessControl" : "public", "name" : "Direction", "staticMethods" : [ From 94f02c351b93d840e55b7ecbf4ae77f8a1cd5c6f Mon Sep 17 00:00:00 2001 From: Ken Tominaga Date: Tue, 21 Apr 2026 01:27:37 -0700 Subject: [PATCH 046/140] JavaScriptKit: import Android module for non-Wasm Android targets (#722) Building JavaScriptKit for the Swift 6.3 Android SDK triples (e.g. aarch64-unknown-linux-android28, x86_64-unknown-linux-android30) fails in ThreadLocal.swift with: error: cannot find 'pthread_key_create' in scope error: cannot find 'pthread_key_t' in scope Android uses Bionic, exposed to Swift as the `Android` module, rather than Glibc. The existing conditional falls through to `#error("Unsupported platform")` on Android. Add a `canImport(Android)` branch between the Darwin and Glibc branches, matching the pattern already used by Foundation and swift-corelibs-libdispatch. No Wasm, Darwin, or Glibc behavior changes. --- Sources/JavaScriptKit/ThreadLocal.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/JavaScriptKit/ThreadLocal.swift b/Sources/JavaScriptKit/ThreadLocal.swift index e92ca32ac..12bf78773 100644 --- a/Sources/JavaScriptKit/ThreadLocal.swift +++ b/Sources/JavaScriptKit/ThreadLocal.swift @@ -4,6 +4,8 @@ import wasi_pthread #endif #elseif canImport(Darwin) import Darwin +#elseif canImport(Android) +import Android #elseif canImport(Glibc) import Glibc #else From f458fb61483a0e713604814d11c7080f39f9148c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Apr 2026 18:28:46 +0100 Subject: [PATCH 047/140] Bump actions/upload-pages-artifact from 4 to 5 (#721) Bumps [actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact) from 4 to 5. - [Release notes](https://github.com/actions/upload-pages-artifact/releases) - [Commits](https://github.com/actions/upload-pages-artifact/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/upload-pages-artifact dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c3c19b1c4..baba9c79b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -185,7 +185,7 @@ jobs: - run: ./Utilities/prepare-gh-pages.sh - name: Upload static files as artifact id: deployment - uses: actions/upload-pages-artifact@v4 + uses: actions/upload-pages-artifact@v5 with: path: ./_site deploy-examples: From d70aaff9cc573a5209580fbc20f43afa19762938 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 22 Apr 2026 10:40:13 +0200 Subject: [PATCH 048/140] feat: Add opt-in pointer identity mode for SwiftHeapObject wrappers --- Benchmarks/README.md | 37 +- Benchmarks/Sources/Benchmarks.swift | 103 ++++ Benchmarks/Sources/Generated/BridgeJS.swift | 442 ++++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 500 ++++++++++++++++++ Benchmarks/run.js | 98 +++- Package.swift | 12 + Package@swift-6.1.swift | 12 + .../BridgeJS/Sources/BridgeJSCore/Misc.swift | 17 +- .../BridgeJSCore/SwiftToSkeleton.swift | 24 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 77 ++- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 16 +- .../Sources/BridgeJSTool/BridgeJSTool.swift | 3 +- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 49 ++ .../Inputs/MacroSwift/IdentityModeClass.swift | 28 + .../IdentityModeClass.json | 148 ++++++ .../IdentityModeClass.swift | 188 +++++++ .../BridgeJSLinkTests/ArrayTypes.js | 40 +- .../BridgeJSLinkTests/DefaultParameters.js | 42 +- .../BridgeJSLinkTests/DictionaryTypes.js | 38 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 38 +- .../BridgeJSLinkTests/EnumNamespace.Global.js | 44 +- .../BridgeJSLinkTests/EnumNamespace.js | 44 +- .../IdentityModeClass.ConfigPointer.d.ts | 42 ++ .../IdentityModeClass.ConfigPointer.js | 342 ++++++++++++ .../IdentityModeClass.PerClass.d.ts | 42 ++ .../IdentityModeClass.PerClass.js | 340 ++++++++++++ .../BridgeJSLinkTests/IdentityModeClass.d.ts | 42 ++ .../BridgeJSLinkTests/IdentityModeClass.js | 340 ++++++++++++ .../BridgeJSLinkTests/JSValue.js | 38 +- .../BridgeJSLinkTests/MixedGlobal.js | 38 +- .../BridgeJSLinkTests/MixedModules.js | 40 +- .../BridgeJSLinkTests/MixedPrivate.js | 38 +- .../BridgeJSLinkTests/Namespaces.Global.js | 44 +- .../BridgeJSLinkTests/Namespaces.js | 44 +- .../BridgeJSLinkTests/Optionals.js | 40 +- .../BridgeJSLinkTests/PropertyTypes.js | 38 +- .../BridgeJSLinkTests/Protocol.js | 42 +- .../BridgeJSLinkTests/ProtocolInClosure.js | 38 +- .../StaticFunctions.Global.js | 38 +- .../BridgeJSLinkTests/StaticFunctions.js | 38 +- .../StaticProperties.Global.js | 38 +- .../BridgeJSLinkTests/StaticProperties.js | 38 +- .../BridgeJSLinkTests/SwiftClass.js | 42 +- .../BridgeJSLinkTests/SwiftClosure.js | 40 +- .../BridgeJSLinkTests/SwiftStruct.js | 38 +- .../BridgeJS/BridgeJS-Configuration.md | 30 ++ .../Exporting-Swift/Exporting-Swift-Class.md | 40 ++ Sources/JavaScriptKit/Macros.swift | 3 +- .../Generated/BridgeJS.swift | 353 +++++++++++++ .../Generated/JavaScript/BridgeJS.json | 447 ++++++++++++++++ .../IdentityModeTests.swift | 113 ++++ .../JavaScript/IdentityModeTests.mjs | 200 +++++++ .../bridge-js.config.json | 3 + Tests/prelude.mjs | 2 + Utilities/bridge-js-generate.sh | 1 + 55 files changed, 4769 insertions(+), 243 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/IdentityModeClass.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js create mode 100644 Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift create mode 100644 Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json create mode 100644 Tests/BridgeJSIdentityTests/IdentityModeTests.swift create mode 100644 Tests/BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs create mode 100644 Tests/BridgeJSIdentityTests/bridge-js.config.json diff --git a/Benchmarks/README.md b/Benchmarks/README.md index 65d867eba..3d1a1cf22 100644 --- a/Benchmarks/README.md +++ b/Benchmarks/README.md @@ -4,8 +4,6 @@ This directory contains performance benchmarks for JavaScriptKit. ## Building Benchmarks -Before running the benchmarks, you need to build the test suite: - ```bash swift package --swift-sdk $SWIFT_SDK_ID js -c release ``` @@ -19,19 +17,38 @@ node run.js # Save results to a JSON file node run.js --output=results.json -# Specify number of iterations -node run.js --runs=20 - # Run in adaptive mode until results stabilize node run.js --adaptive --output=stable-results.json -# Run benchmarks and compare with previous results +# Compare with previous results node run.js --baseline=previous-results.json -# Run only a subset of benchmarks -# Substring match +# Filter benchmarks by name node run.js --filter=Call -# Regex (with flags) node run.js --filter=/^Property access\// -node run.js --filter=/string/i ``` + +## Identity Mode Benchmarks + +The benchmark suite includes identity-mode variants (`@JS(identityMode: true)`) of the core classes to measure pointer identity caching. Both variants are in the same build and run as regular benchmarks alongside everything else. + +```bash +# Run only identity benchmarks +node --expose-gc run.js --filter=Identity + +# Run only pointer-mode identity benchmarks +node --expose-gc run.js --filter=Identity/pointer + +# Run only non-identity baseline +node --expose-gc run.js --filter=Identity/none +``` + +### Identity Scenarios + +| Scenario | What it measures | +|----------|-----------------| +| `passBothWaysRoundtrip` | Same object crossing boundary repeatedly (cache hit path) | +| `getPoolRepeated_100` | Bulk return of 100 cached objects (model collection pattern) | +| `churnObjects` | Create, roundtrip, release cycle (FinalizationRegistry cleanup pressure) | +| `swiftConsumesSameObject` | JS passes same object to Swift repeatedly | +| `swiftCreatesObject` | Fresh object creation overhead (cache miss path) | diff --git a/Benchmarks/Sources/Benchmarks.swift b/Benchmarks/Sources/Benchmarks.swift index 59da8c96c..3e24e597b 100644 --- a/Benchmarks/Sources/Benchmarks.swift +++ b/Benchmarks/Sources/Benchmarks.swift @@ -257,6 +257,109 @@ enum ComplexResult { } } +// MARK: - Class Array Performance Tests + +nonisolated(unsafe) var _classArrayPool: [SimpleClass] = [] + +@JS class ClassArrayRoundtrip { + @JS init() {} + + @JS func setupPool(_ count: Int) { + _classArrayPool = (0.. [SimpleClass] { + return _classArrayPool + } + + @JS func makeClassArray() -> [SimpleClass] { + return (0..<100).map { + SimpleClass(name: "Item \($0)", count: $0, flag: true, rate: 0.5, precise: 3.14) + } + } + + @JS func takeClassArray(_ values: [SimpleClass]) {} + + @JS func roundtripClassArray(_ values: [SimpleClass]) -> [SimpleClass] { + return values + } +} + +// MARK: - Identity Cache Benchmark + +nonisolated(unsafe) var _cachedPool: [SimpleClass] = [] + +@JS class IdentityCacheBenchmark { + @JS init() {} + + @JS func setupPool(_ count: Int) { + _cachedPool = (0.. [SimpleClass] { + return _cachedPool + } +} + +// MARK: - Identity Mode Benchmark Variants +// These classes use @JS(identityMode: true) so that identity cache benchmarks +// can run in the SAME build alongside the non-identity classes above. + +@JS(identityMode: true) +class SimpleClassIdentity { + @JS var name: String + @JS var count: Int + @JS var flag: Bool + @JS var rate: Float + @JS var precise: Double + + @JS init(name: String, count: Int, flag: Bool, rate: Float, precise: Double) { + self.name = name + self.count = count + self.flag = flag + self.rate = rate + self.precise = precise + } +} + +@JS(identityMode: true) +class ClassRoundtripIdentity { + @JS init() {} + + @JS func roundtripSimpleClassIdentity(_ obj: SimpleClassIdentity) -> SimpleClassIdentity { + return obj + } + + @JS func makeSimpleClassIdentity() -> SimpleClassIdentity { + return SimpleClassIdentity(name: "Hello", count: 42, flag: true, rate: 0.5, precise: 3.14159) + } + + @JS func takeSimpleClassIdentity(_ obj: SimpleClassIdentity) { + // consume without returning + } +} + +nonisolated(unsafe) var _cachedPoolIdentity: [SimpleClassIdentity] = [] + +@JS(identityMode: true) +class IdentityCacheBenchmarkIdentity { + @JS init() {} + + @JS func setupPool(_ count: Int) { + _cachedPoolIdentity = (0.. [SimpleClassIdentity] { + return _cachedPoolIdentity + } +} + // MARK: - Array Performance Tests @JS struct Point { diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index c9adb2b1a..e199e4a29 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -1373,6 +1373,448 @@ fileprivate func _bjs_ClassRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_ClassRoundtrip_wrap_extern(pointer) } +@_expose(wasm, "bjs_ClassArrayRoundtrip_init") +@_cdecl("bjs_ClassArrayRoundtrip_init") +public func _bjs_ClassArrayRoundtrip_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ClassArrayRoundtrip() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_setupPool") +@_cdecl("bjs_ClassArrayRoundtrip_setupPool") +public func _bjs_ClassArrayRoundtrip_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { + #if arch(wasm32) + ClassArrayRoundtrip.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_getPool") +@_cdecl("bjs_ClassArrayRoundtrip_getPool") +public func _bjs_ClassArrayRoundtrip_getPool(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).getPool() + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_makeClassArray") +@_cdecl("bjs_ClassArrayRoundtrip_makeClassArray") +public func _bjs_ClassArrayRoundtrip_makeClassArray(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).makeClassArray() + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_takeClassArray") +@_cdecl("bjs_ClassArrayRoundtrip_takeClassArray") +public func _bjs_ClassArrayRoundtrip_takeClassArray(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + ClassArrayRoundtrip.bridgeJSLiftParameter(_self).takeClassArray(_: [SimpleClass].bridgeJSStackPop()) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_roundtripClassArray") +@_cdecl("bjs_ClassArrayRoundtrip_roundtripClassArray") +public func _bjs_ClassArrayRoundtrip_roundtripClassArray(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripClassArray(_: [SimpleClass].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassArrayRoundtrip_deinit") +@_cdecl("bjs_ClassArrayRoundtrip_deinit") +public func _bjs_ClassArrayRoundtrip_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ClassArrayRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassArrayRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassArrayRoundtrip_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "Benchmarks", name: "bjs_ClassArrayRoundtrip_wrap") +fileprivate func _bjs_ClassArrayRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ClassArrayRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ClassArrayRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassArrayRoundtrip_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_IdentityCacheBenchmark_init") +@_cdecl("bjs_IdentityCacheBenchmark_init") +public func _bjs_IdentityCacheBenchmark_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = IdentityCacheBenchmark() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmark_setupPool") +@_cdecl("bjs_IdentityCacheBenchmark_setupPool") +public func _bjs_IdentityCacheBenchmark_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { + #if arch(wasm32) + IdentityCacheBenchmark.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmark_getPoolRepeated") +@_cdecl("bjs_IdentityCacheBenchmark_getPoolRepeated") +public func _bjs_IdentityCacheBenchmark_getPoolRepeated(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = IdentityCacheBenchmark.bridgeJSLiftParameter(_self).getPoolRepeated() + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmark_deinit") +@_cdecl("bjs_IdentityCacheBenchmark_deinit") +public func _bjs_IdentityCacheBenchmark_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension IdentityCacheBenchmark: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_IdentityCacheBenchmark_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_IdentityCacheBenchmark_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "Benchmarks", name: "bjs_IdentityCacheBenchmark_wrap") +fileprivate func _bjs_IdentityCacheBenchmark_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_IdentityCacheBenchmark_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_IdentityCacheBenchmark_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_IdentityCacheBenchmark_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_SimpleClassIdentity_init") +@_cdecl("bjs_SimpleClassIdentity_init") +public func _bjs_SimpleClassIdentity_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ flag: Int32, _ rate: Float32, _ precise: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = SimpleClassIdentity(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), flag: Bool.bridgeJSLiftParameter(flag), rate: Float.bridgeJSLiftParameter(rate), precise: Double.bridgeJSLiftParameter(precise)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_name_get") +@_cdecl("bjs_SimpleClassIdentity_name_get") +public func _bjs_SimpleClassIdentity_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_name_set") +@_cdecl("bjs_SimpleClassIdentity_name_set") +public func _bjs_SimpleClassIdentity_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + SimpleClassIdentity.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_count_get") +@_cdecl("bjs_SimpleClassIdentity_count_get") +public func _bjs_SimpleClassIdentity_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).count + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_count_set") +@_cdecl("bjs_SimpleClassIdentity_count_set") +public func _bjs_SimpleClassIdentity_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + SimpleClassIdentity.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_flag_get") +@_cdecl("bjs_SimpleClassIdentity_flag_get") +public func _bjs_SimpleClassIdentity_flag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).flag + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_flag_set") +@_cdecl("bjs_SimpleClassIdentity_flag_set") +public func _bjs_SimpleClassIdentity_flag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + SimpleClassIdentity.bridgeJSLiftParameter(_self).flag = Bool.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_rate_get") +@_cdecl("bjs_SimpleClassIdentity_rate_get") +public func _bjs_SimpleClassIdentity_rate_get(_ _self: UnsafeMutableRawPointer) -> Float32 { + #if arch(wasm32) + let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).rate + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_rate_set") +@_cdecl("bjs_SimpleClassIdentity_rate_set") +public func _bjs_SimpleClassIdentity_rate_set(_ _self: UnsafeMutableRawPointer, _ value: Float32) -> Void { + #if arch(wasm32) + SimpleClassIdentity.bridgeJSLiftParameter(_self).rate = Float.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_precise_get") +@_cdecl("bjs_SimpleClassIdentity_precise_get") +public func _bjs_SimpleClassIdentity_precise_get(_ _self: UnsafeMutableRawPointer) -> Float64 { + #if arch(wasm32) + let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).precise + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_precise_set") +@_cdecl("bjs_SimpleClassIdentity_precise_set") +public func _bjs_SimpleClassIdentity_precise_set(_ _self: UnsafeMutableRawPointer, _ value: Float64) -> Void { + #if arch(wasm32) + SimpleClassIdentity.bridgeJSLiftParameter(_self).precise = Double.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimpleClassIdentity_deinit") +@_cdecl("bjs_SimpleClassIdentity_deinit") +public func _bjs_SimpleClassIdentity_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension SimpleClassIdentity: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_SimpleClassIdentity_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_SimpleClassIdentity_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "Benchmarks", name: "bjs_SimpleClassIdentity_wrap") +fileprivate func _bjs_SimpleClassIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_SimpleClassIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_SimpleClassIdentity_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SimpleClassIdentity_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_ClassRoundtripIdentity_init") +@_cdecl("bjs_ClassRoundtripIdentity_init") +public func _bjs_ClassRoundtripIdentity_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ClassRoundtripIdentity() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity") +@_cdecl("bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity") +public func _bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity(_ _self: UnsafeMutableRawPointer, _ obj: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ClassRoundtripIdentity.bridgeJSLiftParameter(_self).roundtripSimpleClassIdentity(_: SimpleClassIdentity.bridgeJSLiftParameter(obj)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassRoundtripIdentity_makeSimpleClassIdentity") +@_cdecl("bjs_ClassRoundtripIdentity_makeSimpleClassIdentity") +public func _bjs_ClassRoundtripIdentity_makeSimpleClassIdentity(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ClassRoundtripIdentity.bridgeJSLiftParameter(_self).makeSimpleClassIdentity() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassRoundtripIdentity_takeSimpleClassIdentity") +@_cdecl("bjs_ClassRoundtripIdentity_takeSimpleClassIdentity") +public func _bjs_ClassRoundtripIdentity_takeSimpleClassIdentity(_ _self: UnsafeMutableRawPointer, _ obj: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + ClassRoundtripIdentity.bridgeJSLiftParameter(_self).takeSimpleClassIdentity(_: SimpleClassIdentity.bridgeJSLiftParameter(obj)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClassRoundtripIdentity_deinit") +@_cdecl("bjs_ClassRoundtripIdentity_deinit") +public func _bjs_ClassRoundtripIdentity_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ClassRoundtripIdentity: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ClassRoundtripIdentity_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ClassRoundtripIdentity_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "Benchmarks", name: "bjs_ClassRoundtripIdentity_wrap") +fileprivate func _bjs_ClassRoundtripIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ClassRoundtripIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ClassRoundtripIdentity_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassRoundtripIdentity_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_IdentityCacheBenchmarkIdentity_init") +@_cdecl("bjs_IdentityCacheBenchmarkIdentity_init") +public func _bjs_IdentityCacheBenchmarkIdentity_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = IdentityCacheBenchmarkIdentity() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmarkIdentity_setupPool") +@_cdecl("bjs_IdentityCacheBenchmarkIdentity_setupPool") +public func _bjs_IdentityCacheBenchmarkIdentity_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { + #if arch(wasm32) + IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated") +@_cdecl("bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated") +public func _bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self).getPoolRepeated() + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityCacheBenchmarkIdentity_deinit") +@_cdecl("bjs_IdentityCacheBenchmarkIdentity_deinit") +public func _bjs_IdentityCacheBenchmarkIdentity_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension IdentityCacheBenchmarkIdentity: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_IdentityCacheBenchmarkIdentity_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_IdentityCacheBenchmarkIdentity_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "Benchmarks", name: "bjs_IdentityCacheBenchmarkIdentity_wrap") +fileprivate func _bjs_IdentityCacheBenchmarkIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_IdentityCacheBenchmarkIdentity_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_IdentityCacheBenchmarkIdentity_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_IdentityCacheBenchmarkIdentity_wrap_extern(pointer) +} + @_expose(wasm, "bjs_ArrayRoundtrip_init") @_cdecl("bjs_ArrayRoundtrip_init") public func _bjs_ArrayRoundtrip_init() -> UnsafeMutableRawPointer { diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index b2c33ac01..0bddddfb6 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -1270,6 +1270,506 @@ ], "swiftCallName" : "ClassRoundtrip" }, + { + "constructor" : { + "abiName" : "bjs_ClassArrayRoundtrip_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_ClassArrayRoundtrip_setupPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setupPool", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_ClassArrayRoundtrip_getPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getPool", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + }, + { + "abiName" : "bjs_ClassArrayRoundtrip_makeClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeClassArray", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + }, + { + "abiName" : "bjs_ClassArrayRoundtrip_takeClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeClassArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_ClassArrayRoundtrip_roundtripClassArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripClassArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + } + ], + "name" : "ClassArrayRoundtrip", + "properties" : [ + + ], + "swiftCallName" : "ClassArrayRoundtrip" + }, + { + "constructor" : { + "abiName" : "bjs_IdentityCacheBenchmark_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_IdentityCacheBenchmark_setupPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setupPool", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_IdentityCacheBenchmark_getPoolRepeated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getPoolRepeated", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClass" + } + } + } + } + } + ], + "name" : "IdentityCacheBenchmark", + "properties" : [ + + ], + "swiftCallName" : "IdentityCacheBenchmark" + }, + { + "constructor" : { + "abiName" : "bjs_SimpleClassIdentity_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "label" : "count", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "flag", + "name" : "flag", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "rate", + "name" : "rate", + "type" : { + "float" : { + + } + } + }, + { + "label" : "precise", + "name" : "precise", + "type" : { + "double" : { + + } + } + } + ] + }, + "identityMode" : true, + "methods" : [ + + ], + "name" : "SimpleClassIdentity", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "flag", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "rate", + "type" : { + "float" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "precise", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "SimpleClassIdentity" + }, + { + "constructor" : { + "abiName" : "bjs_ClassRoundtripIdentity_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "identityMode" : true, + "methods" : [ + { + "abiName" : "bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripSimpleClassIdentity", + "parameters" : [ + { + "label" : "_", + "name" : "obj", + "type" : { + "swiftHeapObject" : { + "_0" : "SimpleClassIdentity" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "SimpleClassIdentity" + } + } + }, + { + "abiName" : "bjs_ClassRoundtripIdentity_makeSimpleClassIdentity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeSimpleClassIdentity", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "SimpleClassIdentity" + } + } + }, + { + "abiName" : "bjs_ClassRoundtripIdentity_takeSimpleClassIdentity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeSimpleClassIdentity", + "parameters" : [ + { + "label" : "_", + "name" : "obj", + "type" : { + "swiftHeapObject" : { + "_0" : "SimpleClassIdentity" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "ClassRoundtripIdentity", + "properties" : [ + + ], + "swiftCallName" : "ClassRoundtripIdentity" + }, + { + "constructor" : { + "abiName" : "bjs_IdentityCacheBenchmarkIdentity_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "identityMode" : true, + "methods" : [ + { + "abiName" : "bjs_IdentityCacheBenchmarkIdentity_setupPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setupPool", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getPoolRepeated", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "SimpleClassIdentity" + } + } + } + } + } + ], + "name" : "IdentityCacheBenchmarkIdentity", + "properties" : [ + + ], + "swiftCallName" : "IdentityCacheBenchmarkIdentity" + }, { "constructor" : { "abiName" : "bjs_ArrayRoundtrip_init", diff --git a/Benchmarks/run.js b/Benchmarks/run.js index 5a1ae61e6..444a33be0 100644 --- a/Benchmarks/run.js +++ b/Benchmarks/run.js @@ -282,7 +282,7 @@ async function singleRun(results, nameFilter, iterations) { return; } // Warmup to reduce JIT/IC noise. - body(); + body() if (typeof globalThis.gc === "function") { globalThis.gc(); } @@ -869,6 +869,96 @@ async function singleRun(results, nameFilter, iterations) { arrayRoundtrip.roundtripOptionalArray(null) } }) + + // Identity mode benchmarks - compare classes with and without @JS(identityMode: true) + + // Non-identity baseline (mode = "none") + const classRoundtripNone = new exports.ClassRoundtrip() + const baseObjNone = new exports.SimpleClass('Hello', 42, true, 0.5, 3.14159) + + benchmarkRunner("Identity/none/passBothWaysRoundtrip", () => { + let current = baseObjNone + for (let i = 0; i < iterations; i++) { + current = classRoundtripNone.roundtripSimpleClass(current) + } + }) + + benchmarkRunner("Identity/none/swiftCreatesObject", () => { + for (let i = 0; i < iterations; i++) { + classRoundtripNone.makeSimpleClass() + } + }) + + benchmarkRunner("Identity/none/swiftConsumesSameObject", () => { + for (let i = 0; i < iterations; i++) { + classRoundtripNone.takeSimpleClass(baseObjNone) + } + }) + + benchmarkRunner("Identity/none/churnObjects", () => { + for (let i = 0; i < iterations; i++) { + const obj = new exports.SimpleClass(`temp ${i}`, i, true, 0.5, 3.14159) + classRoundtripNone.roundtripSimpleClass(obj) + obj.release() + } + }) + + const identityCacheNone = new exports.IdentityCacheBenchmark() + identityCacheNone.setupPool(100) + identityCacheNone.getPoolRepeated() // warm the cache + benchmarkRunner("Identity/none/getPoolRepeated_100", () => { + for (let i = 0; i < Math.floor(iterations / 100); i++) { + identityCacheNone.getPoolRepeated() + } + }) + identityCacheNone.release() + + baseObjNone.release() + classRoundtripNone.release() + + // Identity mode (mode = "pointer") + const classRoundtripId = new exports.ClassRoundtripIdentity() + const baseObjId = new exports.SimpleClassIdentity('Hello', 42, true, 0.5, 3.14159) + + benchmarkRunner("Identity/pointer/passBothWaysRoundtrip", () => { + let current = baseObjId + for (let i = 0; i < iterations; i++) { + current = classRoundtripId.roundtripSimpleClassIdentity(current) + } + }) + + benchmarkRunner("Identity/pointer/swiftCreatesObject", () => { + for (let i = 0; i < iterations; i++) { + classRoundtripId.makeSimpleClassIdentity() + } + }) + + benchmarkRunner("Identity/pointer/swiftConsumesSameObject", () => { + for (let i = 0; i < iterations; i++) { + classRoundtripId.takeSimpleClassIdentity(baseObjId) + } + }) + + benchmarkRunner("Identity/pointer/churnObjects", () => { + for (let i = 0; i < iterations; i++) { + const obj = new exports.SimpleClassIdentity(`temp ${i}`, i, true, 0.5, 3.14159) + classRoundtripId.roundtripSimpleClassIdentity(obj) + obj.release() + } + }) + + const identityCacheId = new exports.IdentityCacheBenchmarkIdentity() + identityCacheId.setupPool(100) + identityCacheId.getPoolRepeated() // warm the cache + benchmarkRunner("Identity/pointer/getPoolRepeated_100", () => { + for (let i = 0; i < Math.floor(iterations / 100); i++) { + identityCacheId.getPoolRepeated() + } + }) + identityCacheId.release() + + baseObjId.release() + classRoundtripId.release() } /** @@ -984,7 +1074,7 @@ async function main() { 'min-runs': { type: 'string', default: '5' }, 'max-runs': { type: 'string', default: '50' }, 'target-cv': { type: 'string', default: '5' }, - filter: { type: 'string' } + filter: { type: 'string' }, } }); @@ -1017,7 +1107,7 @@ async function main() { console.log(`Results will be saved to: ${args.values.output}`); } - await runUntilStable(results, options, width, nameFilter, filterArg, iterations); + await runUntilStable(results, options, width, nameFilter, filterArg, iterations) } else { // Fixed number of runs mode const runs = parseInt(args.values.runs, 10); @@ -1039,7 +1129,7 @@ async function main() { console.log("\nOverall Progress:"); for (let i = 0; i < runs; i++) { updateProgress(i, runs, "Benchmark Runs:", width); - await singleRun(results, nameFilter, iterations); + await singleRun(results, nameFilter, iterations) if (i === 0 && Object.keys(results).length === 0) { process.stdout.write("\n"); console.error(`No benchmarks matched filter: ${filterArg}`); diff --git a/Package.swift b/Package.swift index 820524177..3d0f1e943 100644 --- a/Package.swift +++ b/Package.swift @@ -217,5 +217,17 @@ let package = Package( ], linkerSettings: testingLinkerFlags ), + .testTarget( + name: "BridgeJSIdentityTests", + dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], + exclude: [ + "bridge-js.config.json", + "Generated/JavaScript", + ], + swiftSettings: [ + .enableExperimentalFeature("Extern") + ], + linkerSettings: testingLinkerFlags + ), ] ) diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift index 60adb7a5f..fe98ec529 100644 --- a/Package@swift-6.1.swift +++ b/Package@swift-6.1.swift @@ -206,5 +206,17 @@ let package = Package( ], linkerSettings: testingLinkerFlags ), + .testTarget( + name: "BridgeJSIdentityTests", + dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], + exclude: [ + "bridge-js.config.json", + "Generated/JavaScript", + ], + swiftSettings: [ + .enableExperimentalFeature("Extern") + ], + linkerSettings: testingLinkerFlags + ), ] ) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift index 06fb422a9..37040d7a6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift @@ -342,20 +342,32 @@ public struct BridgeJSConfig: Codable { /// Default: `false` public var exposeToGlobal: Bool - public init(tools: [String: String]? = nil, exposeToGlobal: Bool = false) { + /// The identity mode to use for exported Swift heap objects. + /// + /// When `"pointer"`, Swift heap objects are tracked by pointer identity, + /// enabling identity-based caching. When `"none"` or `nil`, no identity + /// tracking is performed. + /// + /// Default: `nil` (treated as `"none"`) + public var identityMode: String? + + public init(tools: [String: String]? = nil, exposeToGlobal: Bool = false, identityMode: String? = nil) { self.tools = tools self.exposeToGlobal = exposeToGlobal + self.identityMode = identityMode } enum CodingKeys: String, CodingKey { case tools case exposeToGlobal + case identityMode } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) tools = try container.decodeIfPresent([String: String].self, forKey: .tools) exposeToGlobal = try container.decodeIfPresent(Bool.self, forKey: .exposeToGlobal) ?? false + identityMode = try container.decodeIfPresent(String.self, forKey: .identityMode) } /// Load the configuration file from the SwiftPM package target directory. @@ -398,7 +410,8 @@ public struct BridgeJSConfig: Codable { func merging(overrides: BridgeJSConfig) -> BridgeJSConfig { return BridgeJSConfig( tools: (tools ?? [:]).merging(overrides.tools ?? [:], uniquingKeysWith: { $1 }), - exposeToGlobal: overrides.exposeToGlobal + exposeToGlobal: overrides.exposeToGlobal, + identityMode: overrides.identityMode ?? identityMode ) } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 7b7c6ca30..3d8f417e3 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -16,14 +16,16 @@ public final class SwiftToSkeleton { public let progress: ProgressReporting public let moduleName: String public let exposeToGlobal: Bool + public let identityMode: String? private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = [] let typeDeclResolver: TypeDeclResolver - public init(progress: ProgressReporting, moduleName: String, exposeToGlobal: Bool) { + public init(progress: ProgressReporting, moduleName: String, exposeToGlobal: Bool, identityMode: String? = nil) { self.progress = progress self.moduleName = moduleName self.exposeToGlobal = exposeToGlobal + self.identityMode = identityMode self.typeDeclResolver = TypeDeclResolver() // Index known types provided by JavaScriptKit @@ -42,7 +44,13 @@ public final class SwiftToSkeleton { public func finalize() throws -> BridgeJSSkeleton { var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = [] var importedFiles: [ImportedFileSkeleton] = [] - var exported = ExportedSkeleton(functions: [], classes: [], enums: [], exposeToGlobal: exposeToGlobal) + var exported = ExportedSkeleton( + functions: [], + classes: [], + enums: [], + exposeToGlobal: exposeToGlobal, + identityMode: identityMode + ) var exportCollectors: [ExportSwiftAPICollector] = [] for (sourceFile, inputFilePath) in sourceFiles { @@ -1189,6 +1197,14 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return nil } + private func extractIdentityMode(from jsAttribute: AttributeSyntax) -> Bool? { + guard let arguments = jsAttribute.arguments?.as(LabeledExprListSyntax.self), + let identityArg = arguments.first(where: { $0.label?.text == "identityMode" }) + else { return nil } + let text = identityArg.expression.trimmedDescription + return text == "true" + } + override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren } @@ -1376,6 +1392,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { for: node, message: "Class visibility must be at least internal" ) + let classIdentityMode = extractIdentityMode(from: jsAttribute) let exportedClass = ExportedClass( name: name, swiftCallName: swiftCallName, @@ -1383,7 +1400,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { constructor: nil, methods: [], properties: [], - namespace: namespaceResult.namespace + namespace: namespaceResult.namespace, + identityMode: classIdentityMode ) let uniqueKey = makeKey(name: name, namespace: namespaceResult.namespace) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 60b34ff16..64a0d2394 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -25,6 +25,21 @@ public struct BridgeJSLink { self.sharedMemory = sharedMemory } + /// The identity mode from the config file, resolved from skeletons. + var configIdentityMode: String { + skeletons.compactMap(\.exported).compactMap(\.identityMode).first ?? "none" + } + + /// 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 + if let classOverride = klass.identityMode { + return classOverride + } + // Fall back to config default + return configIdentityMode == "pointer" + } + mutating func addSkeletonFile(data: Data) throws { do { let unified = try JSONDecoder().decode(BridgeJSSkeleton.self, from: data) @@ -85,31 +100,52 @@ public struct BridgeJSLink { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; + static __wrap(pointer, deinit, prototype, identityCache) { + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; """ if enableLifetimeTracking { - output += " TRACKING.wrap(pointer, deinit, prototype, state);\n" + output += " TRACKING.wrap(pointer, deinit, prototype, state);\n" } output += """ - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { """ if enableLifetimeTracking { - output += " TRACKING.release(this);\n" + output += " TRACKING.release(this);\n" } output += """ const state = this.__swiftHeapObjectState; @@ -118,6 +154,7 @@ public struct BridgeJSLink { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } @@ -1965,13 +2002,24 @@ extension BridgeJSLink { dtsExportEntryPrinter.write("\(klass.name): {") jsPrinter.write("class \(klass.name) extends SwiftHeapObject {") - // Always add __construct and constructor methods for all classes + // Per-class identity mode: determine at codegen time whether this class uses identity caching + let useIdentity = shouldUseIdentityCache(for: klass) jsPrinter.indent { + if useIdentity { + jsPrinter.write("static __identityCache = new Map();") + jsPrinter.nextLine() + } jsPrinter.write("static __construct(ptr) {") jsPrinter.indent { - jsPrinter.write( - "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype);" - ) + if useIdentity { + jsPrinter.write( + "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype, \(klass.name).__identityCache);" + ) + } else { + jsPrinter.write( + "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype, null);" + ) + } } jsPrinter.write("}") jsPrinter.nextLine() @@ -1991,10 +2039,11 @@ extension BridgeJSLink { jsPrinter.indent { jsPrinter.write("constructor(\(constructorParamList)) {") let returnExpr = thunkBuilder.callConstructor(abiName: constructor.abiName) + let constructCall = "\(klass.name).__construct(\(returnExpr))" jsPrinter.indent { thunkBuilder.renderFunctionBody( into: jsPrinter, - returnExpr: "\(klass.name).__construct(\(returnExpr))" + returnExpr: constructCall ) } jsPrinter.write("}") diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index c5672c79c..03e6d676a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -784,6 +784,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { public var methods: [ExportedFunction] public var properties: [ExportedProperty] public var namespace: [String]? + public var identityMode: Bool? // nil = use config default, true/false = override public init( name: String, @@ -792,7 +793,8 @@ public struct ExportedClass: Codable, NamespacedExportedType { constructor: ExportedConstructor? = nil, methods: [ExportedFunction], properties: [ExportedProperty] = [], - namespace: [String]? = nil + namespace: [String]? = nil, + identityMode: Bool? = nil ) { self.name = name self.swiftCallName = swiftCallName @@ -801,6 +803,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { self.methods = methods self.properties = properties self.namespace = namespace + self.identityMode = identityMode } } @@ -890,13 +893,20 @@ public struct ExportedSkeleton: Codable { /// through the exports object. public var exposeToGlobal: Bool + /// The identity mode for exported Swift heap objects. + /// + /// When `"pointer"`, Swift heap objects are tracked by pointer identity. + /// When `"none"` or `nil`, no identity tracking is performed. + public var identityMode: String? + public init( functions: [ExportedFunction], classes: [ExportedClass], enums: [ExportedEnum], structs: [ExportedStruct] = [], protocols: [ExportedProtocol] = [], - exposeToGlobal: Bool + exposeToGlobal: Bool, + identityMode: String? = nil ) { self.functions = functions self.classes = classes @@ -904,6 +914,7 @@ public struct ExportedSkeleton: Codable { self.structs = structs self.protocols = protocols self.exposeToGlobal = exposeToGlobal + self.identityMode = identityMode } public mutating func append(_ other: ExportedSkeleton) { @@ -913,6 +924,7 @@ public struct ExportedSkeleton: Codable { self.structs.append(contentsOf: other.structs) self.protocols.append(contentsOf: other.protocols) assert(self.exposeToGlobal == other.exposeToGlobal) + assert(self.identityMode == other.identityMode) } public var isEmpty: Bool { diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index a71aaee44..3e3f27ea1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -165,7 +165,8 @@ import BridgeJSUtilities let swiftToSkeleton = SwiftToSkeleton( progress: progress, moduleName: moduleName, - exposeToGlobal: config.exposeToGlobal + exposeToGlobal: config.exposeToGlobal, + identityMode: config.identityMode ) for inputFile in inputFiles.sorted() { try withSpan("Parsing \(inputFile)") { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 711b04512..64c9ae535 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -105,4 +105,53 @@ import Testing ) try snapshot(bridgeJSLink: bridgeJSLink, name: "MixedModules") } + + @Test + func perClassIdentityModeFromAnnotation() throws { + let url = Self.inputsDirectory.appendingPathComponent("IdentityModeClass.swift") + let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + identityMode: nil // no config default + ) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "IdentityModeClass.swift") + let outputSkeleton = try swiftAPI.finalize() + + // Verify skeleton has per-class identity mode (not captured by snapshots) + let cachedClass = outputSkeleton.exported!.classes.first { $0.name == "CachedModel" } + let uncachedClass = outputSkeleton.exported!.classes.first { $0.name == "UncachedModel" } + let explicitlyUncachedClass = outputSkeleton.exported!.classes.first { $0.name == "ExplicitlyUncachedModel" } + #expect(cachedClass?.identityMode == true) + #expect(uncachedClass?.identityMode == nil) + #expect(explicitlyUncachedClass?.identityMode == false) + + // Verify generated JS via snapshot + let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton], sharedMemory: false) + try snapshot(bridgeJSLink: bridgeJSLink, name: "IdentityModeClass.PerClass") + } + + @Test + func perClassIdentityModeWithConfigOverride() throws { + let url = Self.inputsDirectory.appendingPathComponent("IdentityModeClass.swift") + let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + identityMode: "pointer" // config says pointer for all classes + ) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "IdentityModeClass.swift") + let outputSkeleton = try swiftAPI.finalize() + + // When config says "pointer", classes without annotation get identity mode from config. + // But @JS(identityMode: false) should still override to "without identity". + let explicitlyUncachedClass = outputSkeleton.exported!.classes.first { $0.name == "ExplicitlyUncachedModel" } + #expect(explicitlyUncachedClass?.identityMode == false) + + // Verify generated JS via snapshot + let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton], sharedMemory: false) + try snapshot(bridgeJSLink: bridgeJSLink, name: "IdentityModeClass.ConfigPointer") + } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/IdentityModeClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/IdentityModeClass.swift new file mode 100644 index 000000000..4d50b6c76 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/IdentityModeClass.swift @@ -0,0 +1,28 @@ +import JavaScriptKit + +@JS(identityMode: true) +class CachedModel { + @JS var name: String + + @JS init(name: String) { + self.name = name + } +} + +@JS +class UncachedModel { + @JS var value: Int + + @JS init(value: Int) { + self.value = value + } +} + +@JS(identityMode: false) +class ExplicitlyUncachedModel { + @JS var count: Int + + @JS init(count: Int) { + self.count = count + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json new file mode 100644 index 000000000..d7a9064dc --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json @@ -0,0 +1,148 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_CachedModel_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "identityMode" : true, + "methods" : [ + + ], + "name" : "CachedModel", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "CachedModel" + }, + { + "constructor" : { + "abiName" : "bjs_UncachedModel_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "UncachedModel", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "UncachedModel" + }, + { + "constructor" : { + "abiName" : "bjs_ExplicitlyUncachedModel_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "count", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "identityMode" : false, + "methods" : [ + + ], + "name" : "ExplicitlyUncachedModel", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "ExplicitlyUncachedModel" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift new file mode 100644 index 000000000..a79b91d56 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift @@ -0,0 +1,188 @@ +@_expose(wasm, "bjs_CachedModel_init") +@_cdecl("bjs_CachedModel_init") +public func _bjs_CachedModel_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = CachedModel(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_CachedModel_name_get") +@_cdecl("bjs_CachedModel_name_get") +public func _bjs_CachedModel_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = CachedModel.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_CachedModel_name_set") +@_cdecl("bjs_CachedModel_name_set") +public func _bjs_CachedModel_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + CachedModel.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_CachedModel_deinit") +@_cdecl("bjs_CachedModel_deinit") +public func _bjs_CachedModel_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension CachedModel: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_CachedModel_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_CachedModel_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_CachedModel_wrap") +fileprivate func _bjs_CachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_CachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_CachedModel_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_CachedModel_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_UncachedModel_init") +@_cdecl("bjs_UncachedModel_init") +public func _bjs_UncachedModel_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = UncachedModel(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_UncachedModel_value_get") +@_cdecl("bjs_UncachedModel_value_get") +public func _bjs_UncachedModel_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = UncachedModel.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_UncachedModel_value_set") +@_cdecl("bjs_UncachedModel_value_set") +public func _bjs_UncachedModel_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + UncachedModel.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_UncachedModel_deinit") +@_cdecl("bjs_UncachedModel_deinit") +public func _bjs_UncachedModel_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension UncachedModel: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_UncachedModel_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_UncachedModel_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_UncachedModel_wrap") +fileprivate func _bjs_UncachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_UncachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_UncachedModel_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_UncachedModel_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_ExplicitlyUncachedModel_init") +@_cdecl("bjs_ExplicitlyUncachedModel_init") +public func _bjs_ExplicitlyUncachedModel_init(_ count: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ExplicitlyUncachedModel(count: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ExplicitlyUncachedModel_count_get") +@_cdecl("bjs_ExplicitlyUncachedModel_count_get") +public func _bjs_ExplicitlyUncachedModel_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = ExplicitlyUncachedModel.bridgeJSLiftParameter(_self).count + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ExplicitlyUncachedModel_count_set") +@_cdecl("bjs_ExplicitlyUncachedModel_count_set") +public func _bjs_ExplicitlyUncachedModel_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + ExplicitlyUncachedModel.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ExplicitlyUncachedModel_deinit") +@_cdecl("bjs_ExplicitlyUncachedModel_deinit") +public func _bjs_ExplicitlyUncachedModel_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ExplicitlyUncachedModel: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ExplicitlyUncachedModel_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ExplicitlyUncachedModel_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ExplicitlyUncachedModel_wrap") +fileprivate func _bjs_ExplicitlyUncachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ExplicitlyUncachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ExplicitlyUncachedModel_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ExplicitlyUncachedModel_wrap_extern(pointer) +} \ 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 85e9c749a..8359220c9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -348,18 +348,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -369,18 +390,19 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Item extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Item_deinit, Item.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Item_deinit, Item.prototype, null); } } class MultiArrayContainer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MultiArrayContainer_deinit, MultiArrayContainer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MultiArrayContainer_deinit, MultiArrayContainer.prototype, null); } constructor(nums, strs) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 004320e4b..cafd250b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -279,18 +279,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -300,12 +321,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class DefaultGreeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DefaultGreeter_deinit, DefaultGreeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DefaultGreeter_deinit, DefaultGreeter.prototype, null); } constructor(name) { @@ -328,7 +350,7 @@ export async function createInstantiator(options, swift) { } class EmptyGreeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_EmptyGreeter_deinit, EmptyGreeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_EmptyGreeter_deinit, EmptyGreeter.prototype, null); } constructor() { @@ -338,7 +360,7 @@ export async function createInstantiator(options, swift) { } class ConstructorDefaults extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ConstructorDefaults_deinit, ConstructorDefaults.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ConstructorDefaults_deinit, ConstructorDefaults.prototype, null); } constructor(name = "Default", count = 42, enabled = true, status = StatusValues.Active, tag = null) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index b6cf2c253..920017972 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -288,18 +288,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -309,12 +330,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Box extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Box_deinit, Box.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Box_deinit, Box.prototype, null); } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index eb474d3b0..3d2230c6c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -955,18 +955,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -976,12 +997,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class User extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_User_deinit, User.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_User_deinit, User.prototype, null); } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 948039cf9..10fe31f64 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -271,18 +271,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -292,12 +313,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype, null); } constructor() { @@ -320,7 +342,7 @@ export async function createInstantiator(options, swift) { } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype, null); } constructor() { @@ -333,7 +355,7 @@ export async function createInstantiator(options, swift) { } class TestServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype, null); } constructor() { @@ -346,7 +368,7 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 5201350b2..a6aeee4b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -252,18 +252,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -273,12 +294,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converter_deinit, Converter.prototype, null); } constructor() { @@ -301,7 +323,7 @@ export async function createInstantiator(options, swift) { } class HTTPServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_API_HTTPServer_deinit, HTTPServer.prototype, null); } constructor() { @@ -314,7 +336,7 @@ export async function createInstantiator(options, swift) { } class TestServer extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Networking_APIV2_Internal_TestServer_deinit, TestServer.prototype, null); } constructor() { @@ -327,7 +349,7 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Formatting_Converter_deinit, Converter.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts new file mode 100644 index 000000000..e5e2a3a84 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts @@ -0,0 +1,42 @@ +// 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 CachedModel extends SwiftHeapObject { + name: string; +} +export interface UncachedModel extends SwiftHeapObject { + value: number; +} +export interface ExplicitlyUncachedModel extends SwiftHeapObject { + count: number; +} +export type Exports = { + CachedModel: { + new(name: string): CachedModel; + } + UncachedModel: { + new(value: number): UncachedModel; + } + ExplicitlyUncachedModel: { + new(count: number): ExplicitlyUncachedModel; + } +} +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/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js new file mode 100644 index 000000000..c2490c0ea --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -0,0 +1,342 @@ +// 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 = []; + 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(); + } + 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_CachedModel_wrap"] = function(pointer) { + const obj = _exports['CachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_ExplicitlyUncachedModel_wrap"] = function(pointer) { + const obj = _exports['ExplicitlyUncachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_UncachedModel_wrap"] = function(pointer) { + const obj = _exports['UncachedModel'].__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 CachedModel extends SwiftHeapObject { + static __identityCache = new Map(); + + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_CachedModel_deinit, CachedModel.prototype, CachedModel.__identityCache); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_CachedModel_init(nameId, nameBytes.length); + return CachedModel.__construct(ret); + } + get name() { + instance.exports.bjs_CachedModel_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_CachedModel_name_set(this.pointer, valueId, valueBytes.length); + } + } + class UncachedModel extends SwiftHeapObject { + static __identityCache = new Map(); + + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UncachedModel_deinit, UncachedModel.prototype, UncachedModel.__identityCache); + } + + constructor(value) { + const ret = instance.exports.bjs_UncachedModel_init(value); + return UncachedModel.__construct(ret); + } + get value() { + const ret = instance.exports.bjs_UncachedModel_value_get(this.pointer); + return ret; + } + set value(value) { + instance.exports.bjs_UncachedModel_value_set(this.pointer, value); + } + } + class ExplicitlyUncachedModel extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ExplicitlyUncachedModel_deinit, ExplicitlyUncachedModel.prototype, null); + } + + constructor(count) { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_init(count); + return ExplicitlyUncachedModel.__construct(ret); + } + get count() { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_count_get(this.pointer); + return ret; + } + set count(value) { + instance.exports.bjs_ExplicitlyUncachedModel_count_set(this.pointer, value); + } + } + const exports = { + CachedModel, + UncachedModel, + ExplicitlyUncachedModel, + }; + _exports = exports; + return 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 new file mode 100644 index 000000000..e5e2a3a84 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts @@ -0,0 +1,42 @@ +// 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 CachedModel extends SwiftHeapObject { + name: string; +} +export interface UncachedModel extends SwiftHeapObject { + value: number; +} +export interface ExplicitlyUncachedModel extends SwiftHeapObject { + count: number; +} +export type Exports = { + CachedModel: { + new(name: string): CachedModel; + } + UncachedModel: { + new(value: number): UncachedModel; + } + ExplicitlyUncachedModel: { + new(count: number): ExplicitlyUncachedModel; + } +} +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/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js new file mode 100644 index 000000000..d970c5d77 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -0,0 +1,340 @@ +// 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 = []; + 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(); + } + 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_CachedModel_wrap"] = function(pointer) { + const obj = _exports['CachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_ExplicitlyUncachedModel_wrap"] = function(pointer) { + const obj = _exports['ExplicitlyUncachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_UncachedModel_wrap"] = function(pointer) { + const obj = _exports['UncachedModel'].__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 CachedModel extends SwiftHeapObject { + static __identityCache = new Map(); + + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_CachedModel_deinit, CachedModel.prototype, CachedModel.__identityCache); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_CachedModel_init(nameId, nameBytes.length); + return CachedModel.__construct(ret); + } + get name() { + instance.exports.bjs_CachedModel_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_CachedModel_name_set(this.pointer, valueId, valueBytes.length); + } + } + class UncachedModel extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UncachedModel_deinit, UncachedModel.prototype, null); + } + + constructor(value) { + const ret = instance.exports.bjs_UncachedModel_init(value); + return UncachedModel.__construct(ret); + } + get value() { + const ret = instance.exports.bjs_UncachedModel_value_get(this.pointer); + return ret; + } + set value(value) { + instance.exports.bjs_UncachedModel_value_set(this.pointer, value); + } + } + class ExplicitlyUncachedModel extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ExplicitlyUncachedModel_deinit, ExplicitlyUncachedModel.prototype, null); + } + + constructor(count) { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_init(count); + return ExplicitlyUncachedModel.__construct(ret); + } + get count() { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_count_get(this.pointer); + return ret; + } + set count(value) { + instance.exports.bjs_ExplicitlyUncachedModel_count_set(this.pointer, value); + } + } + const exports = { + CachedModel, + UncachedModel, + ExplicitlyUncachedModel, + }; + _exports = exports; + return 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 new file mode 100644 index 000000000..e5e2a3a84 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts @@ -0,0 +1,42 @@ +// 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 CachedModel extends SwiftHeapObject { + name: string; +} +export interface UncachedModel extends SwiftHeapObject { + value: number; +} +export interface ExplicitlyUncachedModel extends SwiftHeapObject { + count: number; +} +export type Exports = { + CachedModel: { + new(name: string): CachedModel; + } + UncachedModel: { + new(value: number): UncachedModel; + } + ExplicitlyUncachedModel: { + new(count: number): ExplicitlyUncachedModel; + } +} +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/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js new file mode 100644 index 000000000..d970c5d77 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -0,0 +1,340 @@ +// 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 = []; + 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(); + } + 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_CachedModel_wrap"] = function(pointer) { + const obj = _exports['CachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_ExplicitlyUncachedModel_wrap"] = function(pointer) { + const obj = _exports['ExplicitlyUncachedModel'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_UncachedModel_wrap"] = function(pointer) { + const obj = _exports['UncachedModel'].__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 CachedModel extends SwiftHeapObject { + static __identityCache = new Map(); + + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_CachedModel_deinit, CachedModel.prototype, CachedModel.__identityCache); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_CachedModel_init(nameId, nameBytes.length); + return CachedModel.__construct(ret); + } + get name() { + instance.exports.bjs_CachedModel_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_CachedModel_name_set(this.pointer, valueId, valueBytes.length); + } + } + class UncachedModel extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UncachedModel_deinit, UncachedModel.prototype, null); + } + + constructor(value) { + const ret = instance.exports.bjs_UncachedModel_init(value); + return UncachedModel.__construct(ret); + } + get value() { + const ret = instance.exports.bjs_UncachedModel_value_get(this.pointer); + return ret; + } + set value(value) { + instance.exports.bjs_UncachedModel_value_set(this.pointer, value); + } + } + class ExplicitlyUncachedModel extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ExplicitlyUncachedModel_deinit, ExplicitlyUncachedModel.prototype, null); + } + + constructor(count) { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_init(count); + return ExplicitlyUncachedModel.__construct(ret); + } + get count() { + const ret = instance.exports.bjs_ExplicitlyUncachedModel_count_get(this.pointer); + return ret; + } + set count(value) { + instance.exports.bjs_ExplicitlyUncachedModel_count_set(this.pointer, value); + } + } + const exports = { + CachedModel, + UncachedModel, + ExplicitlyUncachedModel, + }; + _exports = exports; + return 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 08675da6a..0258b63b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -342,18 +342,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -363,12 +384,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class JSValueHolder extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_JSValueHolder_deinit, JSValueHolder.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_JSValueHolder_deinit, JSValueHolder.prototype, null); } constructor(value, optionalValue) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index f4fe4dd61..195eef468 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -215,18 +215,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -236,12 +257,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 4ce318f40..ca54493f6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -223,18 +223,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -244,12 +265,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalAPI_GlobalClass_deinit, GlobalClass.prototype, null); } constructor() { @@ -265,7 +287,7 @@ export async function createInstantiator(options, swift) { } class PrivateClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 025a6fc8a..3551caab2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -215,18 +215,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -236,12 +257,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class PrivateClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateAPI_PrivateClass_deinit, PrivateClass.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index f4596dba7..a63df44be 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -227,18 +227,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -248,12 +269,13 @@ export async function createInstantiator(options, swift) { } 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___Swift_Foundation_Greeter_deinit, Greeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_Greeter_deinit, Greeter.prototype, null); } constructor(name) { @@ -281,7 +303,7 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype, null); } constructor() { @@ -297,7 +319,7 @@ export async function createInstantiator(options, swift) { } class UUID extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype, null); } uuidString() { @@ -309,7 +331,7 @@ export async function createInstantiator(options, swift) { } class Container extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 92ce69cbb..32a325bda 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -227,18 +227,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -248,12 +269,13 @@ export async function createInstantiator(options, swift) { } 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___Swift_Foundation_Greeter_deinit, Greeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_Greeter_deinit, Greeter.prototype, null); } constructor(name) { @@ -281,7 +303,7 @@ export async function createInstantiator(options, swift) { } class Converter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Utils_Converters_Converter_deinit, Converter.prototype, null); } constructor() { @@ -297,7 +319,7 @@ export async function createInstantiator(options, swift) { } class UUID extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs___Swift_Foundation_UUID_deinit, UUID.prototype, null); } uuidString() { @@ -309,7 +331,7 @@ export async function createInstantiator(options, swift) { } class Container extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Collections_Container_deinit, Container.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 37408a42d..5971c2fa8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -471,18 +471,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -492,12 +513,13 @@ export async function createInstantiator(options, swift) { } 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); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype, null); } constructor(name) { @@ -558,7 +580,7 @@ export async function createInstantiator(options, swift) { } class OptionalPropertyHolder extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_OptionalPropertyHolder_deinit, OptionalPropertyHolder.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_OptionalPropertyHolder_deinit, OptionalPropertyHolder.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 658702a39..7f840708e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -215,18 +215,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -236,12 +257,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class PropertyHolder extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyHolder_deinit, PropertyHolder.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyHolder_deinit, PropertyHolder.prototype, null); } constructor(intValue, floatValue, doubleValue, boolValue, stringValue, jsObject) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index f82e41703..9fb9b172b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -575,18 +575,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -596,12 +617,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Helper extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Helper_deinit, Helper.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Helper_deinit, Helper.prototype, null); } constructor(value) { @@ -621,7 +643,7 @@ export async function createInstantiator(options, swift) { } class MyViewController extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MyViewController_deinit, MyViewController.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MyViewController_deinit, MyViewController.prototype, null); } constructor(delegate) { @@ -682,7 +704,7 @@ export async function createInstantiator(options, swift) { } class DelegateManager extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DelegateManager_deinit, DelegateManager.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DelegateManager_deinit, DelegateManager.prototype, null); } constructor(delegates) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index 13070a3cc..aefdb5679 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -361,18 +361,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -382,12 +403,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Widget extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Widget_deinit, Widget.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Widget_deinit, Widget.prototype, null); } constructor(name) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 42e25545e..ef685b8a4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -259,18 +259,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -280,12 +301,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class MathUtils extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 4cf9615fb..1fd066076 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -259,18 +259,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -280,12 +301,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class MathUtils extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 9928804eb..5800fcb56 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -220,18 +220,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -241,12 +262,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class PropertyClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index f82ac20df..b81255810 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -220,18 +220,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -241,12 +262,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class PropertyClass extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype, null); } constructor() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index cf9faa707..9ee57d692 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -243,18 +243,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -264,12 +285,13 @@ export async function createInstantiator(options, swift) { } 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); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype, null); } constructor(name) { @@ -325,13 +347,13 @@ export async function createInstantiator(options, swift) { } class PublicGreeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PublicGreeter_deinit, PublicGreeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PublicGreeter_deinit, PublicGreeter.prototype, null); } } class PackageGreeter extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PackageGreeter_deinit, PackageGreeter.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PackageGreeter_deinit, PackageGreeter.prototype, null); } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 7e90c9415..03a5504e4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -902,18 +902,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -923,12 +944,13 @@ export async function createInstantiator(options, swift) { } state.hasReleased = true; swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); state.deinit(state.pointer); } } class Person extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Person_deinit, Person.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Person_deinit, Person.prototype, null); } constructor(name) { @@ -940,7 +962,7 @@ export async function createInstantiator(options, swift) { } class TestProcessor extends SwiftHeapObject { static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestProcessor_deinit, TestProcessor.prototype); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestProcessor_deinit, TestProcessor.prototype, null); } constructor(transform) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index a60615686..abfb24d48 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -484,18 +484,39 @@ export async function createInstantiator(options, swift) { 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) { - const obj = Object.create(prototype); - const state = { pointer, deinit, hasReleased: false }; - obj.pointer = pointer; - obj.__swiftHeapObjectState = state; - swiftHeapObjectFinalizationRegistry.register(obj, state, state); - return obj; + 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() { @@ -505,12 +526,13 @@ export async function createInstantiator(options, swift) { } 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); + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype, null); } constructor(name) { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md index 604017aad..0bd69aa5b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md @@ -73,6 +73,36 @@ const greeter = new exports.MyModule.Greeter("World"); // globalThis.MyModule is undefined ``` +### `identityMode` + +Controls whether exported Swift class instances use pointer-based identity mapping. + +When set to `"pointer"`, every class in the target uses identity caching — the same Swift heap pointer always returns the same JavaScript wrapper object. This makes `===` identity checks work across boundary crossings. + +```json +{ + "identityMode": "pointer" +} +``` + +**With `identityMode: "pointer"`:** + +```javascript +const a = exports.getModel(); +const b = exports.getModel(); // same Swift object +console.log(a === b); // true +``` + +**Without (default):** + +```javascript +const a = exports.getModel(); +const b = exports.getModel(); // same Swift object +console.log(a === b); // false — different JS wrapper each time +``` + +For finer control, use the `@JS(identityMode:)` parameter on individual classes instead of the project-wide config. See for details. + ### `tools` Specify custom paths for external executables. This is particularly useful when working in environments like Xcode where the system PATH may not be inherited, or when you need to use a specific version of tools for your project. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md index a16c81286..8a1b7dff5 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -135,6 +135,46 @@ Classes use **reference semantics** when crossing the Swift/JavaScript boundary: This differs from structs, which use copy semantics and transfer data by value. +## Identity Mode + +By default, each boundary crossing creates a new JavaScript wrapper for the same Swift object. This means `===` identity checks fail even when the underlying Swift object is the same: + +```javascript +const a = exports.getModel(); +const b = exports.getModel(); // same Swift object +console.log(a === b); // false — different wrappers +``` + +For classes where wrapper identity matters, enable identity mode with the `identityMode` parameter: + +```swift +@JS(identityMode: true) +class Model { + @JS var name: String + @JS init(name: String) { self.name = name } +} +``` + +With identity mode, BridgeJS maintains a per-class `WeakRef`-based cache keyed by the Swift heap pointer. The same pointer always returns the same JavaScript wrapper: + +```javascript +const a = exports.getModel(); +const b = exports.getModel(); // same Swift object +console.log(a === b); // true — same wrapper +``` + +Identity mode is opt-in per class. Non-annotated classes have zero overhead. To enable it for all classes in a target, use `bridge-js.config.json` instead: + +```json +{ "identityMode": "pointer" } +``` + +Per-class `@JS(identityMode: true/false)` overrides the config setting. + +### Tradeoffs + +Identity mode improves performance for reuse-heavy workloads (same objects crossing repeatedly) but adds overhead for create-heavy workloads (many short-lived objects). The cache infrastructure (`Map`, `WeakRef`, `FinalizationRegistry`) has a per-object cost that is only worthwhile when objects are returned multiple times. + ## Supported Features | Swift Feature | Status | diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 67b3488bf..3189cdeab 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -113,7 +113,8 @@ 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) = Builtin.ExternalMacro +public macro JS(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/BridgeJSIdentityTests/Generated/BridgeJS.swift b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift new file mode 100644 index 000000000..e25ebeb4c --- /dev/null +++ b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift @@ -0,0 +1,353 @@ +// bridge-js: skip +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +@_spi(BridgeJS) import JavaScriptKit + +@_expose(wasm, "bjs_getSharedSubject") +@_cdecl("bjs_getSharedSubject") +public func _bjs_getSharedSubject() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = getSharedSubject() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_resetSharedSubject") +@_cdecl("bjs_resetSharedSubject") +public func _bjs_resetSharedSubject() -> Void { + #if arch(wasm32) + resetSharedSubject() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getRetainLeakSubject") +@_cdecl("bjs_getRetainLeakSubject") +public func _bjs_getRetainLeakSubject() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = getRetainLeakSubject() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_resetRetainLeakSubject") +@_cdecl("bjs_resetRetainLeakSubject") +public func _bjs_resetRetainLeakSubject() -> Void { + #if arch(wasm32) + resetRetainLeakSubject() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getRetainLeakDeinits") +@_cdecl("bjs_getRetainLeakDeinits") +public func _bjs_getRetainLeakDeinits() -> Int32 { + #if arch(wasm32) + let ret = getRetainLeakDeinits() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_resetRetainLeakDeinits") +@_cdecl("bjs_resetRetainLeakDeinits") +public func _bjs_resetRetainLeakDeinits() -> Void { + #if arch(wasm32) + resetRetainLeakDeinits() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_setupArrayPool") +@_cdecl("bjs_setupArrayPool") +public func _bjs_setupArrayPool(_ count: Int32) -> Void { + #if arch(wasm32) + setupArrayPool(_: Int.bridgeJSLiftParameter(count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getArrayPool") +@_cdecl("bjs_getArrayPool") +public func _bjs_getArrayPool() -> Void { + #if arch(wasm32) + let ret = getArrayPool() + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getArrayPoolElement") +@_cdecl("bjs_getArrayPoolElement") +public func _bjs_getArrayPoolElement(_ index: Int32) -> Void { + #if arch(wasm32) + let ret = getArrayPoolElement(_: Int.bridgeJSLiftParameter(index)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getArrayPoolDeinits") +@_cdecl("bjs_getArrayPoolDeinits") +public func _bjs_getArrayPoolDeinits() -> Int32 { + #if arch(wasm32) + let ret = getArrayPoolDeinits() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_resetArrayPoolDeinits") +@_cdecl("bjs_resetArrayPoolDeinits") +public func _bjs_resetArrayPoolDeinits() -> Void { + #if arch(wasm32) + resetArrayPoolDeinits() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_clearArrayPool") +@_cdecl("bjs_clearArrayPool") +public func _bjs_clearArrayPool() -> Void { + #if arch(wasm32) + clearArrayPool() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityTestSubject_init") +@_cdecl("bjs_IdentityTestSubject_init") +public func _bjs_IdentityTestSubject_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = IdentityTestSubject(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityTestSubject_value_get") +@_cdecl("bjs_IdentityTestSubject_value_get") +public func _bjs_IdentityTestSubject_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = IdentityTestSubject.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityTestSubject_value_set") +@_cdecl("bjs_IdentityTestSubject_value_set") +public func _bjs_IdentityTestSubject_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + IdentityTestSubject.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityTestSubject_currentValue_get") +@_cdecl("bjs_IdentityTestSubject_currentValue_get") +public func _bjs_IdentityTestSubject_currentValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = IdentityTestSubject.bridgeJSLiftParameter(_self).currentValue + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IdentityTestSubject_deinit") +@_cdecl("bjs_IdentityTestSubject_deinit") +public func _bjs_IdentityTestSubject_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension IdentityTestSubject: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_IdentityTestSubject_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_IdentityTestSubject_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_IdentityTestSubject_wrap") +fileprivate func _bjs_IdentityTestSubject_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_IdentityTestSubject_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_IdentityTestSubject_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_IdentityTestSubject_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_RetainLeakSubject_init") +@_cdecl("bjs_RetainLeakSubject_init") +public func _bjs_RetainLeakSubject_init(_ tag: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = RetainLeakSubject(tag: Int.bridgeJSLiftParameter(tag)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RetainLeakSubject_tag_get") +@_cdecl("bjs_RetainLeakSubject_tag_get") +public func _bjs_RetainLeakSubject_tag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = RetainLeakSubject.bridgeJSLiftParameter(_self).tag + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RetainLeakSubject_tag_set") +@_cdecl("bjs_RetainLeakSubject_tag_set") +public func _bjs_RetainLeakSubject_tag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + RetainLeakSubject.bridgeJSLiftParameter(_self).tag = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RetainLeakSubject_deinit") +@_cdecl("bjs_RetainLeakSubject_deinit") +public func _bjs_RetainLeakSubject_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension RetainLeakSubject: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_RetainLeakSubject_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_RetainLeakSubject_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_RetainLeakSubject_wrap") +fileprivate func _bjs_RetainLeakSubject_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_RetainLeakSubject_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_RetainLeakSubject_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_RetainLeakSubject_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_ArrayIdentityElement_init") +@_cdecl("bjs_ArrayIdentityElement_init") +public func _bjs_ArrayIdentityElement_init(_ tag: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ArrayIdentityElement(tag: Int.bridgeJSLiftParameter(tag)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayIdentityElement_tag_get") +@_cdecl("bjs_ArrayIdentityElement_tag_get") +public func _bjs_ArrayIdentityElement_tag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = ArrayIdentityElement.bridgeJSLiftParameter(_self).tag + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayIdentityElement_tag_set") +@_cdecl("bjs_ArrayIdentityElement_tag_set") +public func _bjs_ArrayIdentityElement_tag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + ArrayIdentityElement.bridgeJSLiftParameter(_self).tag = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayIdentityElement_deinit") +@_cdecl("bjs_ArrayIdentityElement_deinit") +public func _bjs_ArrayIdentityElement_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ArrayIdentityElement: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ArrayIdentityElement_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ArrayIdentityElement_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_ArrayIdentityElement_wrap") +fileprivate func _bjs_ArrayIdentityElement_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ArrayIdentityElement_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ArrayIdentityElement_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ArrayIdentityElement_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_IdentityModeTestImports_runJsIdentityModeTests_static") +fileprivate func bjs_IdentityModeTestImports_runJsIdentityModeTests_static_extern() -> Void +#else +fileprivate func bjs_IdentityModeTestImports_runJsIdentityModeTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_IdentityModeTestImports_runJsIdentityModeTests_static() -> Void { + return bjs_IdentityModeTestImports_runJsIdentityModeTests_static_extern() +} + +func _$IdentityModeTestImports_runJsIdentityModeTests() throws(JSException) -> Void { + bjs_IdentityModeTestImports_runJsIdentityModeTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json new file mode 100644 index 000000000..d30ca00f8 --- /dev/null +++ b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json @@ -0,0 +1,447 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_IdentityTestSubject_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "IdentityTestSubject", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "currentValue", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "IdentityTestSubject" + }, + { + "constructor" : { + "abiName" : "bjs_RetainLeakSubject_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "tag", + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "RetainLeakSubject", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "RetainLeakSubject" + }, + { + "constructor" : { + "abiName" : "bjs_ArrayIdentityElement_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "tag", + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "ArrayIdentityElement", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "ArrayIdentityElement" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_getSharedSubject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getSharedSubject", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "IdentityTestSubject" + } + } + }, + { + "abiName" : "bjs_resetSharedSubject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "resetSharedSubject", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getRetainLeakSubject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getRetainLeakSubject", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "RetainLeakSubject" + } + } + }, + { + "abiName" : "bjs_resetRetainLeakSubject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "resetRetainLeakSubject", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getRetainLeakDeinits", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getRetainLeakDeinits", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_resetRetainLeakDeinits", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "resetRetainLeakDeinits", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_setupArrayPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setupArrayPool", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getArrayPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getArrayPool", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "ArrayIdentityElement" + } + } + } + } + }, + { + "abiName" : "bjs_getArrayPoolElement", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getArrayPoolElement", + "parameters" : [ + { + "label" : "_", + "name" : "index", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "ArrayIdentityElement" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_getArrayPoolDeinits", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getArrayPoolDeinits", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_resetArrayPoolDeinits", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "resetArrayPoolDeinits", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_clearArrayPool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "clearArrayPool", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "identityMode" : "pointer", + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "IdentityModeTestImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsIdentityModeTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "BridgeJSIdentityTests" +} \ No newline at end of file diff --git a/Tests/BridgeJSIdentityTests/IdentityModeTests.swift b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift new file mode 100644 index 000000000..795b0679b --- /dev/null +++ b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift @@ -0,0 +1,113 @@ +import XCTest +import JavaScriptKit + +@JSClass struct IdentityModeTestImports { + @JSFunction static func runJsIdentityModeTests() throws(JSException) +} + +final class IdentityModeTests: XCTestCase { + func testRunJsIdentityModeTests() throws { + try IdentityModeTestImports.runJsIdentityModeTests() + } +} + +@JS class IdentityTestSubject { + @JS var value: Int + + @JS init(value: Int) { + self.value = value + } + + @JS var currentValue: Int { value } +} + +nonisolated(unsafe) private var _sharedSubject: IdentityTestSubject? + +@JS func getSharedSubject() -> IdentityTestSubject { + if _sharedSubject == nil { + _sharedSubject = IdentityTestSubject(value: 42) + } + return _sharedSubject! +} + +@JS func resetSharedSubject() { + _sharedSubject = nil +} + +@JS class RetainLeakSubject { + nonisolated(unsafe) static var deinits: Int = 0 + + @JS var tag: Int + + @JS init(tag: Int) { + self.tag = tag + } + + deinit { + Self.deinits += 1 + } +} + +nonisolated(unsafe) private var _retainLeakSubject: RetainLeakSubject? + +@JS func getRetainLeakSubject() -> RetainLeakSubject { + if _retainLeakSubject == nil { + _retainLeakSubject = RetainLeakSubject(tag: 1) + } + return _retainLeakSubject! +} + +@JS func resetRetainLeakSubject() { + _retainLeakSubject = nil +} + +@JS func getRetainLeakDeinits() -> Int { + RetainLeakSubject.deinits +} + +@JS func resetRetainLeakDeinits() { + RetainLeakSubject.deinits = 0 +} + +// MARK: - Array identity tests + +@JS class ArrayIdentityElement { + nonisolated(unsafe) static var deinits: Int = 0 + + @JS var tag: Int + + @JS init(tag: Int) { + self.tag = tag + } + + deinit { + Self.deinits += 1 + } +} + +nonisolated(unsafe) private var _arrayPool: [ArrayIdentityElement] = [] + +@JS func setupArrayPool(_ count: Int) { + _arrayPool = (0.. [ArrayIdentityElement] { + return _arrayPool +} + +@JS func getArrayPoolElement(_ index: Int) -> ArrayIdentityElement? { + guard index >= 0, index < _arrayPool.count else { return nil } + return _arrayPool[index] +} + +@JS func getArrayPoolDeinits() -> Int { + ArrayIdentityElement.deinits +} + +@JS func resetArrayPoolDeinits() { + ArrayIdentityElement.deinits = 0 +} + +@JS func clearArrayPool() { + _arrayPool = [] +} diff --git a/Tests/BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs b/Tests/BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs new file mode 100644 index 000000000..b2ae2187d --- /dev/null +++ b/Tests/BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs @@ -0,0 +1,200 @@ +// @ts-check + +import assert from "node:assert"; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["IdentityModeTestImports"]} + */ +export function getImports(importsContext) { + return { + runJsIdentityModeTests: () => { + const exports = importsContext.getExports(); + if (!exports) { + throw new Error("No exports!?"); + } + runIdentityModeTests(exports); + }, + }; +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runIdentityModeTests(exports) { + testWrapperIdentity(exports); + testCacheInvalidationOnRelease(exports); + testDifferentClassesDontCollide(exports); + testRetainLeakOnCacheHit(exports); + testArrayElementIdentity(exports); + testArrayElementMatchesSingleGetter(exports); + testArrayRetainLeak(exports); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testWrapperIdentity(exports) { + exports.resetSharedSubject(); + const a = exports.getSharedSubject(); + const b = exports.getSharedSubject(); + + assert.strictEqual( + a, + b, + "Same Swift object should return identical JS wrapper", + ); + assert.equal(a.currentValue, 42); + + a.release(); + exports.resetSharedSubject(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testCacheInvalidationOnRelease(exports) { + exports.resetSharedSubject(); + const first = exports.getSharedSubject(); + first.release(); + + exports.resetSharedSubject(); + const second = exports.getSharedSubject(); + + assert.notStrictEqual( + first, + second, + "After release + reset, should get a different wrapper", + ); + assert.equal(second.currentValue, 42); + + second.release(); + exports.resetSharedSubject(); +} + +/** + * Verifies that repeated boundary crossings of the same Swift object don't leak + * retain counts. Each cache hit triggers passRetained on the Swift side. Without + * the balancing deinit(pointer) call on cache hit, each crossing leaks +1 retain + * and the object is never deallocated. + * + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testRetainLeakOnCacheHit(exports) { + exports.resetRetainLeakDeinits(); + exports.resetRetainLeakSubject(); + + const wrappers = []; + for (let i = 0; i < 10; i++) { + wrappers.push(exports.getRetainLeakSubject()); + } + + for (let i = 1; i < wrappers.length; i++) { + assert.strictEqual( + wrappers[0], + wrappers[i], + "All should be the same cached wrapper", + ); + } + + wrappers[0].release(); + exports.resetRetainLeakSubject(); + + assert.strictEqual( + exports.getRetainLeakDeinits(), + 1, + "Object should be deallocated after release + reset. " + + "If deinits == 0, retain leak from unbalanced passRetained on cache hits.", + ); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testArrayElementIdentity(exports) { + exports.setupArrayPool(10); + const arr1 = exports.getArrayPool(); + const arr2 = exports.getArrayPool(); + + assert.equal(arr1.length, 10); + assert.equal(arr2.length, 10); + + for (let i = 0; i < 10; i++) { + assert.strictEqual( + arr1[i], + arr2[i], + `Array element at index ${i} should be === across calls`, + ); + assert.equal(arr1[i].tag, i); + } + + for (const elem of arr1) { + elem.release(); + } + exports.clearArrayPool(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testArrayElementMatchesSingleGetter(exports) { + exports.setupArrayPool(5); + const arr = exports.getArrayPool(); + const single = exports.getArrayPoolElement(2); + + assert.strictEqual( + arr[2], + single, + "Array element and single getter should return the same wrapper", + ); + assert.equal(single.tag, 2); + + for (const elem of arr) { + elem.release(); + } + exports.clearArrayPool(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testArrayRetainLeak(exports) { + exports.resetArrayPoolDeinits(); + exports.setupArrayPool(5); + + for (let round = 0; round < 10; round++) { + exports.getArrayPool(); + } + + const arr = exports.getArrayPool(); + for (const elem of arr) { + elem.release(); + } + + exports.clearArrayPool(); + + assert.strictEqual( + exports.getArrayPoolDeinits(), + 5, + "All 5 pool objects should be deallocated after release + clear. " + + "If deinits < 5, retain leak from unbalanced passRetained in array returns.", + ); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function testDifferentClassesDontCollide(exports) { + const subject1 = new exports.IdentityTestSubject(1); + const subject2 = new exports.IdentityTestSubject(2); + + assert.notStrictEqual( + subject1, + subject2, + "Different instances should not be ===", + ); + assert.equal(subject1.currentValue, 1); + assert.equal(subject2.currentValue, 2); + + subject1.release(); + subject2.release(); +} diff --git a/Tests/BridgeJSIdentityTests/bridge-js.config.json b/Tests/BridgeJSIdentityTests/bridge-js.config.json new file mode 100644 index 000000000..29884404e --- /dev/null +++ b/Tests/BridgeJSIdentityTests/bridge-js.config.json @@ -0,0 +1,3 @@ +{ + "identityMode": "pointer" +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 0af033226..10c73ec2f 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -14,6 +14,7 @@ import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/ import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; import { getImports as getIntegerTypesSupportImports } from './BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs'; import { getImports as getAsyncImportImports, runAsyncWorksTests } from './BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs'; +import { getImports as getIdentityModeTestImports } from './BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { @@ -155,6 +156,7 @@ export async function setupOptions(options, context) { DefaultArgumentImports: getDefaultArgumentImports(importsContext), JSClassSupportImports: getJSClassSupportImports(importsContext), IntegerTypesSupportImports: getIntegerTypesSupportImports(importsContext), + IdentityModeTestImports: getIdentityModeTestImports(importsContext), }; }, addToCoreImports(importObject, importsContext) { diff --git a/Utilities/bridge-js-generate.sh b/Utilities/bridge-js-generate.sh index 22182d24b..77bdd0833 100755 --- a/Utilities/bridge-js-generate.sh +++ b/Utilities/bridge-js-generate.sh @@ -6,5 +6,6 @@ swift build --package-path ./Plugins/BridgeJS --product BridgeJSTool ./Plugins/BridgeJS/.build/debug/BridgeJSTool generate --project ./tsconfig.json --module-name BridgeJSRuntimeTests --target-dir ./Tests/BridgeJSRuntimeTests --output-dir ./Tests/BridgeJSRuntimeTests/Generated ./Plugins/BridgeJS/.build/debug/BridgeJSTool generate --project ./tsconfig.json --module-name BridgeJSGlobalTests --target-dir ./Tests/BridgeJSGlobalTests --output-dir ./Tests/BridgeJSGlobalTests/Generated +./Plugins/BridgeJS/.build/debug/BridgeJSTool generate --project ./tsconfig.json --module-name BridgeJSIdentityTests --target-dir ./Tests/BridgeJSIdentityTests --output-dir ./Tests/BridgeJSIdentityTests/Generated ./Plugins/BridgeJS/.build/debug/BridgeJSTool generate --project ./tsconfig.json --module-name Benchmarks --target-dir ./Benchmarks/Sources --output-dir ./Benchmarks/Sources/Generated ./Plugins/BridgeJS/.build/debug/BridgeJSTool generate --project ./tsconfig.json --module-name PlayBridgeJS --target-dir ./Examples/PlayBridgeJS/Sources/PlayBridgeJS --output-dir ./Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated From 1f8710b18dc235893b4b333b25e78d159ca9e499 Mon Sep 17 00:00:00 2001 From: 0xpablo Date: Fri, 24 Apr 2026 17:09:16 +0200 Subject: [PATCH 049/140] Adopt Foundation Essentials in compat target (#725) --- Sources/JavaScriptFoundationCompat/Data+JSValue.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/JavaScriptFoundationCompat/Data+JSValue.swift b/Sources/JavaScriptFoundationCompat/Data+JSValue.swift index ac8e773b4..6e74ba266 100644 --- a/Sources/JavaScriptFoundationCompat/Data+JSValue.swift +++ b/Sources/JavaScriptFoundationCompat/Data+JSValue.swift @@ -1,4 +1,8 @@ +#if canImport(FoundationEssentials) +import FoundationEssentials +#else import Foundation +#endif import JavaScriptKit /// Data <-> Uint8Array conversion. The conversion is lossless and copies the bytes at most once per conversion From 8d279a03d854c71d51b9121aff07629bc9f112ff Mon Sep 17 00:00:00 2001 From: Matthew Ayers Date: Sun, 26 Apr 2026 05:30:43 -0400 Subject: [PATCH 050/140] Add Utilities/setup-dev.sh for one-command contributor setup (#726) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wraps the manual steps already documented in CONTRIBUTING.md: - Verifies required tools (swiftly, swift, jq, npm, make, curl). - If a .swift-version file is present, installs the pinned toolchain via swiftly. - Resolves and installs a matching Wasm SDK from swift-sdk-index (idempotent — skipped if already installed). - Runs `make bootstrap` to install JS deps. - Prints SWIFT_SDK_ID for use with `make unittest`. The script runs under bash via shebang; the export instructions it prints work unchanged in zsh and bash. The repo does not track .swift-version; contributors who want it ignored locally can add it to .git/info/exclude. The original manual instructions are kept in CONTRIBUTING.md as a fallback. --- CONTRIBUTING.md | 39 +++++++++++--- Utilities/setup-dev.sh | 112 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 8 deletions(-) create mode 100755 Utilities/setup-dev.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d984555e6..8cb96dec9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,14 +12,37 @@ Thank you for considering contributing to JavaScriptKit! We welcome contribution - Relevant error messages or logs ### Setting Up the Development Environment -1. Clone the repository: - ```bash - git clone https://github.com/swiftwasm/JavaScriptKit.git - cd JavaScriptKit - ``` -2. Install **OSS** Swift toolchain via `swiftly` -3. Install Swift SDK for Wasm corresponding to the Swift version: +Clone the repository: + +```bash +git clone https://github.com/swiftwasm/JavaScriptKit.git +cd JavaScriptKit +``` + +#### Quick start (recommended) + +If you already have an **OSS** Swift toolchain installed via [`swiftly`](https://www.swift.org/install/macos/swiftly), run: + +```bash +./Utilities/setup-dev.sh +``` + +The script verifies prerequisites, installs a matching Wasm Swift SDK from +[swift-sdk-index](https://github.com/swiftwasm/swift-sdk-index), runs `make bootstrap`, +and prints the `SWIFT_SDK_ID` to use with `make unittest`. Re-running it is +idempotent. + +If a `.swift-version` file is present in the repo root, the script will install +that toolchain via `swiftly` automatically. Create one to pin your local dev +toolchain to an indexed release (e.g. `echo 6.3.0 > .swift-version`). The repo +does not track `.swift-version`; if you'd like git to ignore it locally, add it +to `.git/info/exclude`. + +#### Manual setup + +1. Install an **OSS** Swift toolchain via `swiftly`. +2. Install the Swift SDK for Wasm corresponding to the Swift version: ```bash ( set -eo pipefail; \ @@ -35,7 +58,7 @@ Thank you for considering contributing to JavaScriptKit! We welcome contribution jq -r '.["swift-sdks"]["wasm32-unknown-wasip1"]["id"]' ) ``` -4. Install dependencies: +3. Install dependencies: ```bash make bootstrap ``` diff --git a/Utilities/setup-dev.sh b/Utilities/setup-dev.sh new file mode 100755 index 000000000..261e5ebf6 --- /dev/null +++ b/Utilities/setup-dev.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# +# Set up a local development environment for JavaScriptKit. +# +# Steps: +# 1. Verify required tools are available (swiftly, swift, jq, npm, make, curl). +# 2. If .swift-version is present, ensure that toolchain is installed via swiftly. +# 3. Resolve a matching Wasm SDK from https://github.com/swiftwasm/swift-sdk-index +# and install it (idempotent — skipped if already installed). +# 4. Run `make bootstrap` to install JS dependencies. +# 5. Print the SWIFT_SDK_ID so it can be exported for `make unittest`. +# +# The script runs under bash via the shebang. The final `export` instructions +# it prints work unchanged in both bash and zsh. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" + +INDEX_BASE="https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1" + +if [[ -t 1 ]]; then + C_BLUE=$'\033[1;34m'; C_YELLOW=$'\033[1;33m'; C_RED=$'\033[1;31m'; C_RESET=$'\033[0m' +else + C_BLUE=''; C_YELLOW=''; C_RED=''; C_RESET='' +fi + +log() { printf '%s==>%s %s\n' "$C_BLUE" "$C_RESET" "$*"; } +warn() { printf '%swarn:%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; } +fail() { printf '%serror:%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; exit 1; } + +require_cmd() { + command -v "$1" >/dev/null 2>&1 || fail "missing required command: $1${2:+ ($2)}" +} + +log "Checking required tools..." +require_cmd curl +require_cmd jq "install via 'brew install jq' or your package manager" +require_cmd npm "install Node.js from https://nodejs.org" +require_cmd make +require_cmd swiftly "install from https://www.swift.org/install/macos/swiftly" +require_cmd swift "install a Swift toolchain via swiftly" +require_cmd swiftc + +# 1. Honor a .swift-version pin if the repo has one. +if [[ -f .swift-version ]]; then + pinned="$(tr -d '[:space:]' < .swift-version)" + if [[ -n "$pinned" ]]; then + log "Repo pins Swift $pinned via .swift-version" + if ! swiftly list 2>/dev/null | grep -qF "$pinned"; then + log "Installing Swift $pinned via swiftly..." + swiftly install "$pinned" + fi + fi +fi + +SWIFT_VERSION_KEY="$(swiftc --version | head -n1)" +log "Active Swift: $SWIFT_VERSION_KEY" + +# 2. Resolve a matching Wasm SDK. +log "Resolving Wasm SDK from swift-sdk-index..." +TAG_BY_VERSION="$(curl -fsSL "$INDEX_BASE/tag-by-version.json")" +TAG="$(jq -r --arg v "$SWIFT_VERSION_KEY" '.[$v] // [] | .[-1] // empty' <<<"$TAG_BY_VERSION")" + +if [[ -z "$TAG" ]]; then + cat >&2 <'. + + - Use an OSS development snapshot from https://www.swift.org/install/ + +See https://github.com/swiftwasm/swift-sdk-index for details. +EOF + exit 1 +fi + +log "Resolved tag: $TAG" +BUILD_JSON="$(curl -fsSL "$INDEX_BASE/builds/$TAG.json")" +SDK_URL="$(jq -r '."swift-sdks"."wasm32-unknown-wasip1".url' <<<"$BUILD_JSON")" +SDK_CHECKSUM="$(jq -r '."swift-sdks"."wasm32-unknown-wasip1".checksum' <<<"$BUILD_JSON")" +SDK_ID="$(jq -r '."swift-sdks"."wasm32-unknown-wasip1".id' <<<"$BUILD_JSON")" + +if swift sdk list 2>/dev/null | grep -qx "$SDK_ID"; then + log "Wasm SDK already installed: $SDK_ID" +else + log "Installing Wasm SDK: $SDK_ID" + swift sdk install "$SDK_URL" --checksum "$SDK_CHECKSUM" +fi + +# 3. JS dependencies. +log "Installing JS dependencies (make bootstrap)..." +make bootstrap + +cat < Date: Wed, 29 Apr 2026 00:52:11 +0200 Subject: [PATCH 051/140] test: Add GC lifecycle test for identity-cached wrappers (#731) --- .../Generated/BridgeJS.swift | 19 +++++++++ .../Generated/JavaScript/BridgeJS.json | 16 ++++++++ .../IdentityModeTests.swift | 40 +++++++++++++++++++ 3 files changed, 75 insertions(+) diff --git a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift index e25ebeb4c..ffab42367 100644 --- a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift @@ -333,6 +333,25 @@ fileprivate func _bjs_ArrayIdentityElement_wrap_extern(_ pointer: UnsafeMutableR return _bjs_ArrayIdentityElement_wrap_extern(pointer) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_gc") +fileprivate func bjs_gc_extern() -> Void +#else +fileprivate func bjs_gc_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_gc() -> Void { + return bjs_gc_extern() +} + +func _$gc() throws(JSException) -> Void { + bjs_gc() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSIdentityTests", name: "bjs_IdentityModeTestImports_runJsIdentityModeTests_static") fileprivate func bjs_IdentityModeTestImports_runJsIdentityModeTests_static_extern() -> Void diff --git a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json index d30ca00f8..fc1504c37 100644 --- a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json @@ -406,7 +406,23 @@ "children" : [ { "functions" : [ + { + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "global", + "name" : "gc", + "parameters" : [ + + ], + "returnType" : { + "void" : { + } + } + } ], "types" : [ { diff --git a/Tests/BridgeJSIdentityTests/IdentityModeTests.swift b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift index 795b0679b..0aa036163 100644 --- a/Tests/BridgeJSIdentityTests/IdentityModeTests.swift +++ b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift @@ -1,6 +1,8 @@ import XCTest import JavaScriptKit +@JSFunction(from: .global) func gc() throws(JSException) -> Void + @JSClass struct IdentityModeTestImports { @JSFunction static func runJsIdentityModeTests() throws(JSException) } @@ -9,6 +11,44 @@ final class IdentityModeTests: XCTestCase { func testRunJsIdentityModeTests() throws { try IdentityModeTestImports.runJsIdentityModeTests() } + + /// Verifies that identity-cached wrappers are properly reclaimed by GC. + /// + /// Creates an identity-mode object, crosses it multiple times (filling the + /// identity cache), drops all references, triggers GC + event loop ticks, + /// and verifies the Swift object is deallocated. This proves that the + /// WeakRef-based identity cache does not prevent garbage collection. + func testIdentityCachedWrapperIsReclaimedByGC() async throws { + RetainLeakSubject.deinits = 0 + + // Create object and cross it multiple times to fill identity cache + _retainLeakSubject = RetainLeakSubject(tag: 99) + weak var weakSubject = _retainLeakSubject + + // Cross to JS 5 times (populates identity cache with WeakRef) + for _ in 0..<5 { + _ = getRetainLeakSubject() + } + + // Drop Swift-side strong reference + _retainLeakSubject = nil + + // JS wrapper should still be alive via the identity cache's WeakRef, + // but WeakRef doesn't prevent GC. Trigger GC + event loop ticks to + // let FinalizationRegistry fire and call deinit. + for _ in 0..<100 { + try gc() + try await Task.sleep(for: .milliseconds(0)) + if weakSubject == nil { + break + } + } + + // The identity-cached wrapper should have been collected, + // FinalizationRegistry should have fired, deinit should have run. + XCTAssertNil(weakSubject, "Identity-cached object should be deallocated after GC") + XCTAssertEqual(RetainLeakSubject.deinits, 1, "Deinit should fire exactly once") + } } @JS class IdentityTestSubject { From 09b3f4eede93735a73a2ed54baa4b7868c1b0127 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Thu, 30 Apr 2026 16:50:17 +1000 Subject: [PATCH 052/140] BridgeJS: Use `@JS` types from other modules in the same package (#730) * BridgeJS: Use `@JS` types from other modules in the same package * BridgeJS: Improve diagnostics with multi-module AOT * BridgeJS: Fix an issue where the skeleton was being treated as a resource * Fix typo * Documentation improvements --- .../Generated/JavaScript/BridgeJS.json | 5 +- Examples/MultiModule/Package.swift | 38 ++ Examples/MultiModule/README.md | 17 + .../MultiModule/Sources/Core/Vector3D.swift | 17 + .../Sources/Core/bridge-js.config.json | 1 + .../Sources/MultiModule/bridge-js.config.json | 1 + .../Sources/MultiModule/main.swift | 6 + Examples/MultiModule/index.html | 12 + Examples/MultiModule/index.js | 10 + .../Generated/JavaScript/BridgeJS.json | 5 +- .../Sources/PlayBridgeJS/main.swift | 7 +- .../BridgeJSBuildPlugin.swift | 64 +++ .../BridgeJSPluginUtilities | 1 + .../BridgeJSCommandPlugin.swift | 85 ++- .../BridgeJSCore/ExternalModuleIndex.swift | 93 ++++ .../BridgeJSCore/SwiftToSkeleton.swift | 182 ++++--- .../BridgeJSCore/TypeDeclResolver.swift | 2 +- .../BridgeJSPluginUtilities/PluginPaths.swift | 74 +++ .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 9 +- .../Sources/BridgeJSTool/BridgeJSTool.swift | 92 +++- .../BridgeJSToolInternal.swift | 3 +- .../Sources/BridgeJSUtilities/Utilities.swift | 8 +- .../BridgeJSCodegenTests.swift | 56 +- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 30 +- .../CrossModuleResolutionTests.swift | 491 ++++++++++++++++++ .../BridgeJSCodegenTests/ArrayTypes.json | 5 +- .../BridgeJSCodegenTests/Async.json | 5 +- .../BridgeJSCodegenTests/AsyncImport.json | 5 +- .../AsyncStaticImport.json | 5 +- .../CrossFileExtension.json | 5 +- .../CrossFileFunctionTypes.ReverseOrder.json | 5 +- .../CrossFileFunctionTypes.json | 5 +- .../CrossFileSkipsEmptySkeletons.json | 5 +- .../CrossFileTypeResolution.ReverseOrder.json | 5 +- .../CrossFileTypeResolution.json | 5 +- .../DefaultParameters.json | 5 +- .../BridgeJSCodegenTests/DictionaryTypes.json | 5 +- .../EnumAssociatedValue.json | 5 +- .../BridgeJSCodegenTests/EnumCase.json | 5 +- .../EnumNamespace.Global.json | 5 +- .../BridgeJSCodegenTests/EnumNamespace.json | 5 +- .../BridgeJSCodegenTests/EnumRawType.json | 5 +- .../FixedWidthIntegers.json | 5 +- .../BridgeJSCodegenTests/GlobalGetter.json | 5 +- .../GlobalThisImports.json | 5 +- .../IdentityModeClass.json | 5 +- .../BridgeJSCodegenTests/ImportArray.json | 5 +- .../ImportedTypeInExportedInterface.json | 5 +- .../InvalidPropertyNames.json | 5 +- .../BridgeJSCodegenTests/JSClass.json | 5 +- .../JSClassStaticFunctions.json | 5 +- .../BridgeJSCodegenTests/JSValue.json | 5 +- .../BridgeJSCodegenTests/MixedGlobal.json | 5 +- .../BridgeJSCodegenTests/MixedPrivate.json | 5 +- .../Namespaces.Global.json | 5 +- .../BridgeJSCodegenTests/Namespaces.json | 5 +- .../BridgeJSCodegenTests/Optionals.json | 5 +- .../PrimitiveParameters.json | 5 +- .../BridgeJSCodegenTests/PrimitiveReturn.json | 5 +- .../BridgeJSCodegenTests/PropertyTypes.json | 5 +- .../BridgeJSCodegenTests/Protocol.json | 5 +- .../ProtocolInClosure.json | 5 +- .../StaticFunctions.Global.json | 5 +- .../BridgeJSCodegenTests/StaticFunctions.json | 5 +- .../StaticProperties.Global.json | 5 +- .../StaticProperties.json | 5 +- .../BridgeJSCodegenTests/StringParameter.json | 5 +- .../BridgeJSCodegenTests/StringReturn.json | 5 +- .../BridgeJSCodegenTests/SwiftClass.json | 5 +- .../BridgeJSCodegenTests/SwiftClosure.json | 5 +- .../SwiftClosureImports.json | 5 +- .../BridgeJSCodegenTests/SwiftStruct.json | 5 +- .../SwiftStructImports.json | 5 +- .../BridgeJSCodegenTests/Throws.json | 5 +- .../BridgeJSCodegenTests/UnsafePointer.json | 5 +- .../VoidParameterVoidReturn.json | 5 +- .../Sources/BridgeJSPluginUtilities | 1 + .../Sources/PackageToJSPlugin.swift | 16 +- .../BridgeJS/BridgeJS-Configuration.md | 2 + .../Articles/BridgeJS/Setting-up-BridgeJS.md | 4 + .../Articles/BridgeJS/Unsupported-Features.md | 20 +- .../Generated/JavaScript/BridgeJS.json | 5 +- .../Generated/JavaScript/BridgeJS.json | 5 +- .../Generated/JavaScript/BridgeJS.json | 5 +- 84 files changed, 1449 insertions(+), 173 deletions(-) create mode 100644 Examples/MultiModule/Package.swift create mode 100644 Examples/MultiModule/README.md create mode 100644 Examples/MultiModule/Sources/Core/Vector3D.swift create mode 100644 Examples/MultiModule/Sources/Core/bridge-js.config.json create mode 100644 Examples/MultiModule/Sources/MultiModule/bridge-js.config.json create mode 100644 Examples/MultiModule/Sources/MultiModule/main.swift create mode 100644 Examples/MultiModule/index.html create mode 100644 Examples/MultiModule/index.js create mode 120000 Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSPluginUtilities create mode 100644 Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift create mode 100644 Plugins/BridgeJS/Sources/BridgeJSPluginUtilities/PluginPaths.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift create mode 120000 Plugins/PackageToJS/Sources/BridgeJSPluginUtilities diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index 0bddddfb6..8e9c1cd6b 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -3415,5 +3415,8 @@ } ] }, - "moduleName" : "Benchmarks" + "moduleName" : "Benchmarks", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Examples/MultiModule/Package.swift b/Examples/MultiModule/Package.swift new file mode 100644 index 000000000..870e2a5e8 --- /dev/null +++ b/Examples/MultiModule/Package.swift @@ -0,0 +1,38 @@ +// swift-tools-version:6.0 + +import PackageDescription + +let package = Package( + name: "MultiModule", + platforms: [ + .macOS(.v14) + ], + dependencies: [.package(name: "JavaScriptKit", path: "../../")], + targets: [ + .target( + name: "Core", + dependencies: [ + "JavaScriptKit" + ], + swiftSettings: [ + .enableExperimentalFeature("Extern") + ], + plugins: [ + .plugin(name: "BridgeJS", package: "JavaScriptKit") + ] + ), + .executableTarget( + name: "MultiModule", + dependencies: [ + "Core", + "JavaScriptKit", + ], + swiftSettings: [ + .enableExperimentalFeature("Extern") + ], + plugins: [ + .plugin(name: "BridgeJS", package: "JavaScriptKit") + ] + ), + ] +) diff --git a/Examples/MultiModule/README.md b/Examples/MultiModule/README.md new file mode 100644 index 000000000..741394d6f --- /dev/null +++ b/Examples/MultiModule/README.md @@ -0,0 +1,17 @@ +# MultiModule Example + +This example demonstrates using `@JS` types defined in one module (`Core`) from another module (`App`) within the same Swift package. + +## Building and Running + +1. Build the project: + ```sh + swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn + ``` + +2. Serve the files: + ```sh + npx serve + ``` + +Then open your browser to `http://localhost:3000`. diff --git a/Examples/MultiModule/Sources/Core/Vector3D.swift b/Examples/MultiModule/Sources/Core/Vector3D.swift new file mode 100644 index 000000000..988892bcc --- /dev/null +++ b/Examples/MultiModule/Sources/Core/Vector3D.swift @@ -0,0 +1,17 @@ +import JavaScriptKit + +@JS public struct Vector3D { + public let x: Double + public let y: Double + public let z: Double + + @JS public init(x: Double, y: Double, z: Double) { + self.x = x + self.y = y + self.z = z + } + + @JS public func magnitude() -> Double { + (x * x + y * y + z * z).squareRoot() + } +} diff --git a/Examples/MultiModule/Sources/Core/bridge-js.config.json b/Examples/MultiModule/Sources/Core/bridge-js.config.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/Examples/MultiModule/Sources/Core/bridge-js.config.json @@ -0,0 +1 @@ +{} diff --git a/Examples/MultiModule/Sources/MultiModule/bridge-js.config.json b/Examples/MultiModule/Sources/MultiModule/bridge-js.config.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/Examples/MultiModule/Sources/MultiModule/bridge-js.config.json @@ -0,0 +1 @@ +{} diff --git a/Examples/MultiModule/Sources/MultiModule/main.swift b/Examples/MultiModule/Sources/MultiModule/main.swift new file mode 100644 index 000000000..dd238c00d --- /dev/null +++ b/Examples/MultiModule/Sources/MultiModule/main.swift @@ -0,0 +1,6 @@ +import Core +import JavaScriptKit + +@JS public func currentVelocity() -> Vector3D { + Vector3D(x: 0.1, y: 0.2, z: 0.3) +} diff --git a/Examples/MultiModule/index.html b/Examples/MultiModule/index.html new file mode 100644 index 000000000..d9066820f --- /dev/null +++ b/Examples/MultiModule/index.html @@ -0,0 +1,12 @@ + + + + + MultiModule Example + + + + + + + diff --git a/Examples/MultiModule/index.js b/Examples/MultiModule/index.js new file mode 100644 index 000000000..83e79f16d --- /dev/null +++ b/Examples/MultiModule/index.js @@ -0,0 +1,10 @@ +import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; +const { exports } = await init({}); + +const velocity = exports.currentVelocity(); + +const output = document.createElement("pre"); +output.innerText = + `currentVelocity() = (${velocity.x}, ${velocity.y}, ${velocity.z})\n` + + `magnitude = ${velocity.magnitude()}`; +document.body.appendChild(output); diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 1a21916ee..89ce6ae3a 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -300,5 +300,8 @@ } ] }, - "moduleName" : "PlayBridgeJS" + "moduleName" : "PlayBridgeJS", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift index ec9eda774..a30eb3b06 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift @@ -45,7 +45,12 @@ import class Foundation.JSONDecoder func _update(swiftSource: String, dtsSource: String) throws -> PlayBridgeJSOutput { let moduleName = "Playground" - let swiftToSkeleton = SwiftToSkeleton(progress: .silent, moduleName: moduleName, exposeToGlobal: false) + let swiftToSkeleton = SwiftToSkeleton( + progress: .silent, + moduleName: moduleName, + exposeToGlobal: false, + externalModuleIndex: .empty + ) swiftToSkeleton.addSourceFile(Parser.parse(source: swiftSource), inputFilePath: "Playground.swift") let ts2swift = try createTS2Swift() diff --git a/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift index 3cb6dc860..b78f5f9a6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift @@ -63,6 +63,19 @@ struct BridgeJSBuildPlugin: BuildToolPlugin { ]) } + for skeleton in dependencySkeletons(context: context, target: target) { + arguments.append(contentsOf: [ + "--dependency-skeleton", + "\(skeleton.moduleName)=\(skeleton.skeletonURL.path)", + ]) + // We have to use the Swift file, not the skeleton, as the input file, + // since we can’t make the skeleton file an output file without it being + // treated as a resource by the build system (and thus included in the + // resource bundle). We need to use something as the inputFile to maintain + // correct ordering. + inputFiles.append(skeleton.bridgeJSSwiftURL) + } + let allSwiftFiles = inputSwiftFiles + pluginGeneratedSwiftFiles arguments.append(contentsOf: allSwiftFiles.map(\.path)) @@ -74,5 +87,56 @@ struct BridgeJSBuildPlugin: BuildToolPlugin { outputFiles: [outputSwiftPath] ) } + + private struct DependencySkeleton { + let moduleName: String + let skeletonURL: URL + let bridgeJSSwiftURL: URL + } + + /// We only read skeletons from dependencies with a `bridge-js.config.json` file. + /// For the build system to correctly order the plugins, we need to set the skeleton + /// files as input. However, I don’t think we have enough information here to determine + /// whether the plugin which generates this is applied to the dependency, so we use + /// the presence of `bridge-js.config.json` instead. + private func dependencySkeletons( + context: PluginContext, + target: SwiftSourceModuleTarget + ) -> [DependencySkeleton] { + let localTargets: [SwiftSourceModuleTarget] = target.recursiveTargetDependencies + .compactMap { dependency in + guard + let swiftTarget = dependency as? SwiftSourceModuleTarget, + context.package.targets.contains(where: { $0.id == swiftTarget.id }), + FileManager.default.fileExists(atPath: pathToConfigFile(target: swiftTarget).path) + else { + return nil + } + return swiftTarget + } + + var skeletons: [DependencySkeleton] = [] + var seenTargetNames = Set() + for swiftTarget in localTargets where seenTargetNames.insert(swiftTarget.name).inserted { + let skeletonURL = BridgeJSPluginPaths.skeletonURL( + targetName: swiftTarget.name, + packageID: context.package.id, + buildPluginWorkDirectoryURL: context.pluginWorkDirectoryURL + ) + let bridgeJSSwiftURL = BridgeJSPluginPaths.bridgeJSSwiftURL( + targetName: swiftTarget.name, + packageID: context.package.id, + buildPluginWorkDirectoryURL: context.pluginWorkDirectoryURL + ) + skeletons.append( + DependencySkeleton( + moduleName: swiftTarget.name, + skeletonURL: skeletonURL, + bridgeJSSwiftURL: bridgeJSSwiftURL + ) + ) + } + return skeletons + } } #endif diff --git a/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSPluginUtilities b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSPluginUtilities new file mode 120000 index 000000000..2daaa446e --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSPluginUtilities @@ -0,0 +1 @@ +../BridgeJSPluginUtilities \ No newline at end of file diff --git a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift index 23fbae567..24b96f53d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift @@ -74,28 +74,62 @@ struct BridgeJSCommandPlugin: CommandPlugin { } extension BridgeJSCommandPlugin.Context { - func runOnTargets( - remainingArguments: [String], - where predicate: (SwiftSourceModuleTarget) -> Bool - ) throws { + private func collectBridgeJSTargets() -> [String: SwiftSourceModuleTarget] { + var bridgeJSTargets: [String: SwiftSourceModuleTarget] = [:] for target in context.package.targets { - guard let target = target as? SwiftSourceModuleTarget else { + guard + let swiftTarget = target as? SwiftSourceModuleTarget, + FileManager.default.fileExists( + atPath: swiftTarget.directoryURL.appending(path: "bridge-js.config.json").path + ) + else { continue } - let configFilePath = target.directoryURL.appending(path: "bridge-js.config.json") - if !FileManager.default.fileExists(atPath: configFilePath.path) { - printVerbose("No bridge-js.config.json found for \(target.name), skipping...") - continue + bridgeJSTargets[swiftTarget.name] = swiftTarget + } + return bridgeJSTargets + } + + private func targetsInDependencyOrder( + _ bridgeJSTargets: [String: SwiftSourceModuleTarget] + ) -> [SwiftSourceModuleTarget] { + var visitedTargetNames = Set() + var orderedTargets: [SwiftSourceModuleTarget] = [] + func visit(_ target: SwiftSourceModuleTarget) { + if !visitedTargetNames.insert(target.name).inserted { + return } - guard predicate(target) else { - continue + for dependency in target.recursiveTargetDependencies { + if let dependencyTarget = bridgeJSTargets[dependency.name] { + visit(dependencyTarget) + } } - try runSingleTarget(target: target, remainingArguments: remainingArguments) + orderedTargets.append(target) + } + for target in bridgeJSTargets.values.sorted(by: { $0.name < $1.name }) { + visit(target) + } + return orderedTargets + } + + func runOnTargets( + remainingArguments: [String], + where predicate: (SwiftSourceModuleTarget) -> Bool + ) throws { + let allBridgeJSTargets = collectBridgeJSTargets() + let requestedTargets = allBridgeJSTargets.filter { predicate($1) } + for target in targetsInDependencyOrder(requestedTargets) { + try runSingleTarget( + target: target, + bridgeJSTargets: allBridgeJSTargets, + remainingArguments: remainingArguments + ) } } private func runSingleTarget( target: SwiftSourceModuleTarget, + bridgeJSTargets: [String: SwiftSourceModuleTarget], remainingArguments: [String] ) throws { printStderr("Generating bridge code for \(target.name)...") @@ -126,6 +160,25 @@ extension BridgeJSCommandPlugin.Context { ]) } + for dependency in target.recursiveTargetDependencies { + guard let dependencyTarget = bridgeJSTargets[dependency.name] else { continue } + let dependencySkeletonPath = dependencyTarget.directoryURL + .appending(path: "Generated/JavaScript/BridgeJS.json") + guard FileManager.default.fileExists(atPath: dependencySkeletonPath.path) else { + throw BridgeJSCommandPluginError( + """ + Dependency '\(dependencyTarget.name)' is configured for BridgeJS, but its AOT skeleton has not been generated yet. \ + Run `swift package bridge-js --target \(dependencyTarget.name)` to generate it first, \ + or run without `--target` to process in dependency order. + """ + ) + } + generateArguments.append(contentsOf: [ + "--dependency-skeleton", + "\(dependencyTarget.name)=\(dependencySkeletonPath.path)", + ]) + } + generateArguments.append( contentsOf: target.sourceFiles.filter { !$0.url.path.hasPrefix(generatedDirectory.path + "/") @@ -162,6 +215,14 @@ private func printStderr(_ message: String) { fputs(message + "\n", stderr) } +struct BridgeJSCommandPluginError: Error, CustomStringConvertible { + let description: String + + init(_ message: String) { + self.description = message + } +} + extension SwiftSourceModuleTarget { func hasDependency(named name: String) -> Bool { return dependencies.contains(where: { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift new file mode 100644 index 000000000..91fd4388a --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift @@ -0,0 +1,93 @@ +#if canImport(BridgeJSSkeleton) +import BridgeJSSkeleton +#endif + +/// Index of `@JS` types from dependencies. +public struct ExternalModuleIndex { + public struct ExternalType: Equatable { + public let moduleName: String + public let bridgeType: BridgeType + } + + public enum LookupResult: Equatable { + case unique(ExternalType) + case ambiguous(candidates: [ExternalType]) + } + + public static var empty: ExternalModuleIndex { + ExternalModuleIndex(dependencies: []) + } + + private let byModuleAndPath: [String: [String: ExternalType]] + private let byPath: [String: [ExternalType]] + + public var moduleNames: Set { Set(byModuleAndPath.keys) } + + public init(dependencies: [(moduleName: String, skeleton: BridgeJSSkeleton)]) { + var entriesByModule: [String: [String: ExternalType]] = [:] + var entriesByDotPath: [String: [ExternalType]] = [:] + + for (moduleName, skeleton) in dependencies { + guard let exported = skeleton.exported else { continue } + var moduleEntries = entriesByModule[moduleName] ?? [:] + + func register(dotPath: String, bridgeType: BridgeType) { + let externalType = ExternalType(moduleName: moduleName, bridgeType: bridgeType) + if moduleEntries[dotPath] == nil { + moduleEntries[dotPath] = externalType + entriesByDotPath[dotPath, default: []].append(externalType) + } + } + + for klass in exported.classes { + register(dotPath: klass.swiftCallName, bridgeType: .swiftHeapObject(klass.swiftCallName)) + } + for structDef in exported.structs { + register(dotPath: structDef.swiftCallName, bridgeType: .swiftStruct(structDef.swiftCallName)) + } + for enumDef in exported.enums { + let bridgeType: BridgeType + switch enumDef.enumType { + case .simple: + bridgeType = .caseEnum(enumDef.swiftCallName) + case .rawValue: + guard let rawType = enumDef.rawType else { continue } + bridgeType = .rawValueEnum(enumDef.swiftCallName, rawType) + case .associatedValue: + bridgeType = .associatedValueEnum(enumDef.swiftCallName) + case .namespace: + bridgeType = .namespaceEnum(enumDef.swiftCallName) + } + register(dotPath: enumDef.swiftCallName, bridgeType: bridgeType) + } + for proto in exported.protocols { + register(dotPath: proto.name, bridgeType: .swiftProtocol(proto.name)) + } + + entriesByModule[moduleName] = moduleEntries + } + + self.byModuleAndPath = entriesByModule + self.byPath = entriesByDotPath + } + + public var isEmpty: Bool { byModuleAndPath.isEmpty } + + public func isKnownModule(_ name: String) -> Bool { + byModuleAndPath[name] != nil + } + + public func lookup(dotPath: String) -> LookupResult? { + guard let matches = byPath[dotPath], !matches.isEmpty else { return nil } + if matches.count == 1 { + return .unique(matches[0]) + } + return .ambiguous(candidates: matches) + } + + public func lookup(dotPath: String, module moduleName: String) -> LookupResult? { + guard let moduleEntries = byModuleAndPath[moduleName] else { return nil } + guard let externalType = moduleEntries[dotPath] else { return nil } + return .unique(externalType) + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 3d8f417e3..42ba2fbaa 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -18,15 +18,25 @@ public final class SwiftToSkeleton { public let exposeToGlobal: Bool public let identityMode: String? - private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = [] let typeDeclResolver: TypeDeclResolver + let externalModuleIndex: ExternalModuleIndex - public init(progress: ProgressReporting, moduleName: String, exposeToGlobal: Bool, identityMode: String? = nil) { + private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = [] + private var usedExternalModules = Set() + + public init( + progress: ProgressReporting, + moduleName: String, + exposeToGlobal: Bool, + externalModuleIndex: ExternalModuleIndex, + identityMode: String? = nil + ) { self.progress = progress self.moduleName = moduleName self.exposeToGlobal = exposeToGlobal self.identityMode = identityMode self.typeDeclResolver = TypeDeclResolver() + self.externalModuleIndex = externalModuleIndex // Index known types provided by JavaScriptKit self.typeDeclResolver.addSourceFile( @@ -110,7 +120,12 @@ public final class SwiftToSkeleton { }() let exportedSkeleton: ExportedSkeleton? = exported.isEmpty ? nil : exported - return BridgeJSSkeleton(moduleName: moduleName, exported: exportedSkeleton, imported: importedSkeleton) + return BridgeJSSkeleton( + moduleName: moduleName, + exported: exportedSkeleton, + imported: importedSkeleton, + usedExternalModules: usedExternalModules.sorted() + ) } func lookupType(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { @@ -303,79 +318,130 @@ public final class SwiftToSkeleton { return primitiveType } - guard let typeDecl = typeDeclResolver.resolve(type) else { - errors.append( - DiagnosticError( - node: type, - message: "Unsupported type '\(type.trimmedDescription)'.", - hint: "Only primitive types and types defined in the same module are allowed" - ) - ) - return nil - } - - if typeDecl.is(ProtocolDeclSyntax.self) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text) - return .swiftProtocol(swiftCallName) - } + if let typeDecl = typeDeclResolver.resolve(type) { + if typeDecl.is(ProtocolDeclSyntax.self) { + let swiftCallName = SwiftToSkeleton.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 rawTypeString = enumDecl.inheritanceClause?.inheritedTypes.first { inheritedType in - let typeName = inheritedType.type.trimmedDescription - return ExportSwiftConstants.supportedRawTypes.contains(typeName) - }?.type.trimmedDescription + if let enumDecl = typeDecl.as(EnumDeclSyntax.self) { + let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text) + let rawTypeString = enumDecl.inheritanceClause?.inheritedTypes.first { inheritedType in + let typeName = inheritedType.type.trimmedDescription + return ExportSwiftConstants.supportedRawTypes.contains(typeName) + }?.type.trimmedDescription - if let rawType = SwiftEnumRawType(rawTypeString) { - return .rawValueEnum(swiftCallName, rawType) - } else { - let hasAnyCases = enumDecl.memberBlock.members.contains { member in - member.decl.is(EnumCaseDeclSyntax.self) - } - if !hasAnyCases { - return .namespaceEnum(swiftCallName) - } - let hasAssociatedValues = - enumDecl.memberBlock.members.contains { member in - guard let caseDecl = member.decl.as(EnumCaseDeclSyntax.self) else { return false } - return caseDecl.elements.contains { element in - if let params = element.parameterClause?.parameters { - return !params.isEmpty + if let rawType = SwiftEnumRawType(rawTypeString) { + return .rawValueEnum(swiftCallName, rawType) + } else { + let hasAnyCases = enumDecl.memberBlock.members.contains { member in + member.decl.is(EnumCaseDeclSyntax.self) + } + if !hasAnyCases { + return .namespaceEnum(swiftCallName) + } + let hasAssociatedValues = + enumDecl.memberBlock.members.contains { member in + guard let caseDecl = member.decl.as(EnumCaseDeclSyntax.self) else { return false } + return caseDecl.elements.contains { element in + if let params = element.parameterClause?.parameters { + return !params.isEmpty + } + return false } - return false } + if hasAssociatedValues { + return .associatedValueEnum(swiftCallName) + } else { + return .caseEnum(swiftCallName) } - if hasAssociatedValues { - return .associatedValueEnum(swiftCallName) - } else { - return .caseEnum(swiftCallName) } } - } - if let structDecl = typeDecl.as(StructDeclSyntax.self) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: structDecl, itemName: structDecl.name.text) - if structDecl.attributes.hasAttribute(name: "JSClass") { + if let structDecl = typeDecl.as(StructDeclSyntax.self) { + let swiftCallName = SwiftToSkeleton.computeSwiftCallName( + for: structDecl, + itemName: structDecl.name.text + ) + if structDecl.attributes.hasAttribute(name: "JSClass") { + return .jsObject(swiftCallName) + } + return .swiftStruct(swiftCallName) + } + + guard typeDecl.is(ClassDeclSyntax.self) || typeDecl.is(ActorDeclSyntax.self) else { + return nil + } + let swiftCallName = SwiftToSkeleton.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. + if let classDecl = typeDecl.as(ClassDeclSyntax.self), classDecl.attributes.hasAttribute(name: "JSClass") { + return .jsObject(swiftCallName) + } + if let actorDecl = typeDecl.as(ActorDeclSyntax.self), actorDecl.attributes.hasAttribute(name: "JSClass") { return .jsObject(swiftCallName) } - return .swiftStruct(swiftCallName) + + return .swiftHeapObject(swiftCallName) + } + + if let externalType = resolveExternal(for: type, errors: &errors) { + return externalType } - guard typeDecl.is(ClassDeclSyntax.self) || typeDecl.is(ActorDeclSyntax.self) else { + errors.append( + DiagnosticError( + node: type, + message: "Unsupported type '\(type.trimmedDescription)'.", + hint: + "Only primitive types, types defined in the same module, and " + + "`@JS` types from dependency targets that apply the BridgeJS plugin are allowed" + ) + ) + return nil + } + + private func resolveExternal(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { + guard + !externalModuleIndex.isEmpty, + var components = typeDeclResolver.qualifiedComponents(from: type) + else { return nil } - let swiftCallName = SwiftToSkeleton.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. - if let classDecl = typeDecl.as(ClassDeclSyntax.self), classDecl.attributes.hasAttribute(name: "JSClass") { - return .jsObject(swiftCallName) + var scopedModule: String? = nil + if components.count >= 2, externalModuleIndex.isKnownModule(components[0]) { + scopedModule = components[0] + components.removeFirst() } - if let actorDecl = typeDecl.as(ActorDeclSyntax.self), actorDecl.attributes.hasAttribute(name: "JSClass") { - return .jsObject(swiftCallName) + + let dotPath = components.joined(separator: ".") + let lookupResult: ExternalModuleIndex.LookupResult? + if let moduleName = scopedModule { + lookupResult = externalModuleIndex.lookup(dotPath: dotPath, module: moduleName) + } else { + lookupResult = externalModuleIndex.lookup(dotPath: dotPath) } - return .swiftHeapObject(swiftCallName) + guard let lookupResult else { return nil } + switch lookupResult { + case .unique(let externalType): + usedExternalModules.insert(externalType.moduleName) + return externalType.bridgeType + case .ambiguous(let candidates): + let moduleNames = candidates.map(\.moduleName).sorted().joined(separator: ", ") + errors.append( + DiagnosticError( + node: type, + message: "ambiguous use of '\(type.trimmedDescription)'", + hint: + "'\(dotPath)' is exported by multiple dependency modules: \(moduleNames). " + + "Qualify with a module name (e.g. '.\(dotPath)') to disambiguate." + ) + ) + return nil + } } fileprivate static func parseUnsafePointerType(_ type: TypeSyntax) -> UnsafePointerType? { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift index 975c0c9dc..ec04421aa 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift @@ -161,7 +161,7 @@ class TypeDeclResolver { return nil } - private func qualifiedComponents(from type: TypeSyntax) -> QualifiedName? { + func qualifiedComponents(from type: TypeSyntax) -> QualifiedName? { if let m = type.as(MemberTypeSyntax.self) { guard let base = qualifiedComponents(from: TypeSyntax(m.baseType)) else { return nil } return base + [m.name.text] diff --git a/Plugins/BridgeJS/Sources/BridgeJSPluginUtilities/PluginPaths.swift b/Plugins/BridgeJS/Sources/BridgeJSPluginUtilities/PluginPaths.swift new file mode 100644 index 000000000..f95d1adaa --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSPluginUtilities/PluginPaths.swift @@ -0,0 +1,74 @@ +#if canImport(PackagePlugin) +import struct Foundation.URL + +enum BridgeJSPluginPaths { + static func skeletonURL( + targetName: String, + packageID: String, + buildPluginWorkDirectoryURL workDirectoryURL: URL + ) -> URL { + let pluginsOutputsRootURL = + workDirectoryURL + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + return bridgeJSDirectoryURL( + targetName: targetName, + packageID: packageID, + pluginsOutputsRootURL: pluginsOutputsRootURL + ) + .appending(path: "JavaScript/BridgeJS.json") + } + + static func skeletonURL( + targetName: String, + packageID: String, + commandPluginWorkDirectoryURL workDirectoryURL: URL + ) -> URL { + // workDirectoryURL: ".build/plugins/PackageToJS/outputs/" + // .build/plugins/outputs/[package]/[target]/destination/BridgeJS/JavaScript/BridgeJS.json + let pluginsOutputsRootURL = + workDirectoryURL + .deletingLastPathComponent() + .deletingLastPathComponent() + .appending(path: "outputs") + return bridgeJSDirectoryURL( + targetName: targetName, + packageID: packageID, + pluginsOutputsRootURL: pluginsOutputsRootURL + ) + .appending(path: "JavaScript/BridgeJS.json") + } + + static func bridgeJSSwiftURL( + targetName: String, + packageID: String, + buildPluginWorkDirectoryURL workDirectoryURL: URL + ) -> URL { + let pluginsOutputsRootURL = + workDirectoryURL + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + return bridgeJSDirectoryURL( + targetName: targetName, + packageID: packageID, + pluginsOutputsRootURL: pluginsOutputsRootURL + ) + .appending(path: "BridgeJS.swift") + } + + private static func bridgeJSDirectoryURL( + targetName: String, + packageID: String, + pluginsOutputsRootURL: URL + ) -> URL { + pluginsOutputsRootURL + .appending(path: packageID) + .appending(path: targetName) + .appending(path: "destination/BridgeJS") + } +} +#endif diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 03e6d676a..baf6debd9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1239,11 +1239,18 @@ public struct BridgeJSSkeleton: Codable { public let moduleName: String public let exported: ExportedSkeleton? public let imported: ImportedModuleSkeleton? + public let usedExternalModules: [String] - public init(moduleName: String, exported: ExportedSkeleton? = nil, imported: ImportedModuleSkeleton? = nil) { + public init( + moduleName: String, + exported: ExportedSkeleton? = nil, + imported: ImportedModuleSkeleton? = nil, + usedExternalModules: [String] = [] + ) { self.moduleName = moduleName self.exported = exported self.imported = imported + self.usedExternalModules = usedExternalModules } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index 3e3f27ea1..005af04a8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -112,10 +112,18 @@ import BridgeJSUtilities help: "The path to the TypeScript project configuration file (required for .d.ts files)", required: false ), + "dependency-skeleton": OptionRule( + help: "Path to a dependency module's BridgeJS.json, as '='. Repeatable.", + required: false, + repeatable: true + ), ] ) - let (positionalArguments, _, doubleDashOptions) = try parser.parse( - arguments: Array(arguments.dropFirst()) + let parsedArguments = try parser.parse(arguments: Array(arguments.dropFirst())) + let positionalArguments = parsedArguments.positionalArguments + let doubleDashOptions = parsedArguments.doubleDashOptions + let dependencySkeletons = try loadDependencySkeletons( + parsedArguments.repeatedDoubleDashOptions["dependency-skeleton", default: []] ) let progress = ProgressReporting(verbose: doubleDashOptions["verbose"] == "true") let moduleName = doubleDashOptions["module-name"]! @@ -162,10 +170,12 @@ import BridgeJSUtilities inputFiles.append(macrosPath) } } + let externalModuleIndex = ExternalModuleIndex(dependencies: dependencySkeletons) let swiftToSkeleton = SwiftToSkeleton( progress: progress, moduleName: moduleName, exposeToGlobal: config.exposeToGlobal, + externalModuleIndex: externalModuleIndex, identityMode: config.identityMode ) for inputFile in inputFiles.sorted() { @@ -224,7 +234,10 @@ import BridgeJSUtilities // Combine and write unified Swift output let outputSwiftURL = outputDirectory.appending(path: "BridgeJS.swift") let combinedSwift = [closureSupport, exportResult, importResult].compactMap { $0 } - let outputSwift = combineGeneratedSwift(combinedSwift) + let outputSwift = combineGeneratedSwift( + combinedSwift, + importingExternalModules: skeleton.usedExternalModules + ) let shouldWrite = doubleDashOptions["always-write"] == "true" || !outputSwift.isEmpty if shouldWrite { try withSpan("Writing output Swift") { @@ -237,7 +250,14 @@ import BridgeJSUtilities } } - // Write unified skeleton + // Write unified skeleton. + // Note that for the build system to sequence the BridgeJSBuildPlugin correctly, + // the skeleton-to-Swift-output mapping must be injective, i.e. any change to + // the skeleton must produce a change in the Swift output. This is because we + // can’t use the BridgeJS.json file as an outputFile, since it would then be + // treated as a resource and thus included in the generated bundle. The + // invariant currently holds, but if this ever changes the BridgeJS.swift file + // could include a hash of the skeleton to maintain it. let outputSkeletonURL = outputDirectory.appending(path: "JavaScript/BridgeJS.json") try withSpan("Writing output skeleton") { try FileManager.default.createDirectory( @@ -302,14 +322,45 @@ private func writeIfChanged(_ data: Data, to url: URL) throws { try data.write(to: url) } -private func combineGeneratedSwift(_ pieces: [String]) -> String { +private func loadDependencySkeletons( + _ rawArguments: [String] +) throws -> [(moduleName: String, skeleton: BridgeJSSkeleton)] { + var loadedSkeletons: [(moduleName: String, skeleton: BridgeJSSkeleton)] = [] + let decoder = JSONDecoder() + for rawArgument in rawArguments { + guard let equalIndex = rawArgument.firstIndex(of: "="), equalIndex != rawArgument.startIndex else { + throw BridgeJSToolError( + "--dependency-skeleton expects '='; got invalid value '\(rawArgument)'" + ) + } + let moduleName = String(rawArgument[.. String { let trimmedPieces = pieces .map { $0.trimmingCharacters(in: .newlines) } .filter { !$0.isEmpty } guard !trimmedPieces.isEmpty else { return "" } - return ([BridgeJSGeneratedFile.swiftPreamble] + trimmedPieces).joined(separator: "\n\n") + let imports = BridgeJSGeneratedFile.swiftImports(["JavaScriptKit"] + externalModules) + return ([BridgeJSGeneratedFile.swiftHeader, imports] + trimmedPieces).joined(separator: "\n\n") } private func recursivelyCollectSwiftFiles(from directory: URL) -> [URL] { @@ -365,6 +416,7 @@ extension Profiling { struct OptionRule { var help: String var required: Bool = false + var repeatable: Bool = false } struct ArgumentParser { @@ -377,11 +429,12 @@ struct ArgumentParser { self.doubleDashOptions = doubleDashOptions } - typealias ParsedArguments = ( - positionalArguments: [String], - singleDashOptions: [String: String], - doubleDashOptions: [String: String] - ) + struct ParsedArguments { + var positionalArguments: [String] + var singleDashOptions: [String: String] + var doubleDashOptions: [String: String] + var repeatedDoubleDashOptions: [String: [String]] + } func help() -> String { var help = "Usage: \(CommandLine.arguments.first ?? "bridge-js-tool") [options] \n\n" @@ -404,6 +457,7 @@ struct ArgumentParser { var positionalArguments: [String] = [] var singleDashOptions: [String: String] = [:] var doubleDashOptions: [String: String] = [:] + var repeatedDoubleDashOptions: [String: [String]] = [:] var arguments = arguments.makeIterator() @@ -412,7 +466,12 @@ struct ArgumentParser { if arg.starts(with: "--") { let key = String(arg.dropFirst(2)) let value = arguments.next() - doubleDashOptions[key] = value + if self.doubleDashOptions[key]?.repeatable ?? false { + guard let value else { continue } + repeatedDoubleDashOptions[key, default: []].append(value) + } else { + doubleDashOptions[key] = value + } } else { let key = String(arg.dropFirst(1)) let value = arguments.next() @@ -424,11 +483,16 @@ struct ArgumentParser { } for (key, rule) in self.doubleDashOptions { - if rule.required, doubleDashOptions[key] == nil { + if rule.required, doubleDashOptions[key] == nil, repeatedDoubleDashOptions[key] == nil { throw BridgeJSToolError("Option --\(key) is required") } } - return (positionalArguments, singleDashOptions, doubleDashOptions) + return ParsedArguments( + positionalArguments: positionalArguments, + singleDashOptions: singleDashOptions, + doubleDashOptions: doubleDashOptions, + repeatedDoubleDashOptions: repeatedDoubleDashOptions + ) } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift index 8a6a6b7b4..f4de24093 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift @@ -48,7 +48,8 @@ import ArgumentParser let swiftToSkeleton = SwiftToSkeleton( progress: ProgressReporting(verbose: false), moduleName: "InternalModule", - exposeToGlobal: false + exposeToGlobal: false, + externalModuleIndex: .empty ) for inputFile in inputFiles.sorted() { let content = try String(decoding: readData(from: inputFile), as: UTF8.self) diff --git a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift index 68c07f225..8a4171718 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift @@ -13,7 +13,7 @@ public enum BridgeJSGeneratedFile { content.starts(with: skipLine + "\n") } - public static var swiftPreamble: String { + public static var swiftHeader: String { // The generated Swift file itself should not be processed by BridgeJS again. """ \(skipLine) @@ -22,10 +22,12 @@ public enum BridgeJSGeneratedFile { // // To update this file, just rebuild your project or run // `swift package bridge-js`. - - @_spi(BridgeJS) import JavaScriptKit """ } + + public static func swiftImports(_ moduleNames: [String]) -> String { + moduleNames.map { "@_spi(BridgeJS) import \($0)" }.joined(separator: "\n") + } } /// A printer for code fragments. diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index dd0ce5d03..8b8e8b8a2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -77,7 +77,12 @@ 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 swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) swiftAPI.addSourceFile(sourceFile, inputFilePath: input) let skeleton = try swiftAPI.finalize() try snapshotCodegen(skeleton: skeleton, name: name) @@ -93,7 +98,12 @@ 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 swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: true) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: true, + externalModuleIndex: .empty + ) swiftAPI.addSourceFile(sourceFile, inputFilePath: input) let skeleton = try swiftAPI.finalize() try snapshotCodegen(skeleton: skeleton, name: name + ".Global") @@ -101,7 +111,12 @@ import Testing @Test func codegenCrossFileTypeResolution() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let classBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassB.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: classBURL, encoding: .utf8)), @@ -118,7 +133,12 @@ import Testing @Test func codegenCrossFileTypeResolutionReverseOrder() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let classAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassA.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: classAURL, encoding: .utf8)), @@ -135,7 +155,12 @@ import Testing @Test func codegenCrossFileFunctionTypes() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let functionBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionB.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: functionBURL, encoding: .utf8)), @@ -152,7 +177,12 @@ import Testing @Test func codegenCrossFileFunctionTypesReverseOrder() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let functionAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionA.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: functionAURL, encoding: .utf8)), @@ -169,7 +199,12 @@ import Testing @Test func codegenCrossFileExtension() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let classURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionClass.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: classURL, encoding: .utf8)), @@ -186,7 +221,12 @@ import Testing @Test func codegenSkipsEmptySkeletons() throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) let importedURL = Self.multifileInputsDirectory.appendingPathComponent("ImportedFunctions.swift") swiftAPI.addSourceFile( Parser.parse(source: try String(contentsOf: importedURL, encoding: .utf8)), diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 64c9ae535..2f3f46fdb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -49,7 +49,12 @@ import Testing 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) + 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) @@ -69,7 +74,12 @@ import Testing func snapshotExportWithGlobal(inputFile: String) throws { let url = Self.inputsDirectory.appendingPathComponent(inputFile) let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: true) + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: true, + externalModuleIndex: .empty + ) swiftAPI.addSourceFile(sourceFile, inputFilePath: inputFile) let name = url.deletingPathExtension().lastPathComponent let outputSkeleton = try swiftAPI.finalize() @@ -86,13 +96,23 @@ import Testing func snapshotMixedModuleExposure() throws { let globalURL = Self.inputsDirectory.appendingPathComponent("MixedGlobal.swift") let globalSourceFile = Parser.parse(source: try String(contentsOf: globalURL, encoding: .utf8)) - let globalAPI = SwiftToSkeleton(progress: .silent, moduleName: "GlobalModule", exposeToGlobal: true) + let globalAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "GlobalModule", + exposeToGlobal: true, + externalModuleIndex: .empty + ) globalAPI.addSourceFile(globalSourceFile, inputFilePath: "MixedGlobal.swift") let globalSkeleton = try globalAPI.finalize() let privateURL = Self.inputsDirectory.appendingPathComponent("MixedPrivate.swift") let privateSourceFile = Parser.parse(source: try String(contentsOf: privateURL, encoding: .utf8)) - let privateAPI = SwiftToSkeleton(progress: .silent, moduleName: "PrivateModule", exposeToGlobal: false) + let privateAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "PrivateModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) privateAPI.addSourceFile(privateSourceFile, inputFilePath: "MixedPrivate.swift") let privateSkeleton = try privateAPI.finalize() @@ -114,6 +134,7 @@ import Testing progress: .silent, moduleName: "TestModule", exposeToGlobal: false, + externalModuleIndex: .empty, identityMode: nil // no config default ) swiftAPI.addSourceFile(sourceFile, inputFilePath: "IdentityModeClass.swift") @@ -140,6 +161,7 @@ import Testing progress: .silent, moduleName: "TestModule", exposeToGlobal: false, + externalModuleIndex: .empty, identityMode: "pointer" // config says pointer for all classes ) swiftAPI.addSourceFile(sourceFile, inputFilePath: "IdentityModeClass.swift") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift new file mode 100644 index 000000000..4f12a88fa --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift @@ -0,0 +1,491 @@ +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct CrossModuleResolutionTests { + @Test + func resolvesTopLevelExternalStruct() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public struct Vector3D { + public let x: Double + public let y: Double + public let z: Double + @JS public init(x: Double, y: Double, z: Double) { + self.x = x; self.y = y; self.z = z + } + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func currentVelocity() -> Vector3D { + Vector3D(x: 0, y: 0, z: 0) + } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + #expect(app.usedExternalModules == ["Core"]) + let function = try #require(app.exported?.functions.first(where: { $0.name == "currentVelocity" })) + #expect(function.returnType == .swiftStruct("Vector3D")) + } + + @Test + func resolvesTopLevelExternalClass() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public class Emitter { + @JS public init() {} + @JS public func emit() -> String { "" } + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func makeEmitter() -> Emitter { Emitter() } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + #expect(app.usedExternalModules == ["Core"]) + let function = try #require(app.exported?.functions.first(where: { $0.name == "makeEmitter" })) + #expect(function.returnType == .swiftHeapObject("Emitter")) + } + + @Test + func resolvesNestedExternalStruct() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public enum Geometry { + @JS public struct BoundingBox { + public let side: Double + @JS public init(side: Double) { self.side = side } + } + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func unitBox() -> Geometry.BoundingBox { + Geometry.BoundingBox(side: 1) + } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + #expect(app.usedExternalModules == ["Core"]) + let function = try #require(app.exported?.functions.first(where: { $0.name == "unitBox" })) + #expect(function.returnType == .swiftStruct("Geometry.BoundingBox")) + } + + @Test + func resolvesExplicitModuleQualifier() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public struct Vector3D { + @JS public init() {} + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func fromCore() -> Core.Vector3D { Core.Vector3D() } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "fromCore" })) + #expect(function.returnType == .swiftStruct("Vector3D")) + } + + @Test + func resolvesExternalTypeInArrayAndOptional() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public struct Point { + @JS public init() {} + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func scatter(points: [Point?]) -> Point? { nil } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "scatter" })) + #expect(function.returnType == .nullable(.swiftStruct("Point"), .null)) + #expect(function.parameters.first?.type == .array(.nullable(.swiftStruct("Point"), .null))) + } + + // MARK: - Diagnostics + + @Test + func ambiguousExternalNameProducesDiagnostic() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let graphics = try buildDependencySkeleton( + moduleName: "Graphics", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + + do { + _ = try resolveApp( + source: """ + import Core + import Graphics + @JS public func ambiguous() -> Vector3D { fatalError() } + """, + dependencies: [ + (moduleName: "Core", skeleton: core), + (moduleName: "Graphics", skeleton: graphics), + ] + ) + Issue.record("Expected ambiguity diagnostic, but resolution succeeded") + } catch let error as BridgeJSCoreDiagnosticError { + let combined = error.diagnostics.map(\.diagnostic.message).joined(separator: "\n") + #expect(combined.contains("ambiguous use of 'Vector3D'")) + let combinedHints = error.diagnostics.compactMap(\.diagnostic.hint).joined(separator: "\n") + #expect(combinedHints.contains("Core")) + #expect(combinedHints.contains("Graphics")) + } + } + + @Test + func explicitQualifierResolvesAmbiguity() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let graphics = try buildDependencySkeleton( + moduleName: "Graphics", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Core + import Graphics + @JS public func fromCore() -> Core.Vector3D { Core.Vector3D() } + """, + dependencies: [ + (moduleName: "Core", skeleton: core), + (moduleName: "Graphics", skeleton: graphics), + ] + ) + #expect(app.usedExternalModules == ["Core"]) + } + + @Test + func localDeclarationShadowsExternalSameName() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public struct Vector3D { + public let id: Int + @JS public init(id: Int) { self.id = id } + } + @JS public func makeLocal() -> Vector3D { Vector3D(id: 42) } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + // Local declaration wins. + #expect(app.usedExternalModules == []) + let exported = try #require(app.exported) + #expect(exported.structs.contains(where: { $0.name == "Vector3D" })) + } + + @Test + func unknownTypeEmitsHintMentioningDependencyTargets() throws { + do { + _ = try resolveApp( + source: """ + @JS public func use() -> MissingType { fatalError() } + """, + dependencies: [] + ) + Issue.record("Expected an unsupported-type diagnostic") + } catch let error as BridgeJSCoreDiagnosticError { + let combinedHints = error.diagnostics.compactMap(\.diagnostic.hint).joined(separator: "\n") + #expect(combinedHints.contains("dependency targets")) + } + } + + // MARK: - Coverage across type categories + + @Test + func resolvesExternalSimpleEnum() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public enum Direction { case north, south }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public func opposite(_ d: Direction) -> Direction { d } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "opposite" })) + #expect(function.returnType == .caseEnum("Direction")) + #expect(function.parameters.first?.type == .caseEnum("Direction")) + } + + @Test + func resolvesExternalRawValueEnum() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public enum HTTPMethod: String { case get, post }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public func describe(_ m: HTTPMethod) -> String { "" } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "describe" })) + #expect(function.parameters.first?.type == .rawValueEnum("HTTPMethod", .string)) + } + + @Test + func resolvesExternalAssociatedValueEnum() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public enum Shape { case point, circle(radius: Double) }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public func area(_ s: Shape) -> Double { 0 } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "area" })) + #expect(function.parameters.first?.type == .associatedValueEnum("Shape")) + } + + @Test + func resolvesExternalNamespaceEnum() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS public enum Utils { + @JS public static func hello() -> String { "hi" } + } + """ + ) + let app = try resolveApp( + source: """ + import Core + @JS public func dummy(_ u: Utils?) -> Utils? { u } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "dummy" })) + #expect(function.returnType == .nullable(.namespaceEnum("Utils"), .null)) + } + + // MARK: - Structural positions + + @Test + func resolvesExternalInDictionaryValuePosition() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public func names(_ map: [String: Vector3D]) -> [String] { [] } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "names" })) + #expect(function.parameters.first?.type == .dictionary(.swiftStruct("Vector3D"))) + } + + @Test + func resolvesExternalInStructPropertyType() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public struct Particle { + public let position: Vector3D + @JS public init(position: Vector3D) { self.position = position } + } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let particle = try #require(app.exported?.structs.first(where: { $0.name == "Particle" })) + let positionProperty = try #require(particle.properties.first(where: { $0.name == "position" })) + #expect(positionProperty.type == .swiftStruct("Vector3D")) + #expect(app.usedExternalModules == ["Core"]) + } + + // MARK: - Multi-module scenarios + + @Test + func tracksMultipleExternalModulesInSortedOrder() throws { + let alpha = try buildDependencySkeleton( + moduleName: "Alpha", + source: "@JS public struct A { @JS public init() {} }" + ) + let beta = try buildDependencySkeleton( + moduleName: "Beta", + source: "@JS public struct B { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Alpha + import Beta + @JS public func both(_ a: A, _ b: B) -> String { "" } + """, + dependencies: [ + (moduleName: "Beta", skeleton: beta), + (moduleName: "Alpha", skeleton: alpha), + ] + ) + #expect(app.usedExternalModules == ["Alpha", "Beta"]) + } + + @Test + func transitiveDependencyTypesResolve() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let domain = try buildDependencySkeleton( + moduleName: "Domain", + source: """ + @JS public struct Particle { + public let position: Vector3D + @JS public init(position: Vector3D) { self.position = position } + } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + #expect(domain.usedExternalModules == ["Core"]) + // App can still reference Vector3D through Domain’s transitive dependency on Core. + let app = try resolveApp( + source: """ + import Core + import Domain + @JS public func position(of p: Particle) -> Vector3D { p.position } + """, + dependencies: [ + (moduleName: "Core", skeleton: core), + (moduleName: "Domain", skeleton: domain), + ] + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "position" })) + #expect(function.returnType == .swiftStruct("Vector3D")) + #expect(function.parameters.first?.type == .swiftStruct("Particle")) + #expect(app.usedExternalModules == ["Core", "Domain"]) + } + + // MARK: - Skeleton serialisation round-trip + + @Test + func skeletonRoundTripsUsedExternalModules() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + let app = try resolveApp( + source: """ + import Core + @JS public func origin() -> Vector3D { Vector3D() } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(app) + let decoded = try JSONDecoder().decode(BridgeJSSkeleton.self, from: data) + #expect(decoded.usedExternalModules == app.usedExternalModules) + #expect(decoded.moduleName == app.moduleName) + } + + @Test + func externalModuleIndexSkipsDependenciesWithoutExportedTypes() throws { + let empty = BridgeJSSkeleton(moduleName: "Empty") + let index = ExternalModuleIndex(dependencies: [(moduleName: "Empty", skeleton: empty)]) + #expect(index.isEmpty) + #expect(!index.isKnownModule("Empty")) + #expect(index.lookup(dotPath: "Whatever") == nil) + } + + @Test + func moduleQualifierRejectsUnknownModule() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: "@JS public struct Vector3D { @JS public init() {} }" + ) + do { + _ = try resolveApp( + source: """ + import Core + @JS public func useFoundation() -> Foundation.URL { fatalError() } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + Issue.record("Expected unsupported-type diagnostic for Foundation.URL") + } catch let error as BridgeJSCoreDiagnosticError { + let combinedMessages = error.diagnostics.map(\.diagnostic.message).joined(separator: "\n") + #expect(combinedMessages.contains("Foundation.URL")) + } + } + + // MARK: - Utillites + + private func resolveApp( + source appSource: String, + dependencies: [(moduleName: String, skeleton: BridgeJSSkeleton)] + ) throws -> BridgeJSSkeleton { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "App", + exposeToGlobal: false, + externalModuleIndex: ExternalModuleIndex(dependencies: dependencies) + ) + let sourceFile = Parser.parse(source: appSource) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "App.swift") + return try swiftAPI.finalize() + } + + private func buildDependencySkeleton( + moduleName: String, + source: String, + 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() + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json index d071d8c52..89b64c157 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -1531,5 +1531,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json index a2b95cc24..27ba89aca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -189,5 +189,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json index 263578d20..616a0bdbd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json @@ -147,5 +147,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json index 972a532c6..e6f4c2395 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json @@ -63,5 +63,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json index f77d39ad9..4c8d575b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json @@ -78,5 +78,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json index 9b056b650..6c589de87 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json @@ -148,5 +148,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json index d76a1622d..9bec040f1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json @@ -148,5 +148,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json index a0c2c80c6..3bb67f13c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json @@ -29,5 +29,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json index 59fb8484a..edf8177c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json @@ -61,5 +61,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json index cc10331a4..58bfadab7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json @@ -61,5 +61,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json index f8a23c33d..e7874c072 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json @@ -1312,5 +1312,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index e18586e1c..c52f3e82f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -337,5 +337,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ 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 b92cee954..873c5c49f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json @@ -1455,5 +1455,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json index ea32ad739..c4095b502 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json @@ -323,5 +323,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json index 46dbe8917..103a67999 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -639,5 +639,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json index a57703b09..f9890d36b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -639,5 +639,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json index fc4a7ae52..b51940be9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json @@ -1573,5 +1573,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json index 15a20f72e..4b7e5ceb2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json @@ -507,5 +507,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json index f750fc6a5..bafea5d81 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json @@ -57,5 +57,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json index 809a9ad99..5acb585fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json @@ -125,5 +125,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json index d7a9064dc..f4a4440c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json @@ -144,5 +144,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json index 3f9cb8e32..7ae3363db 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -74,5 +74,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json index f57e77d21..aa71b40b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json @@ -198,5 +198,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json index 1ad99f397..6edbc671c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json @@ -267,5 +267,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json index ef8eba9ba..b12f099b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json @@ -181,5 +181,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json index 18f7cfaac..c0d885b89 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json @@ -160,5 +160,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json index fb8601ae7..05e5b9d3b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json @@ -381,5 +381,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json index f140fd007..0d30063ee 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json @@ -75,5 +75,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json index 9e9dc445e..e6bcf2e5c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json @@ -75,5 +75,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ 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 080f9f959..4b6b720f1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -289,5 +289,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index d471eeaca..3c07b7dcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -289,5 +289,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 3e6d6c60c..26479bf1d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -1557,5 +1557,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json index cf76f3878..539f8132a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -125,5 +125,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json index b0398c161..1cdce90a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -150,5 +150,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json index 24e3f44cd..281538dd6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json @@ -377,5 +377,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index b46d1125e..feca4615b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -970,5 +970,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json index 36d6941d3..70273f8b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json @@ -282,5 +282,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index e20af8a3b..800018440 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -483,5 +483,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index ded6f7602..36110488c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -483,5 +483,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json index d14f9b0a3..1cbe44619 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json @@ -351,5 +351,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json index 35d740dff..8fc0667b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json @@ -351,5 +351,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json index 75462af81..3ffadf65d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json @@ -131,5 +131,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json index 1088a5cab..63ee8e54b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json @@ -60,5 +60,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index ceda64904..f25e1bda7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -275,5 +275,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index 41662e48b..abca80150 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -1875,5 +1875,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ 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 a78b1bf5d..9187f5574 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -123,5 +123,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 4c1ef582b..bfde01318 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -712,5 +712,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index ccd3043ac..6c8f9a33f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -107,5 +107,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json index 02796479f..942e5fb45 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json @@ -33,5 +33,8 @@ ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json index 1eb9e47ec..a382778e9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json @@ -412,5 +412,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json index 7f19c18bf..fd2e4c565 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json @@ -60,5 +60,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Plugins/PackageToJS/Sources/BridgeJSPluginUtilities b/Plugins/PackageToJS/Sources/BridgeJSPluginUtilities new file mode 120000 index 000000000..97aa4a1cc --- /dev/null +++ b/Plugins/PackageToJS/Sources/BridgeJSPluginUtilities @@ -0,0 +1 @@ +../../BridgeJS/Sources/BridgeJSPluginUtilities \ No newline at end of file diff --git a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift index 7e335c68e..7686372f9 100644 --- a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift +++ b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift @@ -748,15 +748,15 @@ class SkeletonCollector { } } if let target = target as? SwiftSourceModuleTarget { - let directories = [ - target.directoryURL.appending(path: "Generated/JavaScript"), - // context.pluginWorkDirectoryURL: ".build/plugins/PackageToJS/outputs/" - // .build/plugins/outputs/[package]/[target]/destination/BridgeJS/JavaScript/BridgeJS.json - context.pluginWorkDirectoryURL.deletingLastPathComponent().deletingLastPathComponent() - .appending(path: "outputs/\(package.id)/\(target.name)/destination/BridgeJS/JavaScript"), + let candidates = [ + target.directoryURL.appending(path: "Generated/JavaScript").appending(path: skeletonFile), + BridgeJSPluginPaths.skeletonURL( + targetName: target.name, + packageID: package.id, + commandPluginWorkDirectoryURL: context.pluginWorkDirectoryURL + ), ] - for directory in directories { - let skeletonURL = directory.appending(path: skeletonFile) + for skeletonURL in candidates { if FileManager.default.fileExists(atPath: skeletonURL.path) { skeletons.append(skeletonURL) } diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md index 0bd69aa5b..b8856ac30 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md @@ -12,6 +12,8 @@ The configuration system supports two complementary files: - `bridge-js.config.json` - Base configuration (checked into version control) - `bridge-js.config.local.json` - Local overrides (intended to be ignored by git, for developer-specific settings) +> Note: The presence of a configuration file, even if empty, is required to expose `@JS` types to other modules in the package. See `Examples/MultiModule/` for an example. + ## Configuration Loading ### File Locations diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md index 99a3d5b1c..5b9616105 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md @@ -58,3 +58,7 @@ For package layout and how to consume the output from JavaScript, see . + +## Multiple targets in one package + +A single package can have multiple targets that use `@JS`. Apply the BridgeJS plugin to every target that contains `@JS` declarations. To make a target's `@JS` types visible to other targets in the same package, also add a `bridge-js.config.json` file (`{}` is enough) to that target’s source directory. See `Examples/MultiModule/` for an example. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md index 7ba25f7ae..83213aca1 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md @@ -8,13 +8,11 @@ BridgeJS generates glue code per Swift target (module). Some patterns that are v ## Type usage crossing module boundary -BridgeJS does **not** support using a type across module boundaries in the following situations. +### Exporting Swift: extending types from another Swift module -### Exporting Swift: types from another Swift module +If you have multiple Swift targets (e.g. a library and an app), you **cannot** extend a type defined in one target with a `@JS` exported API in another target. -If you have multiple Swift targets (e.g. a library and an app), you **cannot** use a type defined in one target in an exported API of another target. - -**Unsupported example:** Module `App` exports a function that takes or returns a type defined in module `Lib`: +**Unsupported example:** Module `App` extends a type defined in module `Lib`: ```swift // In module Lib @@ -24,5 +22,15 @@ If you have multiple Swift targets (e.g. a library and an app), you **cannot** u } // In module App (depends on Lib) - unsupported -@JS public func transform(_ p: LibPoint) -> LibPoint { ... } +extension LibPoint { + @JS public func transformed() -> LibPoint { ... } +} ``` + +### Exporting Swift: non-`@JS` types from another Swift module + +While using `@JS` types from another Swift module is supported, it is not possible to use non-`@JS` types defined in other modules: this will fail at type lookup. + +### Exporting Swift: types from another Swift package + +Types defined in a separate Swift package cannot yet be referenced from `@JS` declarations in your package. diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index f57f91936..5e9626840 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -559,5 +559,8 @@ ] }, - "moduleName" : "BridgeJSGlobalTests" + "moduleName" : "BridgeJSGlobalTests", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json index fc1504c37..7687430a7 100644 --- a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json @@ -459,5 +459,8 @@ } ] }, - "moduleName" : "BridgeJSIdentityTests" + "moduleName" : "BridgeJSIdentityTests", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index dd4362fc1..e396662b9 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -20481,5 +20481,8 @@ } ] }, - "moduleName" : "BridgeJSRuntimeTests" + "moduleName" : "BridgeJSRuntimeTests", + "usedExternalModules" : [ + + ] } \ No newline at end of file From f483b91988d054f932f915ebce01ae3a7c473bf7 Mon Sep 17 00:00:00 2001 From: Matthew Ayers Date: Thu, 30 Apr 2026 02:51:15 -0400 Subject: [PATCH 053/140] [BridgeJS] Synthesize typed-closure init access from declaration surface (#709) (#727) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [BridgeJS] Synthesize typed-closure init access from declaration surface Resolves swiftwasm/JavaScriptKit#709: a public `@JSClass` exposing a `JSTypedClosure<...>` parameter could not be consumed from another target because the synthesized `extension JSTypedClosure { init(...) }` was always internal, leaving downstream callers no way to construct the closure value without hand-rolling a public wrapper. Imported skeleton entries now record the source access level (`public`/`package`/`internal`); the closure-signature collector takes the maximum across every surface that references a given signature, and `ClosureCodegen` prefixes the synthesized init with the resulting modifier (internal stays bare). This matches the pattern `JSClassMacro` already uses for `init(unsafelyWrapping:)`. * [BridgeJS] Address PR feedback and refresh generated artifacts - Make `accessLevel` decode-tolerant on imported skeleton structs (`ImportedFunctionSkeleton`, `ImportedConstructorSkeleton`, `ImportedGetterSkeleton`, `ImportedSetterSkeleton`, `ImportedTypeSkeleton`) by writing explicit `init(from:)` decoders that fall back to `.internal` when the key is missing. Without this, any pre-existing skeleton JSON without the new field fails decoding — the `build-examples` CI job hit `DecodingError.keyNotFound` for `accessLevel` against externally consumed skeletons. - Extract a private `recordSignature` helper so `visitClosure` and `recordInjectedSignature` share a single merge implementation. - Assert in `withAccessLevel(rawLevel:)` so unknown access strings ("open", "private", future schema additions) surface in debug builds instead of silently inheriting the outer level. - Document the `.internal` seeding assumption on `ClosureSignatureCollectorVisitor.init(moduleName:signatures:)`. - Regenerate the BridgeJS pre-generated artifacts under Benchmarks/, Examples/PlayBridgeJS/, Tests/BridgeJSIdentityTests/, and Tests/BridgeJSRuntimeTests/ via `./Utilities/bridge-js-generate.sh`, per CONTRIBUTING.md. The runtime-tests Swift output now emits `public init` on three `JSTypedClosure` extensions whose signatures surface through public exported types. * [BridgeJS] Refresh identity tests skeleton after merge with main #731 added the GC lifecycle test (with new imported function entries) to main while this branch was open. Re-running the BridgeJS regen against the merged tree fills in the `accessLevel` field on the new entries that were absent at merge time. * ci: retry flaky JSPromiseTests.testPromiseAndTimer --- .../Generated/JavaScript/BridgeJS.json | 3 + .../Generated/JavaScript/BridgeJS.json | 3 + .../Sources/BridgeJSCore/ClosureCodegen.swift | 17 +- .../BridgeJSCore/SwiftToSkeleton.swift | 64 +++- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 356 +++++++++++++++--- .../MacroSwift/SwiftTypedClosureAccess.swift | 26 ++ .../BridgeJSCodegenTests/ArrayTypes.json | 7 + .../BridgeJSCodegenTests/AsyncImport.json | 6 + .../AsyncStaticImport.json | 3 + .../CrossFileSkipsEmptySkeletons.json | 1 + .../BridgeJSCodegenTests/DictionaryTypes.json | 1 + .../BridgeJSCodegenTests/EnumRawType.json | 2 + .../FixedWidthIntegers.json | 8 + .../BridgeJSCodegenTests/GlobalGetter.json | 3 + .../GlobalThisImports.json | 7 + .../BridgeJSCodegenTests/ImportArray.json | 2 + .../ImportedTypeInExportedInterface.json | 2 + .../InvalidPropertyNames.json | 24 ++ .../BridgeJSCodegenTests/JSClass.json | 11 + .../JSClassStaticFunctions.json | 9 + .../BridgeJSCodegenTests/JSValue.json | 2 + .../BridgeJSCodegenTests/Optionals.json | 26 ++ .../PrimitiveParameters.json | 1 + .../BridgeJSCodegenTests/PrimitiveReturn.json | 2 + .../BridgeJSCodegenTests/StringParameter.json | 2 + .../BridgeJSCodegenTests/StringReturn.json | 1 + .../BridgeJSCodegenTests/SwiftClass.json | 2 + .../SwiftClosureImports.json | 2 + .../SwiftStructImports.json | 1 + .../SwiftTypedClosureAccess.json | 285 ++++++++++++++ .../SwiftTypedClosureAccess.swift | 266 +++++++++++++ .../VoidParameterVoidReturn.json | 1 + .../SwiftTypedClosureAccess.d.ts | 33 ++ .../SwiftTypedClosureAccess.js | 329 ++++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 3 + .../Generated/BridgeJS.swift | 6 +- .../Generated/JavaScript/BridgeJS.json | 164 ++++++++ 37 files changed, 1606 insertions(+), 75 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftTypedClosureAccess.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index 8e9c1cd6b..7209c62f7 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -3339,6 +3339,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -3355,6 +3356,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -3378,6 +3380,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 89ce6ae3a..6f1fc940c 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -242,6 +242,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -260,11 +261,13 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index f3ed97ba3..45cfb73f1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -21,7 +21,10 @@ public struct ClosureCodegen { return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" } - func renderClosureHelpers(_ signature: ClosureSignature) throws -> [DeclSyntax] { + func renderClosureHelpers( + _ signature: ClosureSignature, + accessLevel: BridgeJSAccessLevel = .internal + ) throws -> [DeclSyntax] { let mangledName = signature.mangleName let helperName = "_BJS_Closure_\(mangledName)" let swiftClosureType = swiftClosureType(for: signature) @@ -99,9 +102,10 @@ public struct ClosureCodegen { let helperEnumDecl: DeclSyntax = "\(raw: helperEnumDeclPrinter.lines.joined(separator: "\n"))" + let initAccessModifier = accessLevel.modifierKeyword.map { "\($0) " } ?? "" let typedClosureExtension: DeclSyntax = """ extension JSTypedClosure where Signature == \(raw: swiftClosureType) { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType)) { + \(raw: initAccessModifier)init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType)) { self.init( makeClosure: \(raw: externABIName), body: body, @@ -192,12 +196,13 @@ public struct ClosureCodegen { let collector = ClosureSignatureCollectorVisitor(moduleName: skeleton.moduleName) var walker = BridgeSkeletonWalker(visitor: collector) walker.walk(skeleton) - let closureSignatures = walker.visitor.signatures - guard !closureSignatures.isEmpty else { return nil } + let signatureAccessLevels = walker.visitor.signatureAccessLevels + guard !signatureAccessLevels.isEmpty else { return nil } var decls: [DeclSyntax] = [] - for signature in closureSignatures.sorted(by: { $0.mangleName < $1.mangleName }) { - decls.append(contentsOf: try renderClosureHelpers(signature)) + for signature in signatureAccessLevels.keys.sorted(by: { $0.mangleName < $1.mangleName }) { + let accessLevel = signatureAccessLevels[signature] ?? .internal + decls.append(contentsOf: try renderClosureHelpers(signature, accessLevel: accessLevel)) decls.append(try renderClosureInvokeHandler(signature)) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 42ba2fbaa..61306bf2c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -2122,6 +2122,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let name: String let jsName: String? let from: JSImportFrom? + let accessLevel: BridgeJSAccessLevel var constructor: ImportedConstructorSkeleton? var methods: [ImportedFunctionSkeleton] var staticMethods: [ImportedFunctionSkeleton] @@ -2337,6 +2338,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { name: typeName, jsName: nil, from: nil, + accessLevel: .internal, constructor: nil, methods: [], staticMethods: [], @@ -2345,12 +2347,18 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { ) } - private func enterJSClass(_ typeName: String, jsName: String?, from: JSImportFrom?) { + private func enterJSClass( + _ typeName: String, + jsName: String?, + from: JSImportFrom?, + accessLevel: BridgeJSAccessLevel + ) { stateStack.append(.jsClassBody(name: typeName)) currentType = CurrentType( name: typeName, jsName: jsName, from: from, + accessLevel: accessLevel, constructor: nil, methods: [], staticMethods: [], @@ -2371,7 +2379,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { staticMethods: type.staticMethods, getters: type.getters, setters: type.setters, - documentation: nil + documentation: nil, + accessLevel: type.accessLevel ) ) currentType = nil @@ -2384,7 +2393,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) let jsName = attribute.flatMap(AttributeChecker.extractJSName) let from = attribute.flatMap(AttributeChecker.extractJSImportFrom) - enterJSClass(node.name.text, jsName: jsName, from: from) + let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) + enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) } return .visitChildren } @@ -2400,7 +2410,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) let jsName = attribute.flatMap(AttributeChecker.extractJSName) let from = attribute.flatMap(AttributeChecker.extractJSImportFrom) - enterJSClass(node.name.text, jsName: jsName, from: from) + let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) + enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) } return .visitChildren } @@ -2565,8 +2576,14 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { else { 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) + parameters: parseParameters(from: initializer.signature.parameterClause), + accessLevel: accessLevel ) } @@ -2599,6 +2616,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } else { returnType = .void } + let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedFunctionSkeleton( name: name, jsName: jsName, @@ -2606,7 +2624,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { parameters: parameters, returnType: returnType, effects: effects, - documentation: nil + documentation: nil, + accessLevel: accessLevel ) } @@ -2638,13 +2657,15 @@ 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 accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedGetterSkeleton( name: propertyName, jsName: jsName, from: from, type: propertyType, documentation: nil, - functionName: nil + functionName: nil, + accessLevel: accessLevel ) } @@ -2667,12 +2688,14 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } + let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedSetterSkeleton( name: propertyName, jsName: validation.jsName, type: validation.valueType, documentation: nil, - functionName: "\(functionBaseName)_set" + functionName: "\(functionBaseName)_set", + accessLevel: accessLevel ) } @@ -2718,6 +2741,31 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { modifier.name.tokenKind == .keyword(.static) || modifier.name.tokenKind == .keyword(.class) } } + + /// Maps Swift's declaration modifiers to a `BridgeJSAccessLevel` for + /// recording on imported skeleton entries. Falls back to `default` when no + /// access modifier is present (typically `.internal`, but the caller may + /// override — e.g. an `init` inheriting from its enclosing `@JSClass`). + /// `private`/`fileprivate` are mapped to the fallback because the macros + /// already reject those access levels for `@JS*` declarations. + fileprivate static func bridgeAccessLevel( + from modifiers: DeclModifierListSyntax, + default fallback: BridgeJSAccessLevel = .internal + ) -> BridgeJSAccessLevel { + for modifier in modifiers { + switch modifier.name.tokenKind { + case .keyword(.public), .keyword(.open): + return .public + case .keyword(.package): + return .package + case .keyword(.internal): + return .internal + default: + continue + } + } + return fallback + } } extension GenericArgumentListSyntax { diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index baf6debd9..055ef2552 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -89,6 +89,38 @@ public enum BridgeContext: Sendable { case exportSwift } +/// Access level applied to bridge-generated declarations. +/// +/// Ordering (`Comparable`) reflects visibility breadth, so taking `max` of two +/// levels yields the more permissive one — used to merge a single closure +/// signature seen across surfaces with different declared access. +public enum BridgeJSAccessLevel: String, Codable, Equatable, Hashable, Sendable, Comparable { + case `internal` + case package + case `public` + + public static func < (lhs: BridgeJSAccessLevel, rhs: BridgeJSAccessLevel) -> Bool { + lhs.order < rhs.order + } + + private var order: Int { + switch self { + case .internal: return 0 + case .package: return 1 + case .public: return 2 + } + } + + /// Returns the modifier keyword to emit, or nil for the default (internal). + public var modifierKeyword: String? { + switch self { + case .internal: return nil + case .package: return "package" + case .public: return "public" + } + } +} + public struct ClosureSignature: Codable, Equatable, Hashable, Sendable { public let parameters: [BridgeType] public let returnType: BridgeType @@ -398,17 +430,34 @@ public struct Parameter: Codable, Equatable, Sendable { // MARK: - BridgeSkeleton Visitor public protocol BridgeSkeletonVisitor { - mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) + /// Called when a closure type is encountered during traversal. + /// + /// `accessLevel` reflects the source access of the enclosing declaration, + /// so visitors can derive an appropriate access level for any + /// bridge-generated helpers tied to this signature (e.g. typed closure + /// inits in `ClosureCodegen`). + mutating func visitClosure( + _ signature: ClosureSignature, + useJSTypedClosure: Bool, + accessLevel: BridgeJSAccessLevel + ) mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) } public extension BridgeSkeletonVisitor { - mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) {} + mutating func visitClosure( + _ signature: ClosureSignature, + useJSTypedClosure: Bool, + accessLevel: BridgeJSAccessLevel + ) {} mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) {} } public struct BridgeSkeletonWalker { public var visitor: Visitor + /// Tracks the access level of the enclosing declaration during traversal. + /// Saved/restored around each declaration that introduces an access boundary. + private var currentAccessLevel: BridgeJSAccessLevel = .internal public init(visitor: Visitor) { self.visitor = visitor @@ -417,7 +466,11 @@ public struct BridgeSkeletonWalker { public mutating func walk(_ type: BridgeType) { switch type { case .closure(let signature, let useJSTypedClosure): - visitor.visitClosure(signature, useJSTypedClosure: useJSTypedClosure) + visitor.visitClosure( + signature, + useJSTypedClosure: useJSTypedClosure, + accessLevel: currentAccessLevel + ) for paramType in signature.parameters { walk(paramType) } @@ -449,14 +502,16 @@ public struct BridgeSkeletonWalker { walk(function) } for klass in skeleton.classes { - if let constructor = klass.constructor { - walk(constructor.parameters) - } - for method in klass.methods { - walk(method) - } - for property in klass.properties { - walk(property.type) + withAccessLevel(klass.explicitAccessControl) { + if let constructor = klass.constructor { + $0.walk(constructor.parameters) + } + for method in klass.methods { + $0.walk(method) + } + for property in klass.properties { + $0.walk(property.type) + } } } for proto in skeleton.protocols { @@ -468,58 +523,66 @@ public struct BridgeSkeletonWalker { } } for structDecl in skeleton.structs { - for property in structDecl.properties { - walk(property.type) - } - if let constructor = structDecl.constructor { - walk(constructor.parameters) - } - for method in structDecl.methods { - walk(method) + withAccessLevel(structDecl.explicitAccessControl) { + for property in structDecl.properties { + $0.walk(property.type) + } + if let constructor = structDecl.constructor { + $0.walk(constructor.parameters) + } + for method in structDecl.methods { + $0.walk(method) + } } } for enumDecl in skeleton.enums { - for enumCase in enumDecl.cases { - for associatedValue in enumCase.associatedValues { - walk(associatedValue.type) + withAccessLevel(enumDecl.explicitAccessControl) { + for enumCase in enumDecl.cases { + for associatedValue in enumCase.associatedValues { + $0.walk(associatedValue.type) + } + } + for method in enumDecl.staticMethods { + $0.walk(method) + } + for property in enumDecl.staticProperties { + $0.walk(property.type) } - } - for method in enumDecl.staticMethods { - walk(method) - } - for property in enumDecl.staticProperties { - walk(property.type) } } } public mutating func walk(_ function: ImportedFunctionSkeleton) { visitor.visitImportedFunction(function) - walk(function.parameters) - walk(function.returnType) + withAccessLevel(function.accessLevel) { + $0.walk(function.parameters) + $0.walk(function.returnType) + } } public mutating func walk(_ skeleton: ImportedModuleSkeleton) { for fileSkeleton in skeleton.children { for getter in fileSkeleton.globalGetters { - walk(getter.type) + withAccessLevel(getter.accessLevel) { $0.walk(getter.type) } } for setter in fileSkeleton.globalSetters { - walk(setter.type) + withAccessLevel(setter.accessLevel) { $0.walk(setter.type) } } for function in fileSkeleton.functions { walk(function) } for type in fileSkeleton.types { - if let constructor = type.constructor { - walk(constructor.parameters) - } - for getter in type.getters { - walk(getter.type) - } - for setter in type.setters { - walk(setter.type) - } - for method in type.methods + type.staticMethods { - walk(method) + withAccessLevel(type.accessLevel) { + if let constructor = type.constructor { + $0.withAccessLevel(constructor.accessLevel) { $0.walk(constructor.parameters) } + } + for getter in type.getters { + $0.withAccessLevel(getter.accessLevel) { $0.walk(getter.type) } + } + for setter in type.setters { + $0.withAccessLevel(setter.accessLevel) { $0.walk(setter.type) } + } + for method in type.methods + type.staticMethods { + $0.walk(method) + } } } } @@ -532,6 +595,40 @@ public struct BridgeSkeletonWalker { walk(imported) } } + + /// Sets `currentAccessLevel` to `level` for the duration of `body`, restoring + /// the prior value afterward. A nil level (e.g. for exported decls without + /// an explicit modifier) inherits the outer level rather than overwriting it. + private mutating func withAccessLevel( + _ level: BridgeJSAccessLevel?, + _ body: (inout BridgeSkeletonWalker) -> Void + ) { + let saved = currentAccessLevel + if let level { + currentAccessLevel = level + } + body(&self) + currentAccessLevel = saved + } + + /// String-typed convenience: maps `"public"`/`"package"`/`"internal"` from + /// `Exported*.explicitAccessControl` to the typed enum. Unknown strings + /// (e.g. `"open"`, `"private"`) hit the assert in debug builds and inherit + /// the outer level in release — the `@JSExport` macros reject those cases + /// upstream, so this is a defensive guard against future schema drift. + private mutating func withAccessLevel( + _ rawLevel: String?, + _ body: (inout BridgeSkeletonWalker) -> Void + ) { + let level: BridgeJSAccessLevel? + if let rawLevel { + level = BridgeJSAccessLevel(rawValue: rawLevel) + assert(level != nil, "Unexpected access level string: \(rawLevel)") + } else { + level = nil + } + withAccessLevel(level, body) + } } public struct Effects: Codable, Equatable, Sendable { @@ -951,6 +1048,10 @@ public struct ImportedFunctionSkeleton: Codable { public let returnType: BridgeType public let effects: Effects public let documentation: String? + /// Source access level of the originating Swift declaration. Used to + /// 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 init( name: String, @@ -959,7 +1060,8 @@ public struct ImportedFunctionSkeleton: Codable { parameters: [Parameter], returnType: BridgeType, effects: Effects = Effects(isAsync: false, isThrows: true), - documentation: String? = nil + documentation: String? = nil, + accessLevel: BridgeJSAccessLevel = .internal ) { self.name = name self.jsName = jsName @@ -968,6 +1070,23 @@ public struct ImportedFunctionSkeleton: Codable { self.returnType = returnType self.effects = effects self.documentation = documentation + self.accessLevel = accessLevel + } + + private enum CodingKeys: String, CodingKey { + case name, jsName, from, parameters, returnType, effects, documentation, accessLevel + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.jsName = try container.decodeIfPresent(String.self, forKey: .jsName) + self.from = try container.decodeIfPresent(JSImportFrom.self, forKey: .from) + self.parameters = try container.decode([Parameter].self, forKey: .parameters) + self.returnType = try container.decode(BridgeType.self, forKey: .returnType) + 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 } public func abiName(context: ImportedTypeSkeleton?) -> String { @@ -985,9 +1104,23 @@ public struct ImportedFunctionSkeleton: Codable { public struct ImportedConstructorSkeleton: Codable { public let parameters: [Parameter] + /// Source access level of the originating Swift `init`. Inherits from the + /// enclosing `@JSClass` type when not annotated explicitly. + public let accessLevel: BridgeJSAccessLevel - public init(parameters: [Parameter]) { + public init(parameters: [Parameter], accessLevel: BridgeJSAccessLevel = .internal) { self.parameters = parameters + self.accessLevel = accessLevel + } + + private enum CodingKeys: String, CodingKey { + case parameters, accessLevel + } + + 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 } public func abiName(context: ImportedTypeSkeleton) -> String { @@ -1008,6 +1141,8 @@ public struct ImportedGetterSkeleton: Codable { public let documentation: String? /// Name of the getter function if it's a separate function (from @JSGetter) public let functionName: String? + /// Source access level of the originating Swift declaration. + public let accessLevel: BridgeJSAccessLevel public init( name: String, @@ -1015,7 +1150,8 @@ public struct ImportedGetterSkeleton: Codable { from: JSImportFrom? = nil, type: BridgeType, documentation: String? = nil, - functionName: String? = nil + functionName: String? = nil, + accessLevel: BridgeJSAccessLevel = .internal ) { self.name = name self.jsName = jsName @@ -1023,6 +1159,22 @@ public struct ImportedGetterSkeleton: Codable { self.type = type self.documentation = documentation self.functionName = functionName + self.accessLevel = accessLevel + } + + private enum CodingKeys: String, CodingKey { + case name, jsName, from, type, documentation, functionName, accessLevel + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.jsName = try container.decodeIfPresent(String.self, forKey: .jsName) + self.from = try container.decodeIfPresent(JSImportFrom.self, forKey: .from) + self.type = try container.decode(BridgeType.self, forKey: .type) + self.documentation = try container.decodeIfPresent(String.self, forKey: .documentation) + self.functionName = try container.decodeIfPresent(String.self, forKey: .functionName) + self.accessLevel = try container.decodeIfPresent(BridgeJSAccessLevel.self, forKey: .accessLevel) ?? .internal } public func abiName(context: ImportedTypeSkeleton?) -> String { @@ -1049,19 +1201,37 @@ public struct ImportedSetterSkeleton: Codable { public let documentation: String? /// Name of the setter function if it's a separate function (from @JSSetter) public let functionName: String? + /// Source access level of the originating Swift declaration. + public let accessLevel: BridgeJSAccessLevel public init( name: String, jsName: String? = nil, type: BridgeType, documentation: String? = nil, - functionName: String? = nil + functionName: String? = nil, + accessLevel: BridgeJSAccessLevel = .internal ) { self.name = name self.jsName = jsName self.type = type self.documentation = documentation self.functionName = functionName + self.accessLevel = accessLevel + } + + private enum CodingKeys: String, CodingKey { + case name, jsName, type, documentation, functionName, accessLevel + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.jsName = try container.decodeIfPresent(String.self, forKey: .jsName) + self.type = try container.decode(BridgeType.self, forKey: .type) + self.documentation = try container.decodeIfPresent(String.self, forKey: .documentation) + self.functionName = try container.decodeIfPresent(String.self, forKey: .functionName) + self.accessLevel = try container.decodeIfPresent(BridgeJSAccessLevel.self, forKey: .accessLevel) ?? .internal } public func abiName(context: ImportedTypeSkeleton?) -> String { @@ -1093,6 +1263,8 @@ public struct ImportedTypeSkeleton: Codable { public let getters: [ImportedGetterSkeleton] public let setters: [ImportedSetterSkeleton] public let documentation: String? + /// Source access level of the originating Swift `@JSClass` declaration. + public let accessLevel: BridgeJSAccessLevel public init( name: String, @@ -1103,7 +1275,8 @@ public struct ImportedTypeSkeleton: Codable { staticMethods: [ImportedFunctionSkeleton] = [], getters: [ImportedGetterSkeleton] = [], setters: [ImportedSetterSkeleton] = [], - documentation: String? = nil + documentation: String? = nil, + accessLevel: BridgeJSAccessLevel = .internal ) { self.name = name self.jsName = jsName @@ -1114,6 +1287,25 @@ public struct ImportedTypeSkeleton: Codable { self.getters = getters self.setters = setters self.documentation = documentation + self.accessLevel = accessLevel + } + + private enum CodingKeys: String, CodingKey { + case name, jsName, from, constructor, methods, staticMethods, getters, setters, documentation, accessLevel + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.jsName = try container.decodeIfPresent(String.self, forKey: .jsName) + self.from = try container.decodeIfPresent(JSImportFrom.self, forKey: .from) + self.constructor = try container.decodeIfPresent(ImportedConstructorSkeleton.self, forKey: .constructor) + self.methods = try container.decode([ImportedFunctionSkeleton].self, forKey: .methods) + self.staticMethods = try container.decode([ImportedFunctionSkeleton].self, forKey: .staticMethods) + self.getters = try container.decode([ImportedGetterSkeleton].self, forKey: .getters) + self.setters = try container.decode([ImportedSetterSkeleton].self, forKey: .setters) + self.documentation = try container.decodeIfPresent(String.self, forKey: .documentation) + self.accessLevel = try container.decodeIfPresent(BridgeJSAccessLevel.self, forKey: .accessLevel) ?? .internal } } @@ -1180,16 +1372,50 @@ public struct ImportedModuleSkeleton: Codable { // MARK: - Closure signature collection visitor public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { - public var signatures: Set = [] + /// Each unique closure signature mapped to the most-permissive access level + /// observed across all surfaces that reference it. The codegen reads this + /// to choose the access modifier for the synthesized typed-closure init. + public private(set) var signatureAccessLevels: [ClosureSignature: BridgeJSAccessLevel] = [:] + /// Convenience view for callers (e.g. `BridgeJSLink`) that only need the + /// set of unique signatures, without access metadata. + public var signatures: Set { Set(signatureAccessLevels.keys) } let moduleName: String + /// Convenience for callers that only need to seed signatures without + /// access metadata (e.g. exported-side walking, where closure init access + /// is irrelevant because the synthesized init isn't surfaced to consumers). + /// All seeded signatures default to `.internal`; if a seeded signature is + /// later observed with a more permissive access level, the merge in + /// `recordSignature` upgrades it. public init(moduleName: String, signatures: Set = []) { self.moduleName = moduleName - self.signatures = signatures + for signature in signatures { + signatureAccessLevels[signature] = .internal + } + } + + public mutating func visitClosure( + _ signature: ClosureSignature, + useJSTypedClosure: Bool, + accessLevel: BridgeJSAccessLevel + ) { + recordSignature(signature, accessLevel: accessLevel) } - public mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) { - signatures.insert(signature) + /// 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 + /// 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( + _ signature: ClosureSignature, + accessLevel: BridgeJSAccessLevel + ) { + if let existing = signatureAccessLevels[signature] { + signatureAccessLevels[signature] = max(existing, accessLevel) + } else { + signatureAccessLevels[signature] = accessLevel + } } public mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) { guard function.effects.isAsync else { return } @@ -1202,34 +1428,48 @@ public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { // transferred through the checked continuation without Sendable constraints. // Reject callback - signatures.insert( + recordInjectedSignature( ClosureSignature( parameters: [.jsValue], returnType: .void, moduleName: moduleName, sendingParameters: true - ) + ), + for: function ) // Resolve callback (typed per return type) if function.returnType == .void { - signatures.insert( + recordInjectedSignature( ClosureSignature( parameters: [], returnType: .void, moduleName: moduleName - ) + ), + for: function ) } else { - signatures.insert( + recordInjectedSignature( ClosureSignature( parameters: [function.returnType], returnType: .void, moduleName: moduleName, sendingParameters: true - ) + ), + for: function ) } } + + /// 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 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftTypedClosureAccess.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftTypedClosureAccess.swift new file mode 100644 index 000000000..6487d343b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftTypedClosureAccess.swift @@ -0,0 +1,26 @@ +// Verifies that `JSTypedClosure` initializers synthesized by BridgeJS adopt the +// access level of the originating `@JSClass`/`@JSFunction` surface, so that +// downstream targets can construct typed closures for public APIs (issue #709). + +@JSClass(jsName: "PublicEvent") public struct JSPublicEvent {} +@JSClass(jsName: "PackageEvent") package struct JSPackageEvent {} +@JSClass(jsName: "InternalEvent") struct JSInternalEvent {} + +@JSClass(jsName: "PublicTarget") public struct JSPublicTarget { + // A public method taking a typed closure must yield a `public` synthesized init, + // since downstream modules may construct the closure value. + @JSFunction public func addPublicListener(_ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) + // Same closure shape on an internal method — the synthesized init merges to public, + // because at most one extension per signature is generated. + @JSFunction func addInternalListener(_ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) +} + +@JSClass(jsName: "PackageTarget") package struct JSPackageTarget { + // A package-level surface yields a `package` synthesized init. + @JSFunction package func addPackageListener(_ handler: JSTypedClosure<(JSPackageEvent) -> Void>) throws(JSException) +} + +@JSClass(jsName: "InternalTarget") struct JSInternalTarget { + // No public/package surface for this signature — the synthesized init stays internal. + @JSFunction func addInternalListener(_ handler: JSTypedClosure<(JSInternalEvent) -> Void>) throws(JSException) +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json index 89b64c157..d4ac7a15f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -1331,6 +1331,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1354,6 +1355,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1385,6 +1387,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1412,6 +1415,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1432,6 +1436,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1463,6 +1468,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1494,6 +1500,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json index 616a0bdbd..7f66bede4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -20,6 +21,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -49,6 +51,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -72,6 +75,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -95,6 +99,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -118,6 +123,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json index e6f4c2395..2aea1c115 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.json @@ -7,6 +7,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -19,6 +20,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -42,6 +44,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json index 3bb67f13c..ff90a4cab 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index c52f3e82f..b1185c644 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -300,6 +300,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json index b51940be9..1cf99cd39 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json @@ -1526,6 +1526,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1550,6 +1551,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json index 4b7e5ceb2..1186ad27d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json @@ -269,6 +269,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -298,6 +299,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -327,6 +329,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -356,6 +359,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -385,6 +389,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -414,6 +419,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -443,6 +449,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -472,6 +479,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json index bafea5d81..83353291c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json @@ -7,6 +7,7 @@ ], "globalGetters" : [ { + "accessLevel" : "internal", "name" : "console", "type" : { "jsObject" : { @@ -17,11 +18,13 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json index 5acb585fe..5f6a08da9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -31,6 +32,7 @@ ], "globalGetters" : [ { + "accessLevel" : "internal", "from" : "global", "name" : "console", "type" : { @@ -42,11 +44,13 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -79,7 +83,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "url", @@ -97,6 +103,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json index 7ae3363db..7bf447ad5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -41,6 +42,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json index aa71b40b9..600ae8c89 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json @@ -175,7 +175,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json index 6edbc671c..7cc1d81a8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20,6 +21,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -38,8 +40,10 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ { + "accessLevel" : "internal", "name" : "normalProperty", "type" : { "string" : { @@ -48,6 +52,7 @@ } }, { + "accessLevel" : "internal", "jsName" : "property-with-dashes", "name" : "property_with_dashes", "type" : { @@ -57,6 +62,7 @@ } }, { + "accessLevel" : "internal", "jsName" : "123invalidStart", "name" : "_123invalidStart", "type" : { @@ -66,6 +72,7 @@ } }, { + "accessLevel" : "internal", "jsName" : "property with spaces", "name" : "property_with_spaces", "type" : { @@ -75,6 +82,7 @@ } }, { + "accessLevel" : "internal", "jsName" : "@specialChar", "name" : "_specialChar", "type" : { @@ -84,6 +92,7 @@ } }, { + "accessLevel" : "internal", "name" : "constructor", "type" : { "string" : { @@ -92,6 +101,7 @@ } }, { + "accessLevel" : "internal", "name" : "for", "type" : { "string" : { @@ -100,6 +110,7 @@ } }, { + "accessLevel" : "internal", "name" : "Any", "type" : { "string" : { @@ -110,6 +121,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -126,6 +138,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -145,6 +158,7 @@ "name" : "WeirdNaming", "setters" : [ { + "accessLevel" : "internal", "functionName" : "normalProperty_set", "name" : "normalProperty", "type" : { @@ -154,6 +168,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "property_with_dashes_set", "jsName" : "property-with-dashes", "name" : "property_with_dashes", @@ -164,6 +179,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "_123invalidStart_set", "jsName" : "123invalidStart", "name" : "_123invalidStart", @@ -174,6 +190,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "property_with_spaces_set", "jsName" : "property with spaces", "name" : "property_with_spaces", @@ -184,6 +201,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "_specialChar_set", "jsName" : "@specialChar", "name" : "_specialChar", @@ -194,6 +212,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "constructor_set", "name" : "constructor", "type" : { @@ -203,6 +222,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "for_set", "name" : "for", "type" : { @@ -212,6 +232,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "any_set", "jsName" : "Any", "name" : "any", @@ -227,7 +248,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ ] @@ -238,6 +261,7 @@ "jsName" : "$Weird", "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json index b12f099b6..2455e5e6d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -22,7 +23,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "name", @@ -36,6 +39,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "name", "type" : { "string" : { @@ -44,6 +48,7 @@ } }, { + "accessLevel" : "internal", "name" : "age", "type" : { "double" : { @@ -54,6 +59,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -70,6 +76,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -96,6 +103,7 @@ "name" : "Greeter", "setters" : [ { + "accessLevel" : "internal", "functionName" : "name_set", "name" : "name", "type" : { @@ -110,11 +118,13 @@ ] }, { + "accessLevel" : "internal", "getters" : [ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -146,6 +156,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json index c0d885b89..363e8d875 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json @@ -7,11 +7,13 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -34,6 +36,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -57,6 +60,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -73,6 +77,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -89,6 +94,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -108,7 +114,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "value", @@ -132,6 +140,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json index 05e5b9d3b..f0cd29565 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json @@ -321,6 +321,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -344,6 +345,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 26479bf1d..921983115 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -1008,7 +1008,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "valueOrNull", @@ -1040,6 +1042,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "stringOrNull", "type" : { "nullable" : { @@ -1053,6 +1056,7 @@ } }, { + "accessLevel" : "internal", "name" : "stringOrUndefined", "type" : { "nullable" : { @@ -1066,6 +1070,7 @@ } }, { + "accessLevel" : "internal", "name" : "doubleOrNull", "type" : { "nullable" : { @@ -1079,6 +1084,7 @@ } }, { + "accessLevel" : "internal", "name" : "doubleOrUndefined", "type" : { "nullable" : { @@ -1092,6 +1098,7 @@ } }, { + "accessLevel" : "internal", "name" : "boolOrNull", "type" : { "nullable" : { @@ -1105,6 +1112,7 @@ } }, { + "accessLevel" : "internal", "name" : "boolOrUndefined", "type" : { "nullable" : { @@ -1118,6 +1126,7 @@ } }, { + "accessLevel" : "internal", "name" : "intOrNull", "type" : { "nullable" : { @@ -1134,6 +1143,7 @@ } }, { + "accessLevel" : "internal", "name" : "intOrUndefined", "type" : { "nullable" : { @@ -1152,6 +1162,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1185,6 +1196,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1218,6 +1230,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1251,6 +1264,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1284,6 +1298,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1317,6 +1332,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1350,6 +1366,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1389,6 +1406,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -1431,6 +1449,7 @@ "name" : "WithOptionalJSClass", "setters" : [ { + "accessLevel" : "internal", "functionName" : "stringOrNull_set", "name" : "stringOrNull", "type" : { @@ -1445,6 +1464,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "stringOrUndefined_set", "name" : "stringOrUndefined", "type" : { @@ -1459,6 +1479,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "doubleOrNull_set", "name" : "doubleOrNull", "type" : { @@ -1473,6 +1494,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "doubleOrUndefined_set", "name" : "doubleOrUndefined", "type" : { @@ -1487,6 +1509,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "boolOrNull_set", "name" : "boolOrNull", "type" : { @@ -1501,6 +1524,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "boolOrUndefined_set", "name" : "boolOrUndefined", "type" : { @@ -1515,6 +1539,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "intOrNull_set", "name" : "intOrNull", "type" : { @@ -1532,6 +1557,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "intOrUndefined_set", "name" : "intOrUndefined", "type" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json index 539f8132a..320499ff3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -88,6 +88,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json index 1cdce90a6..414fedbbd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -112,6 +112,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -128,6 +129,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json index 3ffadf65d..d9dc0ec43 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json @@ -71,6 +71,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -94,6 +95,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json index 63ee8e54b..e2cf9ffac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json @@ -38,6 +38,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index f25e1bda7..a3ddab63e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -213,6 +213,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -236,6 +237,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json index 9187f5574..a84441bb4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -4,6 +4,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -66,6 +67,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index 6c8f9a33f..fc59471bb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -56,6 +56,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json new file mode 100644 index 000000000..e602989a1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json @@ -0,0 +1,285 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "public", + "getters" : [ + + ], + "jsName" : "PublicEvent", + "methods" : [ + + ], + "name" : "JSPublicEvent", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "package", + "getters" : [ + + ], + "jsName" : "PackageEvent", + "methods" : [ + + ], + "name" : "JSPackageEvent", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "internal", + "getters" : [ + + ], + "jsName" : "InternalEvent", + "methods" : [ + + ], + "name" : "JSInternalEvent", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "public", + "getters" : [ + + ], + "jsName" : "PublicTarget", + "methods" : [ + { + "accessLevel" : "public", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "addPublicListener", + "parameters" : [ + { + "name" : "handler", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule13JSPublicEventC_y", + "moduleName" : "TestModule", + "parameters" : [ + { + "jsObject" : { + "_0" : "JSPublicEvent" + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "addInternalListener", + "parameters" : [ + { + "name" : "handler", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule13JSPublicEventC_y", + "moduleName" : "TestModule", + "parameters" : [ + { + "jsObject" : { + "_0" : "JSPublicEvent" + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "JSPublicTarget", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "package", + "getters" : [ + + ], + "jsName" : "PackageTarget", + "methods" : [ + { + "accessLevel" : "package", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "addPackageListener", + "parameters" : [ + { + "name" : "handler", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule14JSPackageEventC_y", + "moduleName" : "TestModule", + "parameters" : [ + { + "jsObject" : { + "_0" : "JSPackageEvent" + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "JSPackageTarget", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "internal", + "getters" : [ + + ], + "jsName" : "InternalTarget", + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "addInternalListener", + "parameters" : [ + { + "name" : "handler", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule15JSInternalEventC_y", + "moduleName" : "TestModule", + "parameters" : [ + { + "jsObject" : { + "_0" : "JSInternalEvent" + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "JSInternalTarget", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift new file mode 100644 index 000000000..fbd181fcc --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift @@ -0,0 +1,266 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y") +fileprivate func invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule13JSPublicEventC_y") +fileprivate func make_swift_closure_TestModule_10TestModule13JSPublicEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule13JSPublicEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule13JSPublicEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule13JSPublicEventC_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule13JSPublicEventC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (JSPublicEvent) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (JSPublicEvent) -> Void { + public init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (JSPublicEvent) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule13JSPublicEventC_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y") +public func _invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSPublicEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSPublicEvent.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y") +fileprivate func invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule14JSPackageEventC_y") +fileprivate func make_swift_closure_TestModule_10TestModule14JSPackageEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule14JSPackageEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule14JSPackageEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule14JSPackageEventC_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule14JSPackageEventC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (JSPackageEvent) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (JSPackageEvent) -> Void { + package init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (JSPackageEvent) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule14JSPackageEventC_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y") +public func _invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSPackageEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSPackageEvent.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y") +fileprivate func invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule15JSInternalEventC_y") +fileprivate func make_swift_closure_TestModule_10TestModule15JSInternalEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule15JSInternalEventC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule15JSInternalEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule15JSInternalEventC_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule15JSInternalEventC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (JSInternalEvent) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (JSInternalEvent) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (JSInternalEvent) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule15JSInternalEventC_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y") +public func _invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSInternalEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSInternalEvent.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_JSPublicTarget_addPublicListener") +fileprivate func bjs_JSPublicTarget_addPublicListener_extern(_ self: Int32, _ handler: Int32) -> Void +#else +fileprivate func bjs_JSPublicTarget_addPublicListener_extern(_ self: Int32, _ handler: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSPublicTarget_addPublicListener(_ self: Int32, _ handler: Int32) -> Void { + return bjs_JSPublicTarget_addPublicListener_extern(self, handler) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_JSPublicTarget_addInternalListener") +fileprivate func bjs_JSPublicTarget_addInternalListener_extern(_ self: Int32, _ handler: Int32) -> Void +#else +fileprivate func bjs_JSPublicTarget_addInternalListener_extern(_ self: Int32, _ handler: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSPublicTarget_addInternalListener(_ self: Int32, _ handler: Int32) -> Void { + return bjs_JSPublicTarget_addInternalListener_extern(self, handler) +} + +func _$JSPublicTarget_addPublicListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let handlerFuncRef = handler.bridgeJSLowerParameter() + bjs_JSPublicTarget_addPublicListener(selfValue, handlerFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$JSPublicTarget_addInternalListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let handlerFuncRef = handler.bridgeJSLowerParameter() + bjs_JSPublicTarget_addInternalListener(selfValue, handlerFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_JSPackageTarget_addPackageListener") +fileprivate func bjs_JSPackageTarget_addPackageListener_extern(_ self: Int32, _ handler: Int32) -> Void +#else +fileprivate func bjs_JSPackageTarget_addPackageListener_extern(_ self: Int32, _ handler: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSPackageTarget_addPackageListener(_ self: Int32, _ handler: Int32) -> Void { + return bjs_JSPackageTarget_addPackageListener_extern(self, handler) +} + +func _$JSPackageTarget_addPackageListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPackageEvent) -> Void>) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let handlerFuncRef = handler.bridgeJSLowerParameter() + bjs_JSPackageTarget_addPackageListener(selfValue, handlerFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_JSInternalTarget_addInternalListener") +fileprivate func bjs_JSInternalTarget_addInternalListener_extern(_ self: Int32, _ handler: Int32) -> Void +#else +fileprivate func bjs_JSInternalTarget_addInternalListener_extern(_ self: Int32, _ handler: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSInternalTarget_addInternalListener(_ self: Int32, _ handler: Int32) -> Void { + return bjs_JSInternalTarget_addInternalListener_extern(self, handler) +} + +func _$JSInternalTarget_addInternalListener(_ self: JSObject, _ handler: JSTypedClosure<(JSInternalEvent) -> Void>) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let handlerFuncRef = handler.bridgeJSLowerParameter() + bjs_JSInternalTarget_addInternalListener(selfValue, handlerFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json index fd2e4c565..d31f775fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json @@ -38,6 +38,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts new file mode 100644 index 000000000..99adf95b6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.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 interface JSPublicEvent { +} +export interface JSPackageEvent { +} +export interface JSInternalEvent { +} +export interface JSPublicTarget { + addPublicListener(handler: (arg0: JSPublicEvent) => void): void; + addInternalListener(handler: (arg0: JSPublicEvent) => void): void; +} +export interface JSPackageTarget { + addPackageListener(handler: (arg0: JSPackageEvent) => void): void; +} +export interface JSInternalTarget { + addInternalListener(handler: (arg0: JSInternalEvent) => void): void; +} +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/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js new file mode 100644 index 000000000..4e0fd8341 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -0,0 +1,329 @@ +// 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 = []; + 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(); + } + 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_10TestModule13JSPublicEventC_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(swift.memory.getObject(param0)); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule13JSPublicEventC_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule13JSPublicEventC_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y(boxPtr, swift.memory.retain(param0)); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule13JSPublicEventC_y); + } + bjs["invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(swift.memory.getObject(param0)); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule14JSPackageEventC_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule14JSPackageEventC_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y(boxPtr, swift.memory.retain(param0)); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule14JSPackageEventC_y); + } + bjs["invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(swift.memory.getObject(param0)); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule15JSInternalEventC_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule15JSInternalEventC_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y(boxPtr, swift.memory.retain(param0)); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule15JSInternalEventC_y); + } + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_JSPublicTarget_addPublicListener"] = function bjs_JSPublicTarget_addPublicListener(self, handler) { + try { + swift.memory.getObject(self).addPublicListener(swift.memory.getObject(handler)); + } catch (error) { + setException(error); + } + } + TestModule["bjs_JSPublicTarget_addInternalListener"] = function bjs_JSPublicTarget_addInternalListener(self, handler) { + try { + swift.memory.getObject(self).addInternalListener(swift.memory.getObject(handler)); + } catch (error) { + setException(error); + } + } + TestModule["bjs_JSPackageTarget_addPackageListener"] = function bjs_JSPackageTarget_addPackageListener(self, handler) { + try { + swift.memory.getObject(self).addPackageListener(swift.memory.getObject(handler)); + } catch (error) { + setException(error); + } + } + TestModule["bjs_JSInternalTarget_addInternalListener"] = function bjs_JSInternalTarget_addInternalListener(self, handler) { + try { + swift.memory.getObject(self).addInternalListener(swift.memory.getObject(handler)); + } 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/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json index 7687430a7..56db0a3ed 100644 --- a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json @@ -407,6 +407,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -426,6 +427,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -438,6 +440,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index a37a7e4c5..db8962089 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -369,7 +369,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS { } extension JSTypedClosure where Signature == (Greeter) -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Greeter) -> String) { + public init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Greeter) -> String) { self.init( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS, body: body, @@ -687,7 +687,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { } extension JSTypedClosure where Signature == (String) -> Greeter { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> Greeter) { + public init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> Greeter) { self.init( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC, body: body, @@ -753,7 +753,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { } extension JSTypedClosure where Signature == (String) -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> String) { + public init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> String) { self.init( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS, body: body, diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index e396662b9..d9108f2e7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -16410,7 +16410,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "id", @@ -16424,6 +16426,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "id", "type" : { "string" : { @@ -16444,6 +16447,7 @@ ] }, { + "accessLevel" : "internal", "getters" : [ ], @@ -16456,6 +16460,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16489,6 +16494,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16526,6 +16532,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16557,6 +16564,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16588,6 +16596,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16619,6 +16628,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16650,6 +16660,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16681,6 +16692,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16712,6 +16724,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16759,6 +16772,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16800,6 +16814,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16841,6 +16856,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16882,6 +16898,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16923,6 +16940,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16964,6 +16982,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -16991,6 +17010,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17011,6 +17031,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17036,6 +17057,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -17048,6 +17070,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17064,6 +17087,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17087,6 +17111,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17110,6 +17135,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17133,6 +17159,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17166,6 +17193,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17199,6 +17227,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17230,6 +17259,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17261,6 +17291,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17292,6 +17323,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -17326,6 +17358,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -17338,6 +17371,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17376,6 +17410,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17414,6 +17449,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17476,6 +17512,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17526,6 +17563,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17576,6 +17614,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17626,6 +17665,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17677,6 +17717,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17719,6 +17760,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17761,6 +17803,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17820,6 +17863,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17879,6 +17923,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17946,6 +17991,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -17984,6 +18030,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18027,6 +18074,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18065,6 +18113,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18081,6 +18130,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18100,6 +18150,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18125,6 +18176,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -18137,6 +18189,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18162,6 +18215,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -18174,6 +18228,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18211,6 +18266,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18242,6 +18298,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18273,6 +18330,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18304,6 +18362,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18335,6 +18394,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18383,7 +18443,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "value", @@ -18397,6 +18459,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "value", "type" : { "string" : { @@ -18421,6 +18484,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18437,6 +18501,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18460,6 +18525,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18483,6 +18549,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18506,6 +18573,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18529,6 +18597,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18552,6 +18621,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18575,6 +18645,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18598,6 +18669,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18621,6 +18693,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18646,6 +18719,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -18662,6 +18736,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : true, "isStatic" : false, @@ -18685,6 +18760,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18702,6 +18778,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18728,6 +18805,7 @@ ], "globalGetters" : [ { + "accessLevel" : "internal", "from" : "global", "name" : "globalObject1", "type" : { @@ -18739,7 +18817,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "name", @@ -18761,6 +18841,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "name", "type" : { "string" : { @@ -18769,6 +18850,7 @@ } }, { + "accessLevel" : "internal", "name" : "prefix", "type" : { "string" : { @@ -18779,6 +18861,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18795,6 +18878,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18821,6 +18905,7 @@ "name" : "JsGreeter", "setters" : [ { + "accessLevel" : "internal", "functionName" : "name_set", "name" : "name", "type" : { @@ -18835,8 +18920,10 @@ ] }, { + "accessLevel" : "internal", "getters" : [ { + "accessLevel" : "internal", "name" : "temperature", "type" : { "double" : { @@ -18845,6 +18932,7 @@ } }, { + "accessLevel" : "internal", "name" : "description", "type" : { "string" : { @@ -18853,6 +18941,7 @@ } }, { + "accessLevel" : "internal", "name" : "humidity", "type" : { "double" : { @@ -18867,6 +18956,7 @@ "name" : "WeatherData", "setters" : [ { + "accessLevel" : "internal", "functionName" : "temperature_set", "name" : "temperature", "type" : { @@ -18876,6 +18966,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "description_set", "name" : "description", "type" : { @@ -18885,6 +18976,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "humidity_set", "name" : "humidity", "type" : { @@ -18899,7 +18991,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ ] @@ -18910,6 +19004,7 @@ "jsName" : "$WeirdClass", "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18936,7 +19031,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "value", @@ -18953,6 +19050,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18975,6 +19073,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -18998,6 +19097,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19014,6 +19114,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19030,6 +19131,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19049,7 +19151,9 @@ ] }, { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "name", @@ -19080,6 +19184,7 @@ "from" : "global", "getters" : [ { + "accessLevel" : "internal", "name" : "name", "type" : { "string" : { @@ -19088,6 +19193,7 @@ } }, { + "accessLevel" : "internal", "name" : "age", "type" : { "double" : { @@ -19096,6 +19202,7 @@ } }, { + "accessLevel" : "internal", "name" : "isCat", "type" : { "bool" : { @@ -19106,6 +19213,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19122,6 +19230,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19141,6 +19250,7 @@ "name" : "Animal", "setters" : [ { + "accessLevel" : "internal", "functionName" : "name_set", "name" : "name", "type" : { @@ -19150,6 +19260,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "age_set", "name" : "age", "type" : { @@ -19159,6 +19270,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "isCat_set", "name" : "isCat", "type" : { @@ -19177,6 +19289,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19232,6 +19345,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -19244,6 +19358,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19273,6 +19388,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19302,6 +19418,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19331,6 +19448,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19360,6 +19478,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19389,6 +19508,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19418,6 +19538,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19447,6 +19568,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19476,6 +19598,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19505,6 +19628,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19534,6 +19658,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19559,7 +19684,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ { "name" : "numbers", @@ -19592,6 +19719,7 @@ }, "getters" : [ { + "accessLevel" : "internal", "name" : "numbers", "type" : { "array" : { @@ -19607,6 +19735,7 @@ } }, { + "accessLevel" : "internal", "name" : "labels", "type" : { "array" : { @@ -19621,6 +19750,7 @@ ], "methods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19658,6 +19788,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19689,6 +19820,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19719,6 +19851,7 @@ "name" : "JSClassWithArrayMembers", "setters" : [ { + "accessLevel" : "internal", "functionName" : "numbers_set", "name" : "numbers", "type" : { @@ -19735,6 +19868,7 @@ } }, { + "accessLevel" : "internal", "functionName" : "labels_set", "name" : "labels", "type" : { @@ -19753,6 +19887,7 @@ ] }, { + "accessLevel" : "internal", "getters" : [ ], @@ -19765,6 +19900,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19816,7 +19952,9 @@ ], "types" : [ { + "accessLevel" : "internal", "constructor" : { + "accessLevel" : "internal", "parameters" : [ ] @@ -19837,7 +19975,9 @@ ] }, { + "accessLevel" : "public", "constructor" : { + "accessLevel" : "public", "parameters" : [ ] @@ -19858,7 +19998,9 @@ ] }, { + "accessLevel" : "package", "constructor" : { + "accessLevel" : "package", "parameters" : [ ] @@ -19883,6 +20025,7 @@ { "functions" : [ { + "accessLevel" : "package", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19899,6 +20042,7 @@ } }, { + "accessLevel" : "public", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19915,6 +20059,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19931,6 +20076,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19947,6 +20093,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -19973,6 +20120,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -19985,6 +20133,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20024,6 +20173,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20063,6 +20213,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20096,6 +20247,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20129,6 +20281,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20170,6 +20323,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20211,6 +20365,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20252,6 +20407,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20293,6 +20449,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20315,6 +20472,7 @@ { "functions" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20334,6 +20492,7 @@ ], "types" : [ { + "accessLevel" : "internal", "getters" : [ ], @@ -20346,6 +20505,7 @@ ], "staticMethods" : [ { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20369,6 +20529,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20392,6 +20553,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20425,6 +20587,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, @@ -20448,6 +20611,7 @@ } }, { + "accessLevel" : "internal", "effects" : { "isAsync" : false, "isStatic" : false, From 1c107ad27e29562859f114a18bf7bf128f42bd45 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 30 Apr 2026 11:52:53 +0200 Subject: [PATCH 054/140] BridgeJS: Add swift-format-ignore-file to generated Swift sources --- .../Sources/Generated/BridgeJS.Macros.swift | 1 + Benchmarks/Sources/Generated/BridgeJS.swift | 1 + .../Generated/BridgeJS.Macros.swift | 1 + .../PlayBridgeJS/Generated/BridgeJS.swift | 1 + .../Sources/BridgeJSUtilities/Utilities.swift | 1 + .../Sources/TS2Swift/JavaScript/src/cli.js | 1 + .../test/__snapshots__/ts2swift.test.js.snap | 75 ++++++++++++------- .../SwiftTypedClosureAccess.json | 5 +- .../Generated/BridgeJS.swift | 1 + .../Generated/BridgeJS.swift | 1 + .../Generated/BridgeJS.Macros.swift | 1 + .../Generated/BridgeJS.swift | 1 + 12 files changed, 64 insertions(+), 26 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.Macros.swift b/Benchmarks/Sources/Generated/BridgeJS.Macros.swift index 40fc29e91..b107d8d3c 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.Macros.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.Macros.swift @@ -1,3 +1,4 @@ +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index e199e4a29..384ca35a2 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -1,4 +1,5 @@ // bridge-js: skip +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift index 4a87a6d38..6c9960b02 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift @@ -1,3 +1,4 @@ +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 056c1c27d..920f2cc2f 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -1,4 +1,5 @@ // bridge-js: skip +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift index 8a4171718..cb6e0d0b0 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift @@ -17,6 +17,7 @@ public enum BridgeJSGeneratedFile { // The generated Swift file itself should not be processed by BridgeJS again. """ \(skipLine) + // swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js index 17086e92e..c5e89c208 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js @@ -149,6 +149,7 @@ export function run(filePaths, options) { } const prelude = [ + "// swift-format-ignore-file", "// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit,", "// DO NOT EDIT.", "//", diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap index 643ac8441..0cb0e3206 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap @@ -1,7 +1,8 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`ts2swift > snapshots Swift output for ArrayParameter.d.ts > ArrayParameter 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -24,7 +25,8 @@ exports[`ts2swift > snapshots Swift output for ArrayParameter.d.ts > ArrayParame `; exports[`ts2swift > snapshots Swift output for Async.d.ts > Async 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -49,7 +51,8 @@ exports[`ts2swift > snapshots Swift output for Async.d.ts > Async 1`] = ` `; exports[`ts2swift > snapshots Swift output for CallableConst.d.ts > CallableConst 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -65,7 +68,8 @@ exports[`ts2swift > snapshots Swift output for CallableConst.d.ts > CallableCons `; exports[`ts2swift > snapshots Swift output for Documentation.d.ts > Documentation 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -122,7 +126,8 @@ exports[`ts2swift > snapshots Swift output for Documentation.d.ts > Documentatio `; exports[`ts2swift > snapshots Swift output for ExportAssignment.d.ts > ExportAssignment 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -135,7 +140,8 @@ exports[`ts2swift > snapshots Swift output for ExportAssignment.d.ts > ExportAss `; exports[`ts2swift > snapshots Swift output for Interface.d.ts > Interface 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -153,7 +159,8 @@ exports[`ts2swift > snapshots Swift output for Interface.d.ts > Interface 1`] = `; exports[`ts2swift > snapshots Swift output for InvalidPropertyNames.d.ts > InvalidPropertyNames 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -201,7 +208,8 @@ exports[`ts2swift > snapshots Swift output for InvalidPropertyNames.d.ts > Inval `; exports[`ts2swift > snapshots Swift output for MultipleImportedTypes.d.ts > MultipleImportedTypes 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -238,7 +246,8 @@ exports[`ts2swift > snapshots Swift output for MultipleImportedTypes.d.ts > Mult `; exports[`ts2swift > snapshots Swift output for ObjectLikeTypes.d.ts > ObjectLikeTypes 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -251,7 +260,8 @@ exports[`ts2swift > snapshots Swift output for ObjectLikeTypes.d.ts > ObjectLike `; exports[`ts2swift > snapshots Swift output for OptionalNullUndefined.d.ts > OptionalNullUndefined 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -292,7 +302,8 @@ exports[`ts2swift > snapshots Swift output for OptionalNullUndefined.d.ts > Opti `; exports[`ts2swift > snapshots Swift output for PrimitiveParameters.d.ts > PrimitiveParameters 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -305,7 +316,8 @@ exports[`ts2swift > snapshots Swift output for PrimitiveParameters.d.ts > Primit `; exports[`ts2swift > snapshots Swift output for PrimitiveReturn.d.ts > PrimitiveReturn 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -320,7 +332,8 @@ exports[`ts2swift > snapshots Swift output for PrimitiveReturn.d.ts > PrimitiveR `; exports[`ts2swift > snapshots Swift output for ReExportFrom.d.ts > ReExportFrom 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -338,7 +351,8 @@ exports[`ts2swift > snapshots Swift output for ReExportFrom.d.ts > ReExportFrom `; exports[`ts2swift > snapshots Swift output for RecordDictionary.d.ts > RecordDictionary 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -368,7 +382,8 @@ exports[`ts2swift > snapshots Swift output for RecordDictionary.d.ts > RecordDic `; exports[`ts2swift > snapshots Swift output for StaticProperty.d.ts > StaticProperty 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -384,7 +399,8 @@ exports[`ts2swift > snapshots Swift output for StaticProperty.d.ts > StaticPrope `; exports[`ts2swift > snapshots Swift output for StringEnum.d.ts > StringEnum 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -405,7 +421,8 @@ extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} `; exports[`ts2swift > snapshots Swift output for StringLiteralUnion.d.ts > StringLiteralUnion 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -426,7 +443,8 @@ extension Direction: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} `; exports[`ts2swift > snapshots Swift output for StringParameter.d.ts > StringParameter 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -441,7 +459,8 @@ exports[`ts2swift > snapshots Swift output for StringParameter.d.ts > StringPara `; exports[`ts2swift > snapshots Swift output for StringReturn.d.ts > StringReturn 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -454,7 +473,8 @@ exports[`ts2swift > snapshots Swift output for StringReturn.d.ts > StringReturn `; exports[`ts2swift > snapshots Swift output for TS2SkeletonLike.d.ts > TS2SkeletonLike 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -480,7 +500,8 @@ exports[`ts2swift > snapshots Swift output for TS2SkeletonLike.d.ts > TS2Skeleto `; exports[`ts2swift > snapshots Swift output for TypeAlias.d.ts > TypeAlias 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -493,7 +514,8 @@ exports[`ts2swift > snapshots Swift output for TypeAlias.d.ts > TypeAlias 1`] = `; exports[`ts2swift > snapshots Swift output for TypeAliasObject.d.ts > TypeAliasObject 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -512,7 +534,8 @@ exports[`ts2swift > snapshots Swift output for TypeAliasObject.d.ts > TypeAliasO `; exports[`ts2swift > snapshots Swift output for TypeScriptClass.d.ts > TypeScriptClass 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -533,7 +556,8 @@ exports[`ts2swift > snapshots Swift output for TypeScriptClass.d.ts > TypeScript `; exports[`ts2swift > snapshots Swift output for VoidParameterVoidReturn.d.ts > VoidParameterVoidReturn 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run @@ -546,7 +570,8 @@ exports[`ts2swift > snapshots Swift output for VoidParameterVoidReturn.d.ts > Vo `; exports[`ts2swift > snapshots Swift output for WebIDLDOMDocs.d.ts > WebIDLDOMDocs 1`] = ` -"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +"// swift-format-ignore-file +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // // To update this file, just rebuild your project or run diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json index e602989a1..f6c0c6fe1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.json @@ -281,5 +281,8 @@ } ] }, - "moduleName" : "TestModule" + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] } \ No newline at end of file diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index 862debbf0..4e35a1c9f 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -1,4 +1,5 @@ // bridge-js: skip +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift index ffab42367..72a8dfdd4 100644 --- a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift @@ -1,4 +1,5 @@ // bridge-js: skip +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift index e3a6eec61..08d0db2a7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift @@ -1,3 +1,4 @@ +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index db8962089..4d920873d 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -1,4 +1,5 @@ // bridge-js: skip +// swift-format-ignore-file // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. // From 6eb6668f78a3d2b8e852c83c9e565a1c75d9dd89 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 30 Apr 2026 13:06:10 +0200 Subject: [PATCH 055/140] BridgeJS: Support nested @JS types inside structs and classes --- .../BridgeJSCore/SwiftToSkeleton.swift | 77 ++++- .../JSClassMacroTests.swift | 58 ++++ .../BridgeJSToolTests/DiagnosticsTests.swift | 69 ++++ .../Inputs/MacroSwift/NestedType.swift | 10 + .../BridgeJSCodegenTests/NestedType.json | 89 +++++ .../BridgeJSCodegenTests/NestedType.swift | 89 +++++ .../BridgeJSLinkTests/NestedType.d.ts | 33 ++ .../BridgeJSLinkTests/NestedType.js | 304 ++++++++++++++++++ 8 files changed, 717 insertions(+), 12 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 61306bf2c..209242e79 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -504,6 +504,14 @@ public final class SwiftToSkeleton { enumDecl.attributes.hasJSAttribute() { swiftPath.insert(enumDecl.name.text, at: 0) + } else if let structDecl = parent.as(StructDeclSyntax.self), + structDecl.attributes.hasJSAttribute() + { + swiftPath.insert(structDecl.name.text, at: 0) + } else if let classDecl = parent.as(ClassDeclSyntax.self), + classDecl.attributes.hasJSAttribute() + { + swiftPath.insert(classDecl.name.text, at: 0) } currentNode = parent.parent } @@ -648,6 +656,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { var state: State { return stateStack.current } + let parent: SwiftToSkeleton init(parent: SwiftToSkeleton) { @@ -1453,6 +1462,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } + let effectiveNamespace = effectiveNamespace( + resolvedNamespace: namespaceResult.namespace, + parentTypeNamespace: computeParentTypeNamespace(for: node) + ) let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, @@ -1466,10 +1479,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { constructor: nil, methods: [], properties: [], - namespace: namespaceResult.namespace, + namespace: effectiveNamespace, identityMode: classIdentityMode ) - let uniqueKey = makeKey(name: name, namespace: namespaceResult.namespace) + let uniqueKey = makeKey(name: name, namespace: effectiveNamespace) stateStack.push(state: .classBody(name: name, key: uniqueKey)) exportedClassByName[uniqueKey] = exportedClass @@ -1558,6 +1571,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } + let effectiveNamespace = effectiveNamespace( + resolvedNamespace: namespaceResult.namespace, + parentTypeNamespace: computeParentTypeNamespace(for: node) + ) let emitStyle = extractEnumStyle(from: jsAttribute) ?? .const let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( @@ -1566,7 +1583,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { ) let tsFullPath: String - if let namespace = namespaceResult.namespace, !namespace.isEmpty { + if let namespace = effectiveNamespace, !namespace.isEmpty { tsFullPath = namespace.joined(separator: ".") + "." + name } else { tsFullPath = name @@ -1580,13 +1597,13 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { explicitAccessControl: explicitAccessControl, cases: [], // Will be populated in visit(EnumCaseDeclSyntax) rawType: SwiftEnumRawType(rawType), - namespace: namespaceResult.namespace, + namespace: effectiveNamespace, emitStyle: emitStyle, staticMethods: [], staticProperties: [] ) - let enumUniqueKey = makeKey(name: name, namespace: namespaceResult.namespace) + let enumUniqueKey = makeKey(name: name, namespace: effectiveNamespace) exportedEnumByName[enumUniqueKey] = exportedEnum exportedEnumNames.append(enumUniqueKey) @@ -1685,18 +1702,22 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } + let effectiveNamespace = effectiveNamespace( + resolvedNamespace: namespaceResult.namespace, + parentTypeNamespace: computeParentTypeNamespace(for: node) + ) _ = computeExplicitAtLeastInternalAccessControl( for: node, message: "Protocol visibility must be at least internal" ) - let protocolUniqueKey = makeKey(name: name, namespace: namespaceResult.namespace) + let protocolUniqueKey = makeKey(name: name, namespace: effectiveNamespace) exportedProtocolByName[protocolUniqueKey] = ExportedProtocol( name: name, methods: [], properties: [], - namespace: namespaceResult.namespace + namespace: effectiveNamespace ) stateStack.push(state: .protocolBody(name: name, key: protocolUniqueKey)) @@ -1707,7 +1728,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { if let exportedFunction = visitProtocolMethod( node: funcDecl, protocolName: name, - namespace: namespaceResult.namespace + namespace: effectiveNamespace ) { methods.append(exportedFunction) } @@ -1720,7 +1741,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { name: name, methods: methods, properties: exportedProtocolByName[protocolUniqueKey]?.properties ?? [], - namespace: namespaceResult.namespace + namespace: effectiveNamespace ) exportedProtocolByName[protocolUniqueKey] = exportedProtocol @@ -1742,6 +1763,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } + let effectiveNamespace = effectiveNamespace( + resolvedNamespace: namespaceResult.namespace, + parentTypeNamespace: computeParentTypeNamespace(for: node) + ) let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, @@ -1791,7 +1816,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { type: fieldType, isReadonly: true, isStatic: false, - namespace: namespaceResult.namespace, + namespace: effectiveNamespace, staticContext: nil ) properties.append(property) @@ -1799,14 +1824,14 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } - let structUniqueKey = makeKey(name: name, namespace: namespaceResult.namespace) + let structUniqueKey = makeKey(name: name, namespace: effectiveNamespace) let exportedStruct = ExportedStruct( name: name, swiftCallName: swiftCallName, explicitAccessControl: explicitAccessControl, properties: properties, methods: [], - namespace: namespaceResult.namespace + namespace: effectiveNamespace ) exportedStructByName[structUniqueKey] = exportedStruct @@ -2035,6 +2060,34 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return namespace.isEmpty ? nil : namespace } + 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), + structDecl.attributes.hasJSAttribute() + { + path.insert(structDecl.name.text, at: 0) + } else if let classDecl = parent.as(ClassDeclSyntax.self), + classDecl.attributes.hasJSAttribute() + { + path.insert(classDecl.name.text, at: 0) + } + currentNode = parent.parent + } + + return path.isEmpty ? nil : path + } + + private func effectiveNamespace( + resolvedNamespace: [String]?, + parentTypeNamespace: [String]? + ) -> [String]? { + let combined = (parentTypeNamespace ?? []) + (resolvedNamespace ?? []) + return combined.isEmpty ? nil : combined + } + /// Requires the node to have at least internal access control. private func computeExplicitAtLeastInternalAccessControl( for node: some WithModifiersSyntax, diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift index 77dc814eb..c52bc9db0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift @@ -445,6 +445,64 @@ import BridgeJSMacros ) } + @Test func nestedJSClassStruct() { + let combinedSpecs: [String: MacroSpec] = [ + "JSClass": MacroSpec(type: JSClassMacro.self, conformances: ["_JSBridgedClass"]), + "JSGetter": MacroSpec(type: JSGetterMacro.self), + ] + TestSupport.assertMacroExpansion( + """ + @JSClass + struct User { + @JSGetter + var stats: Stats + + @JSClass + struct Stats { + @JSGetter + var health: Int + } + } + """, + expandedSource: """ + struct User { + var stats: Stats { + get throws(JSException) { + return try _$User_stats_get(self.jsObject) + } + } + struct Stats { + var health: Int { + get throws(JSException) { + return try _$Stats_health_get(self.jsObject) + } + } + + let jsObject: JSObject + + init(unsafelyWrapping jsObject: JSObject) { + self.jsObject = jsObject + } + } + + let jsObject: JSObject + + init(unsafelyWrapping jsObject: JSObject) { + self.jsObject = jsObject + } + } + + extension User.Stats: _JSBridgedClass { + } + + extension User: _JSBridgedClass { + } + """, + macroSpecs: combinedSpecs, + indentationWidth: indentationWidth + ) + } + @Test func fileprivateStructIsRejected() { TestSupport.assertMacroExpansion( """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 500a5db95..869bb2d3e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -165,6 +165,75 @@ import Testing #expect(description.contains(":2:")) } + // MARK: - Nested type validation + + @Test + func nestedStructInsideClassSucceeds() throws { + let source = """ + @JS class User { + @JS struct Stats { + var health: Int + } + } + """ + 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() + #expect(skeleton.exported != nil) + let structs = skeleton.exported?.structs ?? [] + #expect(structs.count == 1) + #expect(structs.first?.swiftCallName == "User.Stats") + } + + @Test + func nestedClassInsideStructSucceeds() throws { + let source = """ + @JS struct Container { + var value: Int + @JS class Inner { + } + } + """ + 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() + #expect(skeleton.exported != nil) + let classes = skeleton.exported?.classes ?? [] + #expect(classes.count == 1) + #expect(classes.first?.swiftCallName == "Container.Inner") + } + + @Test + func structInsideEnumNamespaceSucceeds() throws { + let source = """ + @JS enum API { + @JS struct Point { + var x: Double + var y: Double + } + } + """ + 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() + #expect(skeleton.exported != nil) + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift new file mode 100644 index 000000000..bd2bcc4fe --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift @@ -0,0 +1,10 @@ +@JS class User { + @JS func getName() -> String { + return "test" + } + + @JS struct Stats { + var health: Int + var score: Double + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json new file mode 100644 index 000000000..e8666bbc4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json @@ -0,0 +1,89 @@ +{ + "exported" : { + "classes" : [ + { + "methods" : [ + { + "abiName" : "bjs_User_getName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getName", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "User", + "properties" : [ + + ], + "swiftCallName" : "User" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Stats", + "namespace" : [ + "User" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "health", + "namespace" : [ + "User" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "score", + "namespace" : [ + "User" + ], + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "User.Stats" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ 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 new file mode 100644 index 000000000..35ead0856 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -0,0 +1,89 @@ +extension User.Stats: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> User.Stats { + let score = Double.bridgeJSStackPop() + let health = Int.bridgeJSStackPop() + return User.Stats(health: health, score: score) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.health.bridgeJSStackPush() + self.score.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_User_Stats(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_User_Stats())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_User_Stats") +fileprivate func _bjs_struct_lower_User_Stats_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_User_Stats_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_User_Stats(_ objectId: Int32) -> Void { + return _bjs_struct_lower_User_Stats_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_User_Stats") +fileprivate func _bjs_struct_lift_User_Stats_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_User_Stats_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_User_Stats() -> Int32 { + return _bjs_struct_lift_User_Stats_extern() +} + +@_expose(wasm, "bjs_User_getName") +@_cdecl("bjs_User_getName") +public func _bjs_User_getName(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = User.bridgeJSLiftParameter(_self).getName() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_User_deinit") +@_cdecl("bjs_User_deinit") +public func _bjs_User_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension User: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_User_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_User_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_User_wrap") +fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_User_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_User_wrap_extern(pointer) +} \ 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 new file mode 100644 index 000000000..2d3942e06 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.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 interface Stats { + health: number; + score: 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 User extends SwiftHeapObject { + getName(): string; +} +export type Exports = { + User: { + } +} +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/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js new file mode 100644 index 000000000..cf24e7e2d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.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 = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStatsHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.health | 0)); + f64Stack.push(value.score); + }, + lift: () => { + const f64 = f64Stack.pop(); + const int = i32Stack.pop(); + return { health: int, score: 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); + 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(); + } + bjs["swift_js_struct_lower_User_Stats"] = function(objectId) { + structHelpers.Stats.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_User_Stats"] = function() { + const value = structHelpers.Stats.lift(); + return swift.memory.retain(value); + } + 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_User_wrap"] = function(pointer) { + const obj = _exports['User'].__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 User extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_User_deinit, User.prototype, null); + } + + getName() { + instance.exports.bjs_User_getName(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + } + const StatsHelpers = __bjs_createStatsHelpers(); + structHelpers.Stats = StatsHelpers; + + const exports = { + User, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file From f90fe98ca77f356af4041da967831068262a1d7b Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 30 Apr 2026 12:28:05 +0200 Subject: [PATCH 056/140] BridgeJS: Diagnose struct initializer parameter order mismatch --- .../BridgeJSCore/SwiftToSkeleton.swift | 37 +++++++++- .../BridgeJSToolTests/DiagnosticsTests.swift | 71 +++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 209242e79..f39ac16f8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1843,11 +1843,46 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } override func visitPost(_ node: StructDeclSyntax) { - if case .structBody(_, _) = stateStack.current { + if case .structBody(_, let structKey) = stateStack.current { stateStack.pop() + validateStructInitOrder(node: node, structKey: structKey) } } + private func validateStructInitOrder(node: StructDeclSyntax, structKey: String) { + guard let exportedStruct = exportedStructByName[structKey], + let constructor = exportedStruct.constructor + else { + // No explicit @JS init — synthesized memberwise init is assumed, + // which always matches declaration order. + return + } + + let instanceProps = exportedStruct.properties.filter { !$0.isStatic } + let expectedLabels = instanceProps.map(\.name) + let actualLabels = constructor.parameters.compactMap(\.label) + + guard expectedLabels != actualLabels else { return } + + // Find the @JS init node so we can point the diagnostic at it. + let initNode: (any SyntaxProtocol) = + node.memberBlock.members + .compactMap { $0.decl.as(InitializerDeclSyntax.self) } + .first(where: { $0.attributes.hasJSAttribute() }) + ?? node + + let expectedOrder = expectedLabels.joined(separator: ", ") + let actualOrder = actualLabels.joined(separator: ", ") + + diagnose( + node: initNode, + message: + "@JS struct initializer parameters must match stored properties in declaration order. Expected (\(expectedOrder)), got (\(actualOrder))", + hint: + "Reorder the initializer parameters to match the property declaration order, or remove the @JS init to use the synthesized memberwise initializer" + ) + } + private func visitProtocolMethod( node: FunctionDeclSyntax, protocolName: String, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 869bb2d3e..e71a1f84e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -3,6 +3,7 @@ import SwiftSyntax import Testing @testable import BridgeJSCore +@testable import BridgeJSSkeleton @Suite struct DiagnosticsTests { /// Returns the first parameter's type node from a function in the source (the first `@JS func`-like decl), for pinpointing diagnostics. @@ -234,6 +235,76 @@ import Testing #expect(skeleton.exported != nil) } + // MARK: - Struct init order validation + + @Test + func structInitMismatchedOrderProducesDiagnostic() throws { + let source = """ + @JS struct Animal { + var size: Double + var age: Int + + @JS init(age: Int, size: Double) { + self.age = age + self.size = size + } + } + """ + 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 structInitMatchingOrderSucceeds() throws { + let source = """ + @JS struct Point { + var x: Double + var y: Double + + @JS init(x: Double, y: Double) { + self.x = x + self.y = y + } + } + """ + 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() + #expect(skeleton.exported != nil) + } + + @Test + func structWithoutExplicitInitSucceeds() throws { + let source = """ + @JS struct Point { + var x: Double + var y: Double + } + """ + 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() + #expect(skeleton.exported != nil) + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ From 549b727240775adcacf2dae0bedafaf5ee36b5e2 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Mon, 4 May 2026 15:39:11 +1000 Subject: [PATCH 057/140] BridgeJS: Fix closures with struct return --- .../Inputs/MacroSwift/SwiftClosure.swift | 11 + .../BridgeJSCodegenTests/SwiftClosure.json | 184 ++++++++++++++++ .../BridgeJSCodegenTests/SwiftClosure.swift | 205 ++++++++++++++++++ .../BridgeJSLinkTests/SwiftClosure.d.ts | 8 + .../BridgeJSLinkTests/SwiftClosure.js | 106 +++++++++ .../JavaScriptKit/BridgeJSIntrinsics.swift | 4 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 12 + .../Generated/BridgeJS.swift | 148 +++++++++++++ .../Generated/JavaScript/BridgeJS.json | 93 ++++++++ .../JavaScript/ClosureSupportTests.mjs | 11 + 10 files changed, 782 insertions(+) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift index 791b1b7a9..6872d7989 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift @@ -8,10 +8,21 @@ import JavaScriptKit } } +@JS public struct Animal { + public let type: String + + @JS public init(type: String) { + self.type = type + } +} + @JS class TestProcessor { @JS init(transform: @escaping (String) -> String) {} } +@JS func roundtripAnimal(_ animalClosure: (Animal) -> Animal) -> (Animal) -> Animal +@JS func roundtripOptionalAnimal(_ animalClosure: (Animal?) -> Animal?) -> (Animal?) -> Animal? + @JS func roundtripString(_ stringClosure: (String) -> String) -> (String) -> String @JS func roundtripInt(_ intClosure: (Int) -> Int) -> (Int) -> Int @JS func roundtripBool(_ boolClosure: (Bool) -> Bool) -> (Bool) -> Bool diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index abca80150..ac18f6dc2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -284,6 +284,152 @@ ], "exposeToGlobal" : false, "functions" : [ + { + "abiName" : "bjs_roundtripAnimal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripAnimal", + "parameters" : [ + { + "label" : "_", + "name" : "animalClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule6AnimalV_6AnimalV", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftStruct" : { + "_0" : "Animal" + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule6AnimalV_6AnimalV", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftStruct" : { + "_0" : "Animal" + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalAnimal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalAnimal", + "parameters" : [ + { + "label" : "_", + "name" : "animalClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq6AnimalV_Sq6AnimalV", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "_1" : "null" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq6AnimalV_Sq6AnimalV", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "_1" : "null" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + }, { "abiName" : "bjs_roundtripString", "effects" : { @@ -1872,7 +2018,45 @@ ], "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Animal_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "type", + "name" : "type", + "type" : { + "string" : { + } + } + } + ] + }, + "explicitAccessControl" : "public", + "methods" : [ + + ], + "name" : "Animal", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "type", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Animal" + } ] }, "moduleName" : "TestModule", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index 348f9a788..4eb7c8da4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -127,6 +127,69 @@ public func _invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO(_ boxPt #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV") +fileprivate func invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV") +fileprivate func make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule6AnimalV_6AnimalV { + static func bridgeJSLift(_ callbackId: Int32) -> (Animal) -> Animal { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV(callbackValue) + return Animal.bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Animal) -> Animal { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Animal) -> Animal) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV") +@_cdecl("invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV") +public func _invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Animal) -> Animal>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Animal.bridgeJSLiftParameter()) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC") fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer @@ -761,6 +824,69 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ b #endif } +#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 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ callback: Int32, _ param0: 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) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV") +fileprivate func make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0IsSome = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(callbackValue, param0IsSome) + return Optional.bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV") +public func _invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter()) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC") fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer @@ -1358,6 +1484,85 @@ extension APIResult: _BridgedSwiftAssociatedValueEnum { } } +extension Animal: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Animal { + let type = String.bridgeJSStackPop() + return Animal(type: type) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.type.bridgeJSStackPush() + } + + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Animal(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + public func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Animal())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Animal") +fileprivate func _bjs_struct_lower_Animal_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Animal_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Animal(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Animal_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Animal") +fileprivate func _bjs_struct_lift_Animal_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Animal_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Animal() -> Int32 { + return _bjs_struct_lift_Animal_extern() +} + +@_expose(wasm, "bjs_Animal_init") +@_cdecl("bjs_Animal_init") +public func _bjs_Animal_init(_ typeBytes: Int32, _ typeLength: Int32) -> Void { + #if arch(wasm32) + let ret = Animal(type: String.bridgeJSLiftParameter(typeBytes, typeLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripAnimal") +@_cdecl("bjs_roundtripAnimal") +public func _bjs_roundtripAnimal(_ animalClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripAnimal(_: _BJS_Closure_10TestModule6AnimalV_6AnimalV.bridgeJSLift(animalClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalAnimal") +@_cdecl("bjs_roundtripOptionalAnimal") +public func _bjs_roundtripOptionalAnimal(_ animalClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalAnimal(_: _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV.bridgeJSLift(animalClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundtripString") @_cdecl("bjs_roundtripString") public func _bjs_roundtripString(_ stringClosure: 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 ccc95eb3b..a0cbe6c4e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -41,6 +41,9 @@ export const APIResultValues: { export type APIResultTag = { tag: typeof APIResultValues.Tag.Success; param0: string } | { tag: typeof APIResultValues.Tag.Failure; param0: number } | { tag: typeof APIResultValues.Tag.Flag; param0: boolean } | { tag: typeof APIResultValues.Tag.Rate; param0: number } | { tag: typeof APIResultValues.Tag.Precise; param0: number } | { tag: typeof APIResultValues.Tag.Info } +export interface Animal { + type: string; +} export type DirectionObject = typeof DirectionValues; export type ThemeObject = typeof ThemeValues; @@ -67,6 +70,8 @@ export type Exports = { TestProcessor: { new(transform: (arg0: string) => string): TestProcessor; } + roundtripAnimal(animalClosure: (arg0: AnimalTag) => AnimalTag): (arg0: AnimalTag) => AnimalTag; + roundtripOptionalAnimal(animalClosure: (arg0: AnimalTag | null) => AnimalTag | null): (arg0: AnimalTag | null) => AnimalTag | null; roundtripString(stringClosure: (arg0: string) => string): (arg0: string) => string; roundtripInt(intClosure: (arg0: number) => number): (arg0: number) => number; roundtripBool(boolClosure: (arg0: boolean) => boolean): (arg0: boolean) => boolean; @@ -92,6 +97,9 @@ export type Exports = { Theme: ThemeObject HttpStatus: HttpStatusObject APIResult: APIResultObject + Animal: { + init(type: string): Animal; + } } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 03a5504e4..0b4ca3dcc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -85,6 +85,18 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(real); }; + const __bjs_createAnimalHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.type); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { type: string }; + } + }); const __bjs_createAPIResultValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; @@ -214,6 +226,13 @@ export async function createInstantiator(options, swift) { bjs["swift_js_pop_i64"] = function() { return i64Stack.pop(); } + bjs["swift_js_struct_lower_Animal"] = function(objectId) { + structHelpers.Animal.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Animal"] = function() { + const value = structHelpers.Animal.lift(); + return swift.memory.retain(value); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -359,6 +378,31 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule5ThemeO_5ThemeO); } + bjs["invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + const structValue = structHelpers.Animal.lift(); + let ret = callback(structValue); + structHelpers.Animal.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); + instance.exports.invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(boxPtr); + const structValue = structHelpers.Animal.lift(); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return structValue; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule6AnimalV_6AnimalV); + } bjs["invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); @@ -620,6 +664,46 @@ 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) { + try { + const callback = swift.memory.getObject(callbackId); + let optResult; + if (param0) { + const struct = structHelpers.Animal.lift(); + optResult = struct; + } else { + optResult = null; + } + let ret = callback(optResult); + const isSome = ret != null; + if (isSome) { + structHelpers.Animal.lower(ret); + } + i32Stack.push(isSome ? 1 : 0); + } 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); + instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(boxPtr); + const isSome1 = i32Stack.pop(); + const optResult = isSome1 ? structHelpers.Animal.lift() : null; + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV); + } bjs["invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC"] = function(callbackId, param0IsSome, param0Pointer) { try { const callback = swift.memory.getObject(callbackId); @@ -971,12 +1055,25 @@ export async function createInstantiator(options, swift) { return TestProcessor.__construct(ret); } } + const AnimalHelpers = __bjs_createAnimalHelpers(); + structHelpers.Animal = AnimalHelpers; + const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); 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); + return swift.memory.getObject(ret); + }, + roundtripOptionalAnimal: function bjs_roundtripOptionalAnimal(animalClosure) { + const callbackId = swift.memory.retain(animalClosure); + const ret = instance.exports.bjs_roundtripOptionalAnimal(callbackId); + return swift.memory.getObject(ret); + }, roundtripString: function bjs_roundtripString(stringClosure) { const callbackId = swift.memory.retain(stringClosure); const ret = instance.exports.bjs_roundtripString(callbackId); @@ -1086,6 +1183,15 @@ export async function createInstantiator(options, swift) { Theme: ThemeValues, HttpStatus: HttpStatusValues, APIResult: APIResultValues, + Animal: { + init: function(type) { + const typeBytes = textEncoder.encode(type); + const typeId = swift.memory.retain(typeBytes); + instance.exports.bjs_Animal_init(typeId, typeBytes.length); + const structValue = structHelpers.Animal.lift(); + return structValue; + }, + }, }; _exports = exports; return exports; diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 867d0e835..2a18401b4 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -847,6 +847,10 @@ extension _BridgedSwiftStruct { return Self(unsafelyCopying: jsObject) } + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { + bridgeJSStackPop() + } + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { bridgeJSStackPop() } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 2562fe18e..c81622f0d 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1285,6 +1285,18 @@ enum GraphOperations { processor.increment(by: 7) return callback(processor) + " | " + callback(nil) } + + @JS func processVector(_ callback: (Double) -> Vector2D) -> Double { + return callback(3.0).magnitude() + } + + @JS func processOptionalVector(_ callback: (Double) -> Vector2D?) -> String { + let some = callback(2.0) + let none = callback(-1.0) + let someStr = some.map { "(\($0.dx),\($0.dy))" } ?? "nil" + let noneStr = none.map { "(\($0.dx),\($0.dy))" } ?? "nil" + return "\(someStr) | \(noneStr)" + } } class ExportAPITests: XCTestCase { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 4d920873d..771838716 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -776,6 +776,69 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(_ callback: Int32, _ param0: Float64) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(_ callback: Int32, _ param0: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_8Vector2DV { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) -> Vector2D { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(callbackValue, param0Value) + return Vector2D.bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Double) -> Vector2D { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) -> Vector2D) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Vector2D>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Double.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(_ callback: Int32, _ param0: Float64) -> Float64 @@ -839,6 +902,69 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_ #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(_ callback: Int32, _ param0: Float64) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(_ callback: Int32, _ param0: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_Sq8Vector2DV { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(callbackValue, param0Value) + return Optional.bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Double) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) -> Optional) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Double.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 @@ -10442,6 +10568,28 @@ public func _bjs_TextProcessor_processOptionalDataProcessor(_ _self: UnsafeMutab #endif } +@_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 + fatalError("Only available on WebAssembly") + #endif +} + +@_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 + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_TextProcessor_deinit") @_cdecl("bjs_TextProcessor_deinit") public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index d9108f2e7..7a3e7f7fe 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -4057,6 +4057,99 @@ "returnType" : { "string" : { + } + } + }, + { + "abiName" : "bjs_TextProcessor_processVector", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processVector", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_8Vector2DV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_TextProcessor_processOptionalVector", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalVector", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_Sq8Vector2DV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + }, + "_1" : "null" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + } } } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs index ebe00548b..bab496d09 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs @@ -355,6 +355,17 @@ export function runJsClosureSupportTests(exports) { }); assert.equal(optDpResult, "DP: 7 | DP: null"); + const vectorMagnitude = processor.processVector((value) => ({ + dx: value, + dy: 4.0, + })); + assert.equal(vectorMagnitude, 5.0); + + const optVectorResult = processor.processOptionalVector((value) => + value > 0 ? { dx: value, dy: value * 2 } : null, + ); + assert.equal(optVectorResult, "(2.0,4.0) | nil"); + processor.release(); const intToInt = exports.ClosureSupportExports.makeIntToInt(10); From f8b2c96fdb82dcb4d8074297668ca098b3620819 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 4 May 2026 15:11:42 +0200 Subject: [PATCH 058/140] BridgeJS: Fix optionals build error with Embedded Swift (#734) Remove @_spi(BridgeJS) from _BridgedAsOptional protocol and its Optional/JSUndefinedOr conformances so the conformances are visible in Embedded Swift mode. The underscore-prefixed protocol name already signals internal API, and all extension methods remain @_spi-gated. Fixes #689 --- Sources/JavaScriptKit/BridgeJSIntrinsics.swift | 4 ++-- Sources/JavaScriptKit/JSUndefinedOr.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 867d0e835..07e021be9 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -182,13 +182,13 @@ extension _BridgedSwiftStackType { /// Types that bridge with the same (isSome, value) ABI as Optional. /// Used by JSUndefinedOr so all bridge methods delegate to Optional. -@_spi(BridgeJS) public protocol _BridgedAsOptional { +public protocol _BridgedAsOptional { associatedtype Wrapped var asOptional: Wrapped? { get } init(optional: Wrapped?) } -@_spi(BridgeJS) extension Optional: _BridgedAsOptional { +extension Optional: _BridgedAsOptional { public var asOptional: Wrapped? { self } public init(optional: Wrapped?) { self = optional } } diff --git a/Sources/JavaScriptKit/JSUndefinedOr.swift b/Sources/JavaScriptKit/JSUndefinedOr.swift index c4d601738..de7be09b4 100644 --- a/Sources/JavaScriptKit/JSUndefinedOr.swift +++ b/Sources/JavaScriptKit/JSUndefinedOr.swift @@ -53,4 +53,4 @@ extension JSUndefinedOr: ConvertibleToJSValue where Wrapped: ConvertibleToJSValu // MARK: - BridgeJS (via _BridgedAsOptional in BridgeJSIntrinsics) -@_spi(BridgeJS) extension JSUndefinedOr: _BridgedAsOptional {} +extension JSUndefinedOr: _BridgedAsOptional {} From 43ed78f06d3ee4505f52f034595041c4bb446f87 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 4 May 2026 15:23:41 +0200 Subject: [PATCH 059/140] BridgeJS: Move optional JSObject to stack ABI, enabling Optional<@JSClass> (#738) --- .../Sources/BridgeJSCore/ImportTS.swift | 8 ++- .../Sources/BridgeJSLink/JSGlueGen.swift | 4 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 4 +- .../Inputs/MacroSwift/Optionals.swift | 6 ++ .../BridgeJSCodegenTests/Optionals.json | 63 ++++++++++++++++++ .../BridgeJSCodegenTests/Optionals.swift | 64 +++++++++++++++++++ .../BridgeJSLinkTests/Optionals.d.ts | 2 + .../BridgeJSLinkTests/Optionals.js | 51 +++++++++++++++ .../JavaScriptKit/BridgeJSIntrinsics.swift | 6 +- 9 files changed, 198 insertions(+), 10 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 536c7eeab..d491c4058 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -128,7 +128,9 @@ public struct ImportTS { self.returnType = returnType self.context = context let liftingInfo = try returnType.liftingReturnInfo(context: context) - if effects.isAsync || returnType == .void || returnType.usesSideChannelForOptionalReturn() { + if effects.isAsync || returnType == .void || returnType.usesSideChannelForOptionalReturn() + || liftingInfo.valueToLift == nil + { abiReturnType = nil } else { abiReturnType = liftingInfo.valueToLift @@ -1032,6 +1034,10 @@ 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 + if case .jsObject = wrappedType { + 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 599b6df39..1ad397f71 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2648,7 +2648,7 @@ private extension BridgeType { case .string: return .sideChannelReturn(.storage) case .jsObject: - return .sideChannelReturn(.retainedObject) + return .stackABI case .jsValue: return .inlineFlag case .swiftHeapObject: @@ -2685,7 +2685,7 @@ private extension BridgeType { var nilSentinel: NilSentinel { switch self { - case .jsObject, .swiftProtocol: + case .swiftProtocol: return .i32(0) case .swiftHeapObject: return .pointer diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 055ef2552..346b7333b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1655,7 +1655,7 @@ extension BridgeType { } switch wrappedType { - case .string, .integer, .float, .double, .jsObject, .swiftProtocol: + case .string, .integer, .float, .double, .swiftProtocol: return true case .rawValueEnum(_, let rawType): switch rawType { @@ -1666,7 +1666,7 @@ extension BridgeType { default: return false } - case .bool, .caseEnum, .swiftHeapObject, .associatedValueEnum: + case .bool, .caseEnum, .swiftHeapObject, .associatedValueEnum, .jsObject: return false default: return false diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift index 927fac6a0..5df48d9c0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift @@ -155,4 +155,10 @@ func testMixedOptionals(firstName: String?, lastName: String?, age: Int?, active @JSSetter func setIntOrUndefined(_ value: JSUndefinedOr) throws(JSException) @JSFunction func roundTripIntOrNull(value: Int?) throws(JSException) -> Int? @JSFunction func roundTripIntOrUndefined(value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + + @JSGetter var childOrNull: WithOptionalJSClass? + @JSSetter func setChildOrNull(_ value: WithOptionalJSClass?) throws(JSException) + @JSFunction func roundTripChildOrNull( + value: WithOptionalJSClass? + ) throws(JSException) -> WithOptionalJSClass? } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 921983115..91291c24e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -1158,6 +1158,20 @@ "_1" : "undefined" } } + }, + { + "accessLevel" : "internal", + "name" : "childOrNull", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } } ], "methods" : [ @@ -1444,6 +1458,40 @@ "_1" : "undefined" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundTripChildOrNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } } ], "name" : "WithOptionalJSClass", @@ -1573,6 +1621,21 @@ "_1" : "undefined" } } + }, + { + "accessLevel" : "internal", + "functionName" : "childOrNull_set", + "name" : "childOrNull", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } } ], "staticMethods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index 0c6a79bf5..0a2528340 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -526,6 +526,18 @@ fileprivate func bjs_WithOptionalJSClass_intOrUndefined_get_extern(_ self: Int32 return bjs_WithOptionalJSClass_intOrUndefined_get_extern(self) } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_childOrNull_get") +fileprivate func bjs_WithOptionalJSClass_childOrNull_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_childOrNull_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_childOrNull_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_childOrNull_get_extern(self) +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrNull_set") fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void @@ -622,6 +634,18 @@ fileprivate func bjs_WithOptionalJSClass_intOrUndefined_set_extern(_ self: Int32 return bjs_WithOptionalJSClass_intOrUndefined_set_extern(self, newValueIsSome, newValueValue) } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_childOrNull_set") +fileprivate func bjs_WithOptionalJSClass_childOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_childOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_childOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_childOrNull_set_extern(self, newValueIsSome, newValueValue) +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrNull") fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void @@ -718,6 +742,18 @@ fileprivate func bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(_ self: return bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(self, valueIsSome, valueValue) } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripChildOrNull") +fileprivate func bjs_WithOptionalJSClass_roundTripChildOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripChildOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripChildOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripChildOrNull_extern(self, valueIsSome, valueValue) +} + func _$WithOptionalJSClass_init(_ valueOrNull: Optional, _ valueOrUndefined: JSUndefinedOr) throws(JSException) -> JSObject { let ret0 = valueOrNull.bridgeJSWithLoweredParameter { (valueOrNullIsSome, valueOrNullBytes, valueOrNullLength) in let ret1 = valueOrUndefined.bridgeJSWithLoweredParameter { (valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) in @@ -805,6 +841,15 @@ func _$WithOptionalJSClass_intOrUndefined_get(_ self: JSObject) throws(JSExcepti return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() } +func _$WithOptionalJSClass_childOrNull_get(_ self: JSObject) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_childOrNull_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() +} + func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in @@ -879,6 +924,15 @@ 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() + bjs_WithOptionalJSClass_childOrNull_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { let selfValue = self.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in @@ -959,4 +1013,14 @@ func _$WithOptionalJSClass_roundTripIntOrUndefined(_ self: JSObject, _ value: JS throw error } return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripChildOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripChildOrNull(selfValue, valueIsSome, valueValue) + 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/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index a5a6e16fb..fb9d68db7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -30,6 +30,7 @@ export interface WithOptionalJSClass { roundTripBoolOrUndefined(value: boolean | undefined): boolean | undefined; roundTripIntOrNull(value: number | null): number | null; roundTripIntOrUndefined(value: number | undefined): number | undefined; + roundTripChildOrNull(value: WithOptionalJSClass | null): WithOptionalJSClass | null; stringOrNull: string | null; stringOrUndefined: string | undefined; doubleOrNull: number | null; @@ -38,6 +39,7 @@ export interface WithOptionalJSClass { boolOrUndefined: boolean | undefined; intOrNull: number | null; intOrUndefined: number | undefined; + childOrNull: WithOptionalJSClass | null; } export type Exports = { Greeter: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 5971c2fa8..1d585ce0b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -296,6 +296,19 @@ export async function createInstantiator(options, swift) { setException(error); } } + 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); + } catch (error) { + setException(error); + } + } TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueBytes, newValueCount) { try { let optResult; @@ -366,6 +379,22 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_WithOptionalJSClass_childOrNull_set"] = function bjs_WithOptionalJSClass_childOrNull_set(self, newValue) { + 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; + } catch (error) { + setException(error); + } + } TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueBytes, valueCount) { try { let optResult; @@ -452,6 +481,28 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, value) { + 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); + const isSome = ret != null; + if (isSome) { + const objId1 = swift.memory.retain(ret); + i32Stack.push(objId1); + } + i32Stack.push(isSome ? 1 : 0); + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 07e021be9..ebad67a4d 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1693,11 +1693,7 @@ extension _BridgedAsOptional where Wrapped == JSObject { } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - asOptional._bridgeJSLowerReturn( - noneValue: 0, - lowerWrapped: { $0.bridgeJSLowerReturn() }, - write: _swift_js_return_optional_object - ) + Wrapped.bridgeJSStackPushAsOptional(asOptional) } } From 4326481aacc61943b10fe5efaa2227b625ffa683 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 5 May 2026 10:13:50 +1000 Subject: [PATCH 060/140] BridgeJS: Fix TypeScript type definition generation for struct arguments --- Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 4 +--- .../__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 64a0d2394..ceaaae8f1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1441,8 +1441,6 @@ public struct BridgeJSLink { } } return type.tsType - case .swiftStruct(let name): - return name.components(separatedBy: ".").last ?? name case .nullable(let wrapped, let kind): let base = resolveTypeScriptType(wrapped, exportedSkeletons: exportedSkeletons) return "\(base) | \(kind.absenceLiteral)" @@ -3612,7 +3610,7 @@ extension BridgeType { case .associatedValueEnum(let name): return "\(name)Tag" case .swiftStruct(let name): - return "\(name)Tag" + return name.components(separatedBy: ".").last ?? name case .namespaceEnum(let name): return name case .swiftProtocol(let name): diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index a0cbe6c4e..d024be7dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -70,8 +70,8 @@ export type Exports = { TestProcessor: { new(transform: (arg0: string) => string): TestProcessor; } - roundtripAnimal(animalClosure: (arg0: AnimalTag) => AnimalTag): (arg0: AnimalTag) => AnimalTag; - roundtripOptionalAnimal(animalClosure: (arg0: AnimalTag | null) => AnimalTag | null): (arg0: AnimalTag | null) => AnimalTag | null; + 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; roundtripInt(intClosure: (arg0: number) => number): (arg0: number) => number; roundtripBool(boolClosure: (arg0: boolean) => boolean): (arg0: boolean) => boolean; From d3f96f43bfd91b027d18086aa645673cb4804d85 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 6 May 2026 18:29:34 +0000 Subject: [PATCH 061/140] Fix cross-thread JSString deinit by wrapping JSObject instead of raw ref JSString.Guts previously held a raw JavaScriptObjectRef and released it unconditionally on whatever thread ran deinit. In the multithreaded Wasm runtime each thread has its own JSObjectSpace, so releasing a ref on the wrong thread caused a TypeError crash (BugSnag: rc property of undefined). JSObject already handles this correctly by capturing ownerTid at init time and routing deinit through swjs_release_remote when destroyed off-thread. This change makes Guts hold a JSObject instead of a raw ref, delegating the correct cross-thread release behaviour to the existing JSObject.deinit path. Adds a regression test testDeinitJSStringOnDifferentThread that reproduces the crash deterministically: it forces JS ref allocation on the main thread via asInternalJSRef(), then drops the last reference on a worker thread. Fixes the crash seen in v292745-rc4 after upgrading to JavaScriptKit 0.50.2. https://claude.ai/code/session_01Qhg5GLXZYNJtH63Gs1SwJH --- .../FundamentalObjects/JSString.swift | 27 ++++++++----------- .../WebWorkerTaskExecutorTests.swift | 25 +++++++++++++++++ 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/Sources/JavaScriptKit/FundamentalObjects/JSString.swift b/Sources/JavaScriptKit/FundamentalObjects/JSString.swift index 4e6a0a085..0eabfa78d 100644 --- a/Sources/JavaScriptKit/FundamentalObjects/JSString.swift +++ b/Sources/JavaScriptKit/FundamentalObjects/JSString.swift @@ -16,25 +16,26 @@ import _CJavaScriptKit /// public struct JSString: LosslessStringConvertible, Equatable { /// The internal representation of JS compatible string - /// The initializers of this type must initialize `jsRef` or `buffer`. + /// The initializers of this type must initialize `jsObject` or `buffer`. /// And the uninitialized one will be lazily initialized class Guts { - var shouldDeallocateRef: Bool = false - lazy var jsRef: JavaScriptObjectRef = { - self.shouldDeallocateRef = true - return buffer.withUTF8 { bufferPtr in + // Owns the JS-side ref via JSObject, whose deinit routes the release to + // the correct thread via swjs_release_remote when destroyed off-owner-thread. + lazy var jsObject: JSObject = { + let ref = buffer.withUTF8 { bufferPtr in return swjs_decode_string(bufferPtr.baseAddress!, Int32(bufferPtr.count)) } + return JSObject(id: ref) // captures ownerTid = current thread here }() lazy var buffer: String = { var bytesRef: JavaScriptObjectRef = 0 - let bytesLength = Int(swjs_encode_string(jsRef, &bytesRef)) + let bytesLength = Int(swjs_encode_string(jsObject.id, &bytesRef)) // +1 for null terminator let buffer = UnsafeMutablePointer.allocate(capacity: bytesLength + 1) defer { buffer.deallocate() - swjs_release(bytesRef) + swjs_release(bytesRef) // bytesRef is a same-thread temporary } swjs_load_string(bytesRef, buffer) buffer[bytesLength] = 0 @@ -46,13 +47,7 @@ public struct JSString: LosslessStringConvertible, Equatable { } init(from jsRef: JavaScriptObjectRef) { - self.jsRef = jsRef - self.shouldDeallocateRef = true - } - - deinit { - guard shouldDeallocateRef else { return } - swjs_release(jsRef) + self.jsObject = JSObject(id: jsRef) } } @@ -79,7 +74,7 @@ public struct JSString: LosslessStringConvertible, Equatable { public static func == (lhs: JSString, rhs: JSString) -> Bool { withExtendedLifetime(lhs.guts) { lhsGuts in withExtendedLifetime(rhs.guts) { rhsGuts in - return swjs_value_equals(lhsGuts.jsRef, rhsGuts.jsRef) + return swjs_value_equals(lhsGuts.jsObject.id, rhsGuts.jsObject.id) } } } @@ -95,6 +90,6 @@ extension JSString: ExpressibleByStringLiteral { extension JSString { func asInternalJSRef() -> JavaScriptObjectRef { - guts.jsRef + guts.jsObject.id } } diff --git a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift index 54559f3d8..69b3390dc 100644 --- a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift +++ b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift @@ -789,5 +789,30 @@ final class WebWorkerTaskExecutorTests: XCTestCase { // await task.value // executor.terminate() // } + + func testDeinitJSStringOnDifferentThread() async throws { + final class Box: @unchecked Sendable { + var string: JSString? + init(_ string: JSString) { self.string = string } + } + + let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1) + defer { executor.terminate() } + + // Force JS ref allocation on the main thread so ownerTid = main thread. + var string: JSString? = JSString("main-thread-owned-key") + _ = string!.asInternalJSRef() + + let box = Box(string!) + string = nil + + // Drop the last reference on a worker — deinit fires on the worker. + // Before the fix this crashed: TypeError: Cannot read properties of undefined (reading 'rc') + let task = Task(executorPreference: executor) { + XCTAssertFalse(isMainThread()) + box.string = nil + } + await task.value + } } #endif From f1f290b40ffff79672fc49fdeef8e770d1976dc9 Mon Sep 17 00:00:00 2001 From: Simon Leeb <52261246+sliemeobn@users.noreply.github.com> Date: Wed, 13 May 2026 09:21:23 +0200 Subject: [PATCH 062/140] faster JSObjectSpace (JS runtime retain / release) (#676) --- Plugins/PackageToJS/Templates/runtime.d.ts | 14 +- Plugins/PackageToJS/Templates/runtime.mjs | 109 ++++++++++----- Runtime/src/object-heap.ts | 125 +++++++++++++----- Tests/JavaScriptKitTests/JSClosureTests.swift | 46 +++---- 4 files changed, 192 insertions(+), 102 deletions(-) diff --git a/Plugins/PackageToJS/Templates/runtime.d.ts b/Plugins/PackageToJS/Templates/runtime.d.ts index 87cbeea72..e4795bedf 100644 --- a/Plugins/PackageToJS/Templates/runtime.d.ts +++ b/Plugins/PackageToJS/Templates/runtime.d.ts @@ -2,14 +2,16 @@ type ref = number; type pointer = number; declare class JSObjectSpace { - private _heapValueById; - private _heapEntryByValue; - private _heapNextKey; + private _slotByValue; + private _values; + private _stateBySlot; + private _freeSlotStack; constructor(); retain(value: any): number; - retainByRef(ref: ref): number; - release(ref: ref): void; - getObject(ref: ref): any; + retainByRef(reference: ref): number; + release(reference: ref): void; + getObject(reference: ref): any; + private _getValidatedSlotState; } /** diff --git a/Plugins/PackageToJS/Templates/runtime.mjs b/Plugins/PackageToJS/Templates/runtime.mjs index ab85e7893..daf4f3ab0 100644 --- a/Plugins/PackageToJS/Templates/runtime.mjs +++ b/Plugins/PackageToJS/Templates/runtime.mjs @@ -241,44 +241,91 @@ function deserializeError(error) { const globalVariable = globalThis; +const SLOT_BITS = 24; +const SLOT_MASK = (1 << SLOT_BITS) - 1; +const GEN_MASK = (1 << (32 - SLOT_BITS)) - 1; class JSObjectSpace { constructor() { - this._heapValueById = new Map(); - this._heapValueById.set(1, globalVariable); - this._heapEntryByValue = new Map(); - this._heapEntryByValue.set(globalVariable, { id: 1, rc: 1 }); + this._slotByValue = new Map(); + this._values = []; + this._stateBySlot = []; + this._freeSlotStack = []; // Note: 0 is preserved for invalid references, 1 is preserved for globalThis - this._heapNextKey = 2; + this._values[0] = undefined; + this._values[1] = globalVariable; + this._slotByValue.set(globalVariable, 1); + this._stateBySlot[1] = 1; // gen=0, rc=1 } retain(value) { - const entry = this._heapEntryByValue.get(value); - if (entry) { - entry.rc++; - return entry.id; - } - const id = this._heapNextKey++; - this._heapValueById.set(id, value); - this._heapEntryByValue.set(value, { id: id, rc: 1 }); - return id; - } - retainByRef(ref) { - return this.retain(this.getObject(ref)); - } - release(ref) { - const value = this._heapValueById.get(ref); - const entry = this._heapEntryByValue.get(value); - entry.rc--; - if (entry.rc != 0) + const slot = this._slotByValue.get(value); + if (slot !== undefined) { + const state = this._stateBySlot[slot]; + const nextState = (state + 1) >>> 0; + if ((nextState & SLOT_MASK) === 0) { + throw new RangeError(`Reference count overflow at slot ${slot}`); + } + this._stateBySlot[slot] = nextState; + return ((nextState & ~SLOT_MASK) | slot) >>> 0; + } + let newSlot; + let state; + if (this._freeSlotStack.length > 0) { + newSlot = this._freeSlotStack.pop(); + const gen = this._stateBySlot[newSlot] >>> SLOT_BITS; + state = ((gen << SLOT_BITS) | 1) >>> 0; + } + else { + newSlot = this._values.length; + if (newSlot > SLOT_MASK) { + throw new RangeError(`Reference slot overflow: ${newSlot} exceeds ${SLOT_MASK}`); + } + state = 1; + } + this._stateBySlot[newSlot] = state; + this._values[newSlot] = value; + this._slotByValue.set(value, newSlot); + return ((state & ~SLOT_MASK) | newSlot) >>> 0; + } + retainByRef(reference) { + const state = this._getValidatedSlotState(reference); + const slot = reference & SLOT_MASK; + const nextState = (state + 1) >>> 0; + if ((nextState & SLOT_MASK) === 0) { + throw new RangeError(`Reference count overflow at slot ${slot}`); + } + this._stateBySlot[slot] = nextState; + return reference; + } + release(reference) { + const state = this._getValidatedSlotState(reference); + const slot = reference & SLOT_MASK; + if ((state & SLOT_MASK) > 1) { + this._stateBySlot[slot] = (state - 1) >>> 0; return; - this._heapEntryByValue.delete(value); - this._heapValueById.delete(ref); - } - getObject(ref) { - const value = this._heapValueById.get(ref); - if (value === undefined) { - throw new ReferenceError("Attempted to read invalid reference " + ref); } - return value; + this._slotByValue.delete(this._values[slot]); + this._values[slot] = undefined; + const nextGen = ((state >>> SLOT_BITS) + 1) & GEN_MASK; + this._stateBySlot[slot] = (nextGen << SLOT_BITS) >>> 0; + this._freeSlotStack.push(slot); + } + getObject(reference) { + this._getValidatedSlotState(reference); + return this._values[reference & SLOT_MASK]; + } + // Returns the packed state for the slot, after validating the reference. + _getValidatedSlotState(reference) { + const slot = reference & SLOT_MASK; + if (slot === 0) + throw new ReferenceError(`Attempted to use invalid reference ${reference}`); + const state = this._stateBySlot[slot]; + if (state === undefined || (state & SLOT_MASK) === 0) { + throw new ReferenceError(`Attempted to use invalid reference ${reference}`); + } + if (state >>> SLOT_BITS !== reference >>> SLOT_BITS) { + throw new ReferenceError(`Attempted to use stale reference ${reference}`); + } + return state; } } diff --git a/Runtime/src/object-heap.ts b/Runtime/src/object-heap.ts index ba9cf8021..6138953e9 100644 --- a/Runtime/src/object-heap.ts +++ b/Runtime/src/object-heap.ts @@ -1,59 +1,114 @@ import { globalVariable } from "./find-global.js"; import { ref } from "./types.js"; -type SwiftRuntimeHeapEntry = { - id: number; - rc: number; -}; +const SLOT_BITS = 24; +const SLOT_MASK = (1 << SLOT_BITS) - 1; +const GEN_MASK = (1 << (32 - SLOT_BITS)) - 1; + export class JSObjectSpace { - private _heapValueById: Map; - private _heapEntryByValue: Map; - private _heapNextKey: number; + private _slotByValue: Map; + private _values: (any | undefined)[]; + private _stateBySlot: number[]; + private _freeSlotStack: number[]; constructor() { - this._heapValueById = new Map(); - this._heapValueById.set(1, globalVariable); - - this._heapEntryByValue = new Map(); - this._heapEntryByValue.set(globalVariable, { id: 1, rc: 1 }); + this._slotByValue = new Map(); + this._values = []; + this._stateBySlot = []; + this._freeSlotStack = []; // Note: 0 is preserved for invalid references, 1 is preserved for globalThis - this._heapNextKey = 2; + this._values[0] = undefined; + this._values[1] = globalVariable; + this._slotByValue.set(globalVariable, 1); + this._stateBySlot[1] = 1; // gen=0, rc=1 } retain(value: any) { - const entry = this._heapEntryByValue.get(value); - if (entry) { - entry.rc++; - return entry.id; + const slot = this._slotByValue.get(value); + if (slot !== undefined) { + const state = this._stateBySlot[slot]!; + const nextState = (state + 1) >>> 0; + if ((nextState & SLOT_MASK) === 0) { + throw new RangeError( + `Reference count overflow at slot ${slot}`, + ); + } + this._stateBySlot[slot] = nextState; + return ((nextState & ~SLOT_MASK) | slot) >>> 0; + } + + let newSlot: number; + let state: number; + if (this._freeSlotStack.length > 0) { + newSlot = this._freeSlotStack.pop()!; + const gen = this._stateBySlot[newSlot]! >>> SLOT_BITS; + state = ((gen << SLOT_BITS) | 1) >>> 0; + } else { + newSlot = this._values.length; + if (newSlot > SLOT_MASK) { + throw new RangeError( + `Reference slot overflow: ${newSlot} exceeds ${SLOT_MASK}`, + ); + } + state = 1; } - const id = this._heapNextKey++; - this._heapValueById.set(id, value); - this._heapEntryByValue.set(value, { id: id, rc: 1 }); - return id; + + this._stateBySlot[newSlot] = state; + this._values[newSlot] = value; + this._slotByValue.set(value, newSlot); + return ((state & ~SLOT_MASK) | newSlot) >>> 0; } - retainByRef(ref: ref) { - return this.retain(this.getObject(ref)); + retainByRef(reference: ref) { + const state = this._getValidatedSlotState(reference); + const slot = reference & SLOT_MASK; + const nextState = (state + 1) >>> 0; + if ((nextState & SLOT_MASK) === 0) { + throw new RangeError(`Reference count overflow at slot ${slot}`); + } + this._stateBySlot[slot] = nextState; + return reference; } - release(ref: ref) { - const value = this._heapValueById.get(ref); - const entry = this._heapEntryByValue.get(value)!; - entry.rc--; - if (entry.rc != 0) return; + release(reference: ref) { + const state = this._getValidatedSlotState(reference); + const slot = reference & SLOT_MASK; + if ((state & SLOT_MASK) > 1) { + this._stateBySlot[slot] = (state - 1) >>> 0; + return; + } + + this._slotByValue.delete(this._values[slot]); + this._values[slot] = undefined; + const nextGen = ((state >>> SLOT_BITS) + 1) & GEN_MASK; + this._stateBySlot[slot] = (nextGen << SLOT_BITS) >>> 0; + this._freeSlotStack.push(slot); + } - this._heapEntryByValue.delete(value); - this._heapValueById.delete(ref); + getObject(reference: ref) { + this._getValidatedSlotState(reference); + return this._values[reference & SLOT_MASK]; } - getObject(ref: ref) { - const value = this._heapValueById.get(ref); - if (value === undefined) { + // Returns the packed state for the slot, after validating the reference. + private _getValidatedSlotState(reference: ref): number { + const slot = reference & SLOT_MASK; + if (slot === 0) + throw new ReferenceError( + `Attempted to use invalid reference ${reference}`, + ); + const state = this._stateBySlot[slot]; + if (state === undefined || (state & SLOT_MASK) === 0) { + throw new ReferenceError( + `Attempted to use invalid reference ${reference}`, + ); + } + if (state >>> SLOT_BITS !== reference >>> SLOT_BITS) { throw new ReferenceError( - "Attempted to read invalid reference " + ref, + `Attempted to use stale reference ${reference}`, ); } - return value; + return state; } } diff --git a/Tests/JavaScriptKitTests/JSClosureTests.swift b/Tests/JavaScriptKitTests/JSClosureTests.swift index 3d609a9b9..e278656d8 100644 --- a/Tests/JavaScriptKitTests/JSClosureTests.swift +++ b/Tests/JavaScriptKitTests/JSClosureTests.swift @@ -92,52 +92,38 @@ class JSClosureTests: XCTestCase { throw XCTSkip("Missing --expose-gc flag") } - // Step 1: Create many JSClosure instances + // Step 1: Create many source closures and keep only JS references alive. + // These closures must remain callable even after heavy finalizer churn. let obj = JSObject() - var closurePointers: Set = [] let numberOfSourceClosures = 10_000 do { var closures: [JSClosure] = [] for i in 0.. maxClosurePointer { - break + let numberOfProbeClosures = 50_000 + for i in 0.. Date: Wed, 13 May 2026 12:44:09 +0200 Subject: [PATCH 063/140] BridgeJS: Fix name collision for same-named nested structs --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 56 +++++- .../Sources/BridgeJSLink/JSGlueGen.swift | 20 +- .../Inputs/MacroSwift/NestedType.swift | 11 ++ .../BridgeJSCodegenTests/NestedType.json | 67 +++++++ .../BridgeJSCodegenTests/NestedType.swift | 90 +++++++++ .../BridgeJSLinkTests/NestedType.d.ts | 19 +- .../BridgeJSLinkTests/NestedType.js | 55 +++++- .../BridgeJSRuntimeTests/ExportAPITests.swift | 18 ++ .../Generated/BridgeJS.swift | 118 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 173 ++++++++++++++++++ Tests/prelude.mjs | 11 ++ 11 files changed, 611 insertions(+), 27 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index ceaaae8f1..6c283a3b4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -232,7 +232,9 @@ public struct BridgeJSLink { var structExportEntries: [(js: [String], dts: [String])] = [] for structDefinition in skeleton.structs { let (jsStruct, dtsType, dtsExportEntry) = try renderExportedStruct(structDefinition) - data.topLevelDtsTypeLines.append(contentsOf: dtsType) + if structDefinition.namespace == nil { + data.topLevelDtsTypeLines.append(contentsOf: dtsType) + } if structDefinition.namespace == nil && (!jsStruct.isEmpty || !dtsExportEntry.isEmpty) { structExportEntries.append((js: jsStruct, dts: dtsExportEntry)) @@ -492,7 +494,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_struct_lower_\(structDef.abiName)\"] = function(objectId) {") printer.indent { printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" + "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" ) } printer.write("}") @@ -500,7 +502,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_struct_lift_\(structDef.abiName)\"] = function() {") printer.indent { printer.write( - "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lift();" + "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lift();" ) printer.write("return \(JSGlueVariableScope.reservedSwift).memory.retain(value);") } @@ -1005,7 +1007,7 @@ public struct BridgeJSLink { let structScope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) let fragment = IntrinsicJSFragment.structHelper(structDefinition: structDef, allStructs: allStructs) _ = try fragment.printCode( - [structDef.name], + [structDef.abiName], IntrinsicJSFragment.PrintCodeContext( scope: structScope, printer: structPrinter, @@ -1159,10 +1161,10 @@ public struct BridgeJSLink { for skeleton in skeletons.compactMap(\.exported) { for structDef in skeleton.structs { printer.write( - "const \(structDef.name)Helpers = __bjs_create\(structDef.name)Helpers();" + "const \(structDef.abiName)Helpers = __bjs_create\(structDef.abiName)Helpers();" ) printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name) = \(structDef.name)Helpers;" + "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName) = \(structDef.abiName)Helpers;" ) printer.nextLine() } @@ -2616,6 +2618,7 @@ extension BridgeJSLink { var functions: [ExportedFunction] = [] var classes: [ExportedClass] = [] var enums: [ExportedEnum] = [] + var structs: [ExportedStruct] = [] var staticProperties: [ExportedProperty] = [] var functionJsLines: [(name: String, lines: [String])] = [] var functionDtsLines: [(name: String, lines: [String])] = [] @@ -2664,6 +2667,14 @@ extension BridgeJSLink { currentNode.content.classes.append(klass) } + for structDef in skeleton.structs where structDef.namespace != nil { + var currentNode = rootNode + for part in structDef.namespace! { + currentNode = currentNode.addChild(part) + } + currentNode.content.structs.append(structDef) + } + for enumDef in skeleton.enums where enumDef.namespace != nil && enumDef.enumType != .namespace { var currentNode = rootNode for part in enumDef.namespace! { @@ -2845,8 +2856,18 @@ 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 + { + return true + } + return node.children.values.contains(where: { hasExportContent(node: $0) }) + } + private func printExportsTypeHierarchy(node: NamespaceNode, printer: CodeFragmentPrinter) { for (childName, childNode) in node.children.sorted(by: { $0.key < $1.key }) { + guard hasExportContent(node: childNode) else { continue } printer.write("\(childName): {") printer.indent { for (_, lines) in childNode.content.classDtsLines.sorted(by: { $0.name < $1.name }) { @@ -2983,8 +3004,8 @@ extension BridgeJSLink { renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String ) { func hasContent(node: NamespaceNode) -> Bool { - // Enums are always included - if !node.content.enums.isEmpty { + // Enums and structs are always included + if !node.content.enums.isEmpty || !node.content.structs.isEmpty { return true } @@ -3164,6 +3185,23 @@ 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("export interface \(structDef.name) {") + printer.indent { + for property in instanceProps { + let tsType = BridgeJSLink.resolveTypeScriptType( + property.type, + exportedSkeletons: exportedSkeletons + ) + 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 } @@ -3610,7 +3648,7 @@ extension BridgeType { case .associatedValueEnum(let name): return "\(name)Tag" case .swiftStruct(let name): - return name.components(separatedBy: ".").last ?? name + return name case .namespaceEnum(let name): return name case .swiftProtocol(let name): diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 1ad397f71..accc2a287 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -944,7 +944,7 @@ struct IntrinsicJSFragment: Sendable { fullName: String, kind: JSOptionalKind ) -> IntrinsicJSFragment { - let base = fullName.components(separatedBy: ".").last ?? fullName + let base = fullName.replacingOccurrences(of: ".", with: "_") let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], @@ -1300,7 +1300,7 @@ struct IntrinsicJSFragment: Sendable { let base = fullName.components(separatedBy: ".").last ?? fullName return .associatedEnumLowerParameter(enumBase: base) case .swiftStruct(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName + let base = fullName.replacingOccurrences(of: ".", with: "_") return swiftStructLowerParameter(structBase: base) case .closure: return IntrinsicJSFragment( @@ -1360,7 +1360,7 @@ struct IntrinsicJSFragment: Sendable { let base = fullName.components(separatedBy: ".").last ?? fullName return .associatedEnumLiftReturn(enumBase: base) case .swiftStruct(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName + let base = fullName.replacingOccurrences(of: ".", with: "_") return swiftStructLiftReturn(structBase: base) case .closure: return IntrinsicJSFragment( @@ -1446,7 +1446,7 @@ struct IntrinsicJSFragment: Sendable { case .importTS: return .jsObjectLiftRetainedObjectId case .exportSwift: - let base = fullName.components(separatedBy: ".").last ?? fullName + let base = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in @@ -1805,7 +1805,7 @@ struct IntrinsicJSFragment: Sendable { } static func swiftStructLowerReturn(fullName: String) -> IntrinsicJSFragment { - swiftStructLower(structBase: fullName.components(separatedBy: ".").last ?? fullName) + swiftStructLower(structBase: fullName.replacingOccurrences(of: ".", with: "_")) } static func swiftStructLowerParameter(structBase: String) -> IntrinsicJSFragment { @@ -2008,7 +2008,7 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - let structBase = fullName.components(separatedBy: ".").last ?? fullName + let structBase = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in @@ -2130,7 +2130,7 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - let structBase = fullName.components(separatedBy: ".").last ?? fullName + let structBase = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in @@ -2426,7 +2426,7 @@ struct IntrinsicJSFragment: Sendable { ) try printer.indent { printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(this);" + "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lower(this);" ) var paramForwardings: [String] = [] @@ -2502,7 +2502,7 @@ struct IntrinsicJSFragment: Sendable { let printer = context.printer let value = arguments[0] printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lower(\(value));" + "\(JSGlueVariableScope.reservedStructHelpers).\(nestedName.replacingOccurrences(of: ".", with: "_")).lower(\(value));" ) return [] } @@ -2540,7 +2540,7 @@ struct IntrinsicJSFragment: Sendable { let (scope, printer) = (context.scope, context.printer) let structVar = scope.variable("struct") printer.write( - "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lift();" + "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName.replacingOccurrences(of: ".", with: "_")).lift();" ) return [structVar] } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift index bd2bcc4fe..12fccb379 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedType.swift @@ -8,3 +8,14 @@ var score: Double } } + +@JS class Player { + @JS func getTag() -> String { + return "player" + } + + @JS struct Stats { + var level: Int + var rating: String + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json index e8666bbc4..f924b3eba 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json @@ -26,6 +26,32 @@ ], "swiftCallName" : "User" + }, + { + "methods" : [ + { + "abiName" : "bjs_Player_getTag", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTag", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Player", + "properties" : [ + + ], + "swiftCallName" : "Player" } ], "enums" : [ @@ -79,6 +105,47 @@ } ], "swiftCallName" : "User.Stats" + }, + { + "methods" : [ + + ], + "name" : "Stats", + "namespace" : [ + "Player" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "level", + "namespace" : [ + "Player" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "rating", + "namespace" : [ + "Player" + ], + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Player.Stats" } ] }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift index 35ead0856..ed1a080e9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -46,6 +46,54 @@ fileprivate func _bjs_struct_lift_User_Stats_extern() -> Int32 { return _bjs_struct_lift_User_Stats_extern() } +extension Player.Stats: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Player.Stats { + let rating = String.bridgeJSStackPop() + let level = Int.bridgeJSStackPop() + return Player.Stats(level: level, rating: rating) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.level.bridgeJSStackPush() + self.rating.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Player_Stats(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Player_Stats())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Player_Stats") +fileprivate func _bjs_struct_lower_Player_Stats_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Player_Stats_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Player_Stats(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Player_Stats_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Player_Stats") +fileprivate func _bjs_struct_lift_Player_Stats_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Player_Stats_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Player_Stats() -> Int32 { + return _bjs_struct_lift_Player_Stats_extern() +} + @_expose(wasm, "bjs_User_getName") @_cdecl("bjs_User_getName") public func _bjs_User_getName(_ _self: UnsafeMutableRawPointer) -> Void { @@ -86,4 +134,46 @@ 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) +} + +@_expose(wasm, "bjs_Player_getTag") +@_cdecl("bjs_Player_getTag") +public func _bjs_Player_getTag(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Player.bridgeJSLiftParameter(_self).getTag() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Player_deinit") +@_cdecl("bjs_Player_deinit") +public func _bjs_Player_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Player: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Player_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Player_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Player_wrap") +fileprivate func _bjs_Player_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Player_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Player_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Player_wrap_extern(pointer) } \ 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 2d3942e06..4e966661e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts @@ -4,9 +4,17 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -export interface Stats { - health: number; - score: number; +export namespace Player { + export interface Stats { + level: number; + rating: string; + } +} +export namespace User { + export interface Stats { + health: number; + score: number; + } } /// Represents a Swift heap object like a class instance or an actor instance. export interface SwiftHeapObject { @@ -18,9 +26,14 @@ export interface SwiftHeapObject { export interface User extends SwiftHeapObject { getName(): string; } +export interface Player extends SwiftHeapObject { + getTag(): string; +} export type Exports = { User: { } + Player: { + } } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index cf24e7e2d..f276877e0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -30,7 +30,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createStatsHelpers = () => ({ + const __bjs_createUser_StatsHelpers = () => ({ lower: (value) => { i32Stack.push((value.health | 0)); f64Stack.push(value.score); @@ -41,6 +41,20 @@ export async function createInstantiator(options, swift) { return { health: int, score: f64 }; } }); + const __bjs_createPlayer_StatsHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.level | 0)); + const bytes = textEncoder.encode(value.rating); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + const int = i32Stack.pop(); + return { level: int, rating: string }; + } + }); return { /** @@ -110,10 +124,17 @@ export async function createInstantiator(options, swift) { return i64Stack.pop(); } bjs["swift_js_struct_lower_User_Stats"] = function(objectId) { - structHelpers.Stats.lower(swift.memory.getObject(objectId)); + structHelpers.User_Stats.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_User_Stats"] = function() { - const value = structHelpers.Stats.lift(); + const value = structHelpers.User_Stats.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Player_Stats"] = function(objectId) { + structHelpers.Player_Stats.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Player_Stats"] = function() { + const value = structHelpers.Player_Stats.lift(); return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { @@ -210,6 +231,10 @@ export async function createInstantiator(options, swift) { if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } + importObject["TestModule"]["bjs_Player_wrap"] = function(pointer) { + const obj = _exports['Player'].__construct(pointer); + return swift.memory.retain(obj); + }; importObject["TestModule"]["bjs_User_wrap"] = function(pointer) { const obj = _exports['User'].__construct(pointer); return swift.memory.retain(obj); @@ -291,11 +316,31 @@ export async function createInstantiator(options, swift) { return ret; } } - const StatsHelpers = __bjs_createStatsHelpers(); - structHelpers.Stats = StatsHelpers; + class Player extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Player_deinit, Player.prototype, null); + } + + getTag() { + instance.exports.bjs_Player_getTag(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + } + const User_StatsHelpers = __bjs_createUser_StatsHelpers(); + structHelpers.User_Stats = User_StatsHelpers; + + const Player_StatsHelpers = __bjs_createPlayer_StatsHelpers(); + structHelpers.Player_Stats = Player_StatsHelpers; const exports = { User, + Player, + Player: { + }, + User: { + }, }; _exports = exports; return exports; diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c81622f0d..c6e216203 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1299,6 +1299,24 @@ enum GraphOperations { } } +@JS enum NestedStructGroupA { + @JS struct Metadata { + var label: String + var count: Int + } + + @JS static func roundtripMetadata(_ m: Metadata) -> Metadata { m } +} + +@JS enum NestedStructGroupB { + @JS struct Metadata { + var tag: String + var value: Double + } + + @JS static func roundtripMetadata(_ m: Metadata) -> Metadata { m } +} + class ExportAPITests: XCTestCase { func testAll() { var hasDeinitGreeter = false diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 771838716..f695917db 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4809,6 +4809,28 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_se #endif } +@_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 +} + +@_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 +} + @_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { @@ -5319,6 +5341,102 @@ extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { } } +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())) + } +} + +#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 +@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata(_ objectId: Int32) -> Void { + return _bjs_struct_lower_NestedStructGroupA_Metadata_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 +#else +fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata_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() +} + +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())) + } +} + +#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 +@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata(_ objectId: Int32) -> Void { + return _bjs_struct_lower_NestedStructGroupB_Metadata_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 +#else +fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_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() +} + 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 7a3e7f7fe..5222902e0 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -9163,6 +9163,100 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "NestedStructGroupA", + "staticMethods" : [ + { + "abiName" : "bjs_NestedStructGroupA_static_roundtripMetadata", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtripMetadata", + "namespace" : [ + "NestedStructGroupA" + ], + "parameters" : [ + { + "label" : "_", + "name" : "m", + "type" : { + "swiftStruct" : { + "_0" : "NestedStructGroupA.Metadata" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "NestedStructGroupA.Metadata" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "NestedStructGroupA" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "NestedStructGroupA", + "tsFullPath" : "NestedStructGroupA" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "NestedStructGroupB", + "staticMethods" : [ + { + "abiName" : "bjs_NestedStructGroupB_static_roundtripMetadata", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtripMetadata", + "namespace" : [ + "NestedStructGroupB" + ], + "parameters" : [ + { + "label" : "_", + "name" : "m", + "type" : { + "swiftStruct" : { + "_0" : "NestedStructGroupB.Metadata" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "NestedStructGroupB.Metadata" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "NestedStructGroupB" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "NestedStructGroupB", + "tsFullPath" : "NestedStructGroupB" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "IntegerTypesSupportExports", @@ -14890,6 +14984,85 @@ } ], "structs" : [ + { + "methods" : [ + + ], + "name" : "Metadata", + "namespace" : [ + "NestedStructGroupA" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "NestedStructGroupA" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "count", + "namespace" : [ + "NestedStructGroupA" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "NestedStructGroupA.Metadata" + }, + { + "methods" : [ + + ], + "name" : "Metadata", + "namespace" : [ + "NestedStructGroupB" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "tag", + "namespace" : [ + "NestedStructGroupB" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "namespace" : [ + "NestedStructGroupB" + ], + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "NestedStructGroupB.Metadata" + }, { "methods" : [ diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 10c73ec2f..42aa9feaf 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -1023,6 +1023,17 @@ function testStructSupport(exports) { const fooContainerResult2 = exports.roundTripFooContainer(fooContainer2); assert.equal(fooContainerResult2.foo.value, "first"); assert.equal(fooContainerResult2.optionalFoo, null); + + // Test nested structs with same short name under different parents + const metaA = { label: "hello", count: 42 }; + const metaAResult = exports.NestedStructGroupA.roundtripMetadata(metaA); + assert.equal(metaAResult.label, "hello"); + assert.equal(metaAResult.count, 42); + + const metaB = { tag: "world", value: 3.14 }; + const metaBResult = exports.NestedStructGroupB.roundtripMetadata(metaB); + assert.equal(metaBResult.tag, "world"); + assert.equal(metaBResult.value, 3.14); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ From fc672e7b429f835888f999437dfd28843287e643 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 13 May 2026 19:50:35 +0200 Subject: [PATCH 064/140] BridgeJS: Add JSTypedArray as a recognized BridgeJS type (#746) BridgeJS: Add JSTypedArray convenience typealiases as recognized types Add JSInt8Array, JSUint8Array, JSInt16Array, JSUint16Array, JSInt32Array, JSUint32Array, JSFloat32Array, JSFloat64Array typealiases and pre-seed them in SwiftToSkeleton so BridgeJS recognizes them in @JS signatures. Users can now write: @JS func processData(_ data: JSUint8Array) -> JSUint8Array Generated TypeScript uses native typed array names: processData(data: Uint8Array): Uint8Array Bridging is reference-based (passes JSObject ID, no data copying). Follows the existing JSPromise pre-seeding pattern. --- .../BridgeJSCore/SwiftToSkeleton.swift | 32 ++ .../Sources/BridgeJSLink/BridgeJSLink.swift | 15 + .../Inputs/MacroSwift/JSTypedArrayTypes.swift | 19 ++ .../JSTypedArrayTypes.json | 123 ++++++++ .../JSTypedArrayTypes.swift | 43 +++ .../BridgeJSLinkTests/JSTypedArrayTypes.d.ts | 21 ++ .../BridgeJSLinkTests/JSTypedArrayTypes.js | 235 ++++++++++++++ .../BasicObjects/JSTypedArray.swift | 9 + .../Exporting-Swift/Exporting-Swift-Array.md | 36 +++ .../Articles/BridgeJS/Supported-Types.md | 14 + .../Generated/BridgeJS.swift | 167 ++++++++++ .../Generated/JavaScript/BridgeJS.json | 298 ++++++++++++++++++ .../JSTypedArrayTests.swift | 53 ++++ .../JavaScript/JSTypedArrayTests.mjs | 77 +++++ Tests/prelude.mjs | 2 + 15 files changed, 1144 insertions(+) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSTypedArrayTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js create mode 100644 Tests/BridgeJSRuntimeTests/JSTypedArrayTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index f39ac16f8..57b9a57df 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -42,6 +42,14 @@ public final class SwiftToSkeleton { self.typeDeclResolver.addSourceFile( """ @JSClass struct JSPromise {} + @JSClass struct JSInt8Array {} + @JSClass struct JSUint8Array {} + @JSClass struct JSInt16Array {} + @JSClass struct JSUint16Array {} + @JSClass struct JSInt32Array {} + @JSClass struct JSUint32Array {} + @JSClass struct JSFloat32Array {} + @JSClass struct JSFloat64Array {} """ ) } @@ -128,11 +136,35 @@ public final class SwiftToSkeleton { ) } + private static let jsTypedArrayTypealiasNames: [String: String] = [ + "Int8": "JSInt8Array", + "UInt8": "JSUint8Array", + "Int16": "JSInt16Array", + "UInt16": "JSUint16Array", + "Int32": "JSInt32Array", + "UInt32": "JSUint32Array", + "Float": "JSFloat32Array", + "Float32": "JSFloat32Array", + "Double": "JSFloat64Array", + "Float64": "JSFloat64Array", + ] + func lookupType(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { if let attributedType = type.as(AttributedTypeSyntax.self) { return lookupType(for: attributedType.baseType, errors: &errors) } + // JSTypedArray + if let identifierType = type.as(IdentifierTypeSyntax.self), + identifierType.name.text == "JSTypedArray", + let genericArgs = identifierType.genericArgumentClause?.arguments, + genericArgs.count == 1, + let elementName = genericArgs.first?.argument.as(IdentifierTypeSyntax.self)?.name.text, + let typealiasName = Self.jsTypedArrayTypealiasNames[elementName] + { + return .jsObject(typealiasName) + } + if let identifierType = type.as(IdentifierTypeSyntax.self), identifierType.name.text == "JSTypedClosure", let genericArgs = identifierType.genericArgumentClause?.arguments, diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 6c283a3b4..aed27437b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -3632,6 +3632,9 @@ extension BridgeType { case .bool: return "boolean" case .jsObject(let name): + if let name, let tsName = Self.jsTypedArrayTSNames[name] { + return tsName + } return name ?? "any" case .jsValue: return "any" @@ -3668,6 +3671,18 @@ extension BridgeType { return "Record" } } + + /// Maps JSTypedArray Swift typealias names to their JavaScript TypedArray constructor names. + private static let jsTypedArrayTSNames: [String: String] = [ + "JSInt8Array": "Int8Array", + "JSUint8Array": "Uint8Array", + "JSInt16Array": "Int16Array", + "JSUint16Array": "Uint16Array", + "JSInt32Array": "Int32Array", + "JSUint32Array": "Uint32Array", + "JSFloat32Array": "Float32Array", + "JSFloat64Array": "Float64Array", + ] } extension WasmCoreType { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSTypedArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSTypedArrayTypes.swift new file mode 100644 index 000000000..7f308f560 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSTypedArrayTypes.swift @@ -0,0 +1,19 @@ +import JavaScriptKit + +// Using typealiases +@JS func processBytes(_ data: JSUint8Array) -> JSUint8Array { + return data +} + +@JS func processFloats(_ data: JSFloat32Array) -> JSFloat32Array { + return data +} + +// Using generic form directly +@JS func processGenericDoubles(_ data: JSTypedArray) -> JSTypedArray { + return data +} + +@JS func processGenericInts(_ data: JSTypedArray) -> JSTypedArray { + return data +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json new file mode 100644 index 000000000..a7b9c8623 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json @@ -0,0 +1,123 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_processBytes", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processBytes", + "parameters" : [ + { + "label" : "_", + "name" : "data", + "type" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + }, + { + "abiName" : "bjs_processFloats", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processFloats", + "parameters" : [ + { + "label" : "_", + "name" : "data", + "type" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + } + }, + { + "abiName" : "bjs_processGenericDoubles", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processGenericDoubles", + "parameters" : [ + { + "label" : "_", + "name" : "data", + "type" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + } + }, + { + "abiName" : "bjs_processGenericInts", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processGenericInts", + "parameters" : [ + { + "label" : "_", + "name" : "data", + "type" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift new file mode 100644 index 000000000..4777af058 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift @@ -0,0 +1,43 @@ +@_expose(wasm, "bjs_processBytes") +@_cdecl("bjs_processBytes") +public func _bjs_processBytes(_ data: Int32) -> Int32 { + #if arch(wasm32) + let ret = processBytes(_: JSUint8Array.bridgeJSLiftParameter(data)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processFloats") +@_cdecl("bjs_processFloats") +public func _bjs_processFloats(_ data: Int32) -> Int32 { + #if arch(wasm32) + let ret = processFloats(_: JSFloat32Array.bridgeJSLiftParameter(data)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processGenericDoubles") +@_cdecl("bjs_processGenericDoubles") +public func _bjs_processGenericDoubles(_ data: Int32) -> Int32 { + #if arch(wasm32) + let ret = processGenericDoubles(_: JSFloat64Array.bridgeJSLiftParameter(data)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processGenericInts") +@_cdecl("bjs_processGenericInts") +public func _bjs_processGenericInts(_ data: Int32) -> Int32 { + #if arch(wasm32) + let ret = processGenericInts(_: JSInt32Array.bridgeJSLiftParameter(data)) + 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/JSTypedArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts new file mode 100644 index 000000000..b842e7d7d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.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 type Exports = { + processBytes(data: Uint8Array): Uint8Array; + processFloats(data: Float32Array): Float32Array; + processGenericDoubles(data: Float64Array): Float64Array; + processGenericInts(data: Int32Array): Int32Array; +} +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/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js new file mode 100644 index 000000000..ee51d4a28 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -0,0 +1,235 @@ +// 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 = []; + 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(); + } + 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 exports = { + processBytes: function bjs_processBytes(data) { + const ret = instance.exports.bjs_processBytes(swift.memory.retain(data)); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + processFloats: function bjs_processFloats(data) { + const ret = instance.exports.bjs_processFloats(swift.memory.retain(data)); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + processGenericDoubles: function bjs_processGenericDoubles(data) { + const ret = instance.exports.bjs_processGenericDoubles(swift.memory.retain(data)); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + processGenericInts: function bjs_processGenericInts(data) { + const ret = instance.exports.bjs_processGenericInts(swift.memory.retain(data)); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift b/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift index 0ad7b235a..4717b6705 100644 --- a/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift +++ b/Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift @@ -204,3 +204,12 @@ public enum JSUInt8Clamped: TypedArrayElement { } public typealias JSUInt8ClampedArray = JSTypedArray + +public typealias JSInt8Array = JSTypedArray +public typealias JSUint8Array = JSTypedArray +public typealias JSInt16Array = JSTypedArray +public typealias JSUint16Array = JSTypedArray +public typealias JSInt32Array = JSTypedArray +public typealias JSUint32Array = JSTypedArray +public typealias JSFloat32Array = JSTypedArray +public typealias JSFloat64Array = JSTypedArray diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md index e97bceefa..1100358ba 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md @@ -95,6 +95,42 @@ TypeScript definitions: - `[Int]?` becomes `number[] | null` - `[[Int]]` becomes `number[][]` +## Using TypedArrays + +When you need the JavaScript API to use native TypedArray types (e.g., `Uint8Array` for `fetch` body, `Float32Array` for WebGPU), use ``JSTypedArray`` instead of a plain Swift array: + +```swift +import JavaScriptKit + +@JS func processData(_ data: JSTypedArray) -> JSTypedArray { + return data +} + +// Convenience typealiases also work: +@JS func processFloats(_ data: JSFloat32Array) -> JSFloat32Array { + return data +} +``` + +Generated TypeScript: + +```typescript +export type Exports = { + processData(data: Uint8Array): Uint8Array; + processFloats(data: Float32Array): Float32Array; +} +``` + +Unlike plain arrays which use copy semantics, `JSTypedArray` uses **reference semantics** — it wraps a JavaScript TypedArray object and passes it by reference (no data copying). This is ideal for large binary data or when interacting with JavaScript APIs that expect TypedArrays. + +| Swift | TypeScript | +|:------|:-----------| +| `JSTypedArray` / `JSUint8Array` | `Uint8Array` | +| `JSTypedArray` / `JSInt8Array` | `Int8Array` | +| `JSTypedArray` / `JSInt32Array` | `Int32Array` | +| `JSTypedArray` / `JSFloat32Array` | `Float32Array` | +| `JSTypedArray` / `JSFloat64Array` | `Float64Array` | + ## How It Works Arrays use **copy semantics** when crossing the Swift/JavaScript boundary: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md index 81a135af3..5c609ab72 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md @@ -16,6 +16,20 @@ Swift types and their JavaScript/TypeScript equivalents at the BridgeJS boundary | ``JSUndefinedOr`` `` | `undefined` or `T` | `T \| undefined` | | ``JSObject`` | object | `object` | | ``JSValue`` | any | `any` | +| ``JSTypedArray`` `` | TypedArray | `Uint8Array`, `Float32Array`, etc. | + +### TypedArray mapping + +When using `JSTypedArray` (or convenience typealiases) in `@JS` signatures, the TypeScript type maps to the corresponding JavaScript TypedArray: + +| Swift | TypeScript | +|:--|:--| +| `JSTypedArray` / `JSUint8Array` | `Uint8Array` | +| `JSTypedArray` / `JSInt32Array` | `Int32Array` | +| `JSTypedArray` / `JSFloat32Array` | `Float32Array` | +| `JSTypedArray` / `JSFloat64Array` | `Float64Array` | + +See for usage details. ## See Also diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index f695917db..3fa4eb9d5 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4941,6 +4941,50 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) - #endif } +@_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 = JSTypedArrayExports.roundTripUint8Array(_: JSUint8Array.bridgeJSLiftParameter(v)) + 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 +} + +@_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 +} + +@_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_OptionalSupportExports_static_roundTripOptionalString") @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalString") public func _bjs_OptionalSupportExports_static_roundTripOptionalString(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { @@ -13658,6 +13702,129 @@ func _$JSClassSupportImports_makeJSClassWithArrayMembers(_ numbers: [Int], _ lab return JSClassWithArrayMembers.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsCreateUint8Array_static") +fileprivate func bjs_JSTypedArrayImports_jsCreateUint8Array_static_extern() -> Int32 +#else +fileprivate func bjs_JSTypedArrayImports_jsCreateUint8Array_static_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_jsCreateUint8Array_static() -> Int32 { + return bjs_JSTypedArrayImports_jsCreateUint8Array_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsRoundTripUint8Array_static") +fileprivate func bjs_JSTypedArrayImports_jsRoundTripUint8Array_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_JSTypedArrayImports_jsRoundTripUint8Array_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_jsRoundTripUint8Array_static(_ v: Int32) -> Int32 { + return bjs_JSTypedArrayImports_jsRoundTripUint8Array_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static") +fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static(_ v: Int32) -> Int32 { + return bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static") +fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static(_ v: Int32) -> Int32 { + return bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsRoundTripInt32Array_static") +fileprivate func bjs_JSTypedArrayImports_jsRoundTripInt32Array_static_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_JSTypedArrayImports_jsRoundTripInt32Array_static_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_jsRoundTripInt32Array_static(_ v: Int32) -> Int32 { + return bjs_JSTypedArrayImports_jsRoundTripInt32Array_static_extern(v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_runJsTypedArrayTests_static") +fileprivate func bjs_JSTypedArrayImports_runJsTypedArrayTests_static_extern() -> Void +#else +fileprivate func bjs_JSTypedArrayImports_runJsTypedArrayTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JSTypedArrayImports_runJsTypedArrayTests_static() -> Void { + return bjs_JSTypedArrayImports_runJsTypedArrayTests_static_extern() +} + +func _$JSTypedArrayImports_jsCreateUint8Array() throws(JSException) -> JSUint8Array { + let ret = bjs_JSTypedArrayImports_jsCreateUint8Array_static() + if let error = _swift_js_take_exception() { + throw error + } + return JSUint8Array.bridgeJSLiftReturn(ret) +} + +func _$JSTypedArrayImports_jsRoundTripUint8Array(_ v: JSUint8Array) throws(JSException) -> JSUint8Array { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_JSTypedArrayImports_jsRoundTripUint8Array_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUint8Array.bridgeJSLiftReturn(ret) +} + +func _$JSTypedArrayImports_jsRoundTripFloat32Array(_ v: JSFloat32Array) throws(JSException) -> JSFloat32Array { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_JSTypedArrayImports_jsRoundTripFloat32Array_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSFloat32Array.bridgeJSLiftReturn(ret) +} + +func _$JSTypedArrayImports_jsRoundTripFloat64Array(_ v: JSFloat64Array) throws(JSException) -> JSFloat64Array { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_JSTypedArrayImports_jsRoundTripFloat64Array_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSFloat64Array.bridgeJSLiftReturn(ret) +} + +func _$JSTypedArrayImports_jsRoundTripInt32Array(_ v: JSInt32Array) throws(JSException) -> JSInt32Array { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_JSTypedArrayImports_jsRoundTripInt32Array_static(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSInt32Array.bridgeJSLiftReturn(ret) +} + +func _$JSTypedArrayImports_runJsTypedArrayTests() throws(JSException) -> Void { + bjs_JSTypedArrayImports_runJsTypedArrayTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MyJSClassInternal_init") fileprivate func bjs_MyJSClassInternal_init_extern() -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 5222902e0..94142f470 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -9661,6 +9661,152 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "JSTypedArrayExports", + "staticMethods" : [ + { + "abiName" : "bjs_JSTypedArrayExports_static_roundTripUint8Array", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripUint8Array", + "namespace" : [ + "JSTypedArrayExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "JSTypedArrayExports" + } + } + }, + { + "abiName" : "bjs_JSTypedArrayExports_static_roundTripFloat32Array", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripFloat32Array", + "namespace" : [ + "JSTypedArrayExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "JSTypedArrayExports" + } + } + }, + { + "abiName" : "bjs_JSTypedArrayExports_static_roundTripFloat64Array", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripFloat64Array", + "namespace" : [ + "JSTypedArrayExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "JSTypedArrayExports" + } + } + }, + { + "abiName" : "bjs_JSTypedArrayExports_static_roundTripInt32Array", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundTripInt32Array", + "namespace" : [ + "JSTypedArrayExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "JSTypedArrayExports" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "JSTypedArrayExports", + "tsFullPath" : "JSTypedArrayExports" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "OptionalSupportExports", @@ -20215,6 +20361,158 @@ { "functions" : [ + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "JSTypedArrayImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsCreateUint8Array", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripUint8Array", + "parameters" : [ + { + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSUint8Array" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripFloat32Array", + "parameters" : [ + { + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat32Array" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripFloat64Array", + "parameters" : [ + { + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSFloat64Array" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripInt32Array", + "parameters" : [ + { + "name" : "v", + "type" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "JSInt32Array" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsTypedArrayTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, + { + "functions" : [ + ], "types" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JSTypedArrayTests.swift b/Tests/BridgeJSRuntimeTests/JSTypedArrayTests.swift new file mode 100644 index 000000000..25045ecc8 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JSTypedArrayTests.swift @@ -0,0 +1,53 @@ +import XCTest +import JavaScriptKit + +@JS enum JSTypedArrayExports { + @JS static func roundTripUint8Array(_ v: JSUint8Array) -> JSUint8Array { v } + @JS static func roundTripFloat32Array(_ v: JSFloat32Array) -> JSFloat32Array { v } + @JS static func roundTripFloat64Array(_ v: JSFloat64Array) -> JSFloat64Array { v } + @JS static func roundTripInt32Array(_ v: JSInt32Array) -> JSInt32Array { v } +} + +@JSClass struct JSTypedArrayImports { + @JSFunction static func jsCreateUint8Array() throws(JSException) -> JSUint8Array + @JSFunction static func jsRoundTripUint8Array(_ v: JSUint8Array) throws(JSException) -> JSUint8Array + @JSFunction static func jsRoundTripFloat32Array(_ v: JSFloat32Array) throws(JSException) -> JSFloat32Array + @JSFunction static func jsRoundTripFloat64Array(_ v: JSFloat64Array) throws(JSException) -> JSFloat64Array + @JSFunction static func jsRoundTripInt32Array(_ v: JSInt32Array) throws(JSException) -> JSInt32Array + @JSFunction static func runJsTypedArrayTests() throws(JSException) +} + +final class JSTypedArrayTests: XCTestCase { + func testRunJsTypedArrayTests() throws { + try JSTypedArrayImports.runJsTypedArrayTests() + } + + func testRoundTripUint8Array() throws { + let arr = JSUint8Array([1, 2, 3, 255]) + let result = try JSTypedArrayImports.jsRoundTripUint8Array(arr) + XCTAssertEqual(result.length, 4) + } + + func testCreateUint8Array() throws { + let result = try JSTypedArrayImports.jsCreateUint8Array() + XCTAssertEqual(result.length, 3) + } + + func testRoundTripFloat32Array() throws { + let arr = JSFloat32Array([1.0, 2.5, 3.0]) + let result = try JSTypedArrayImports.jsRoundTripFloat32Array(arr) + XCTAssertEqual(result.length, 3) + } + + func testRoundTripFloat64Array() throws { + let arr = JSFloat64Array([1.0, 2.5, 3.14159]) + let result = try JSTypedArrayImports.jsRoundTripFloat64Array(arr) + XCTAssertEqual(result.length, 3) + } + + func testRoundTripInt32Array() throws { + let arr = JSInt32Array([1, -2, 2_147_483_647]) + let result = try JSTypedArrayImports.jsRoundTripInt32Array(arr) + XCTAssertEqual(result.length, 3) + } +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs new file mode 100644 index 000000000..f29c248f9 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs @@ -0,0 +1,77 @@ +// @ts-check + +import assert from 'node:assert'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["JSTypedArrayImports"]} + */ +export function getImports(importsContext) { + return { + jsCreateUint8Array: function () { + return new Uint8Array([10, 20, 30]); + }, + jsRoundTripUint8Array: function (arr) { + assert.ok(arr instanceof Uint8Array, 'Expected Uint8Array'); + return arr; + }, + jsRoundTripFloat32Array: function (arr) { + assert.ok(arr instanceof Float32Array, 'Expected Float32Array'); + return arr; + }, + jsRoundTripFloat64Array: function (arr) { + assert.ok(arr instanceof Float64Array, 'Expected Float64Array'); + return arr; + }, + jsRoundTripInt32Array: function (arr) { + assert.ok(arr instanceof Int32Array, 'Expected Int32Array'); + return arr; + }, + runJsTypedArrayTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsTypedArrayTests(exports); + }, + }; +} + +/** + * JSTypedArray bridging coverage for BridgeJS runtime tests. + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports + */ +export function runJsTypedArrayTests(rootExports) { + const exports = rootExports.JSTypedArrayExports; + + // Uint8Array round-trip + const u8 = new Uint8Array([1, 2, 3, 255]); + const u8Result = exports.roundTripUint8Array(u8); + assert.ok(u8Result instanceof Uint8Array, 'Expected Uint8Array back from Swift'); + assert.equal(u8Result.length, 4); + assert.deepEqual(Array.from(u8Result), [1, 2, 3, 255]); + + // Float32Array round-trip + const f32 = new Float32Array([1.0, 2.5, 3.0]); + const f32Result = exports.roundTripFloat32Array(f32); + assert.ok(f32Result instanceof Float32Array, 'Expected Float32Array back from Swift'); + assert.equal(f32Result.length, 3); + assert.deepEqual(Array.from(f32Result), [1.0, 2.5, 3.0]); + + // Float64Array round-trip + const f64 = new Float64Array([1.0, 2.5, 3.14159]); + const f64Result = exports.roundTripFloat64Array(f64); + assert.ok(f64Result instanceof Float64Array, 'Expected Float64Array back from Swift'); + assert.equal(f64Result.length, 3); + assert.deepEqual(Array.from(f64Result), [1.0, 2.5, 3.14159]); + + // Int32Array round-trip + const i32 = new Int32Array([1, -2, 2147483647]); + const i32Result = exports.roundTripInt32Array(i32); + assert.ok(i32Result instanceof Int32Array, 'Expected Int32Array back from Swift'); + assert.equal(i32Result.length, 3); + assert.deepEqual(Array.from(i32Result), [1, -2, 2147483647]); + + // Empty typed array + const emptyU8 = new Uint8Array([]); + const emptyResult = exports.roundTripUint8Array(emptyU8); + assert.ok(emptyResult instanceof Uint8Array, 'Expected Uint8Array for empty array'); + assert.equal(emptyResult.length, 0); +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 42aa9feaf..2c922dbe2 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -14,6 +14,7 @@ import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/ import { getImports as getJSClassSupportImports, JSClassWithArrayMembers } from './BridgeJSRuntimeTests/JavaScript/JSClassSupportTests.mjs'; import { getImports as getIntegerTypesSupportImports } from './BridgeJSRuntimeTests/JavaScript/IntegerTypesSupportTests.mjs'; import { getImports as getAsyncImportImports, runAsyncWorksTests } from './BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs'; +import { getImports as getJSTypedArrayImports } from './BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs'; import { getImports as getIdentityModeTestImports } from './BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ @@ -156,6 +157,7 @@ export async function setupOptions(options, context) { DefaultArgumentImports: getDefaultArgumentImports(importsContext), JSClassSupportImports: getJSClassSupportImports(importsContext), IntegerTypesSupportImports: getIntegerTypesSupportImports(importsContext), + JSTypedArrayImports: getJSTypedArrayImports(importsContext), IdentityModeTestImports: getIdentityModeTestImports(importsContext), }; }, From 403ae956d68503957699b6dc4c07b73caad031b7 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 13 May 2026 22:58:13 +0200 Subject: [PATCH 065/140] BridgeJS: Optimize numeric array transfer with bulk TypedArray copy (#745) --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 16 + .../Sources/BridgeJSLink/JSGlueGen.swift | 29 +- .../BridgeJSLinkTests/ArrayTypes.js | 623 +++++++++++------- .../__Snapshots__/BridgeJSLinkTests/Async.js | 8 + .../BridgeJSLinkTests/AsyncImport.js | 8 + .../BridgeJSLinkTests/AsyncStaticImport.js | 8 + .../BridgeJSLinkTests/DefaultParameters.js | 83 ++- .../BridgeJSLinkTests/DictionaryTypes.js | 23 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 38 +- .../BridgeJSLinkTests/EnumCase.js | 8 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 8 + .../BridgeJSLinkTests/EnumNamespace.js | 8 + .../BridgeJSLinkTests/EnumRawType.js | 8 + .../BridgeJSLinkTests/FixedWidthIntegers.js | 8 + .../BridgeJSLinkTests/GlobalGetter.js | 8 + .../BridgeJSLinkTests/GlobalThisImports.js | 8 + .../IdentityModeClass.ConfigPointer.js | 8 + .../IdentityModeClass.PerClass.js | 8 + .../BridgeJSLinkTests/IdentityModeClass.js | 8 + .../BridgeJSLinkTests/ImportArray.js | 38 +- .../ImportedTypeInExportedInterface.js | 58 +- .../BridgeJSLinkTests/InvalidPropertyNames.js | 8 + .../BridgeJSLinkTests/JSClass.js | 8 + .../JSClassStaticFunctions.js | 8 + .../BridgeJSLinkTests/JSTypedArrayTypes.js | 8 + .../BridgeJSLinkTests/JSValue.js | 71 +- .../BridgeJSLinkTests/MixedGlobal.js | 8 + .../BridgeJSLinkTests/MixedModules.js | 8 + .../BridgeJSLinkTests/MixedPrivate.js | 8 + .../BridgeJSLinkTests/Namespaces.Global.js | 25 +- .../BridgeJSLinkTests/Namespaces.js | 25 +- .../BridgeJSLinkTests/NestedType.js | 8 + .../BridgeJSLinkTests/Optionals.js | 8 + .../BridgeJSLinkTests/PrimitiveParameters.js | 8 + .../BridgeJSLinkTests/PrimitiveReturn.js | 8 + .../BridgeJSLinkTests/PropertyTypes.js | 8 + .../BridgeJSLinkTests/Protocol.js | 46 +- .../BridgeJSLinkTests/ProtocolInClosure.js | 8 + .../StaticFunctions.Global.js | 8 + .../BridgeJSLinkTests/StaticFunctions.js | 8 + .../StaticProperties.Global.js | 8 + .../BridgeJSLinkTests/StaticProperties.js | 8 + .../BridgeJSLinkTests/StringParameter.js | 8 + .../BridgeJSLinkTests/StringReturn.js | 8 + .../BridgeJSLinkTests/SwiftClass.js | 8 + .../BridgeJSLinkTests/SwiftClosure.js | 8 + .../BridgeJSLinkTests/SwiftClosureImports.js | 8 + .../BridgeJSLinkTests/SwiftStruct.js | 8 + .../BridgeJSLinkTests/SwiftStructImports.js | 8 + .../SwiftTypedClosureAccess.js | 8 + .../__Snapshots__/BridgeJSLinkTests/Throws.js | 8 + .../BridgeJSLinkTests/UnsafePointer.js | 8 + .../VoidParameterVoidReturn.js | 8 + Plugins/PackageToJS/Templates/instantiate.js | 1 + .../JavaScriptKit/BridgeJSIntrinsics.swift | 140 +++- 55 files changed, 1183 insertions(+), 361 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index aed27437b..03dfa87a2 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -347,6 +347,7 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedF32Stack) = [];", "let \(JSGlueVariableScope.reservedF64Stack) = [];", "let \(JSGlueVariableScope.reservedPointerStack) = [];", + "let \(JSGlueVariableScope.reservedTaStack) = [];", "const \(JSGlueVariableScope.reservedEnumHelpers) = {};", "const \(JSGlueVariableScope.reservedStructHelpers) = {};", "", @@ -489,6 +490,21 @@ public struct BridgeJSLink { printer.write("return \(JSGlueVariableScope.reservedI64Stack).pop();") } printer.write("}") + // Typed array constructors indexed by kind (must match _BridgedNumericArrayKind) + printer.write( + "const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];" + ) + printer.write("bjs[\"swift_js_push_typed_array\"] = function(kind, ptr, count) {") + printer.indent { + printer.write("const Ctor = taCtors[kind];") + printer.write("const byteLen = count * Ctor.BYTES_PER_ELEMENT;") + // slice() copies the bytes into a new ArrayBuffer that is properly aligned + printer.write( + "const copy = \(JSGlueVariableScope.reservedMemory).buffer.slice(ptr, ptr + byteLen);" + ) + printer.write("\(JSGlueVariableScope.reservedTaStack).push(Array.from(new Ctor(copy)));") + } + printer.write("}") if !allStructs.isEmpty { for structDef in allStructs { printer.write("bjs[\"swift_js_struct_lower_\(structDef.abiName)\"] = function(objectId) {") diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index accc2a287..51ef16b20 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -34,6 +34,7 @@ final class JSGlueVariableScope { static let reservedStructHelpers = "structHelpers" static let reservedSwiftClosureRegistry = "swiftClosureRegistry" static let reservedMakeSwiftClosure = "makeClosure" + static let reservedTaStack = "taStack" private let intrinsicRegistry: JSIntrinsicRegistry @@ -63,6 +64,7 @@ final class JSGlueVariableScope { reservedStructHelpers, reservedSwiftClosureRegistry, reservedMakeSwiftClosure, + reservedTaStack, ] init(intrinsicRegistry: JSIntrinsicRegistry) { @@ -1896,20 +1898,31 @@ struct IntrinsicJSFragment: Sendable { let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("arrayResult") let lenVar = scope.variable("arrayLen") - let iVar = scope.variable("i") printer.write("const \(lenVar) = \(scope.popI32());") - printer.write("const \(resultVar) = [];") - printer.write("for (let \(iVar) = 0; \(iVar) < \(lenVar); \(iVar)++) {") + 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 { - let elementFragment = try stackLiftFragment(elementType: elementType) - let elementResults = try elementFragment.printCode([], context) - if let elementExpr = elementResults.first { - printer.write("\(resultVar).push(\(elementExpr));") + // 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("}") - printer.write("\(resultVar).reverse();") return [resultVar] } ) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 8359220c9..ad0111929 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -38,6 +38,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -123,6 +124,13 @@ export async function createInstantiator(options, swift) { 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)); } @@ -250,12 +258,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importProcessNumbers"] = function bjs_importProcessNumbers() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); + 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(); } - arrayResult.reverse(); imports.importProcessNumbers(arrayResult); } catch (error) { setException(error); @@ -275,12 +288,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importTransformNumbers"] = function bjs_importTransformNumbers() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); + 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(); } - arrayResult.reverse(); let ret = imports.importTransformNumbers(arrayResult); for (const elem of ret) { f64Stack.push(elem); @@ -293,12 +311,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importProcessStrings"] = function bjs_importProcessStrings() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); + 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(); } - arrayResult.reverse(); let ret = imports.importProcessStrings(arrayResult); for (const elem of ret) { const bytes = textEncoder.encode(elem); @@ -314,12 +337,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importProcessBooleans"] = function bjs_importProcessBooleans() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); + 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(); } - arrayResult.reverse(); let ret = imports.importProcessBooleans(arrayResult); for (const elem of ret) { i32Stack.push(elem ? 1 : 0); @@ -423,23 +451,33 @@ export async function createInstantiator(options, swift) { get numbers() { instance.exports.bjs_MultiArrayContainer_numbers_get(this.pointer); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); return arrayResult; } get strings() { instance.exports.bjs_MultiArrayContainer_strings_get(this.pointer); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); + 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(); } - arrayResult.reverse(); return arrayResult; } } @@ -456,12 +494,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processIntArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); return arrayResult; }, processStringArray: function bjs_processStringArray(values) { @@ -474,12 +517,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processStringArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); + 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(); } - arrayResult.reverse(); return arrayResult; }, processDoubleArray: function bjs_processDoubleArray(values) { @@ -489,12 +537,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processDoubleArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); + 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(); } - arrayResult.reverse(); return arrayResult; }, processBoolArray: function bjs_processBoolArray(values) { @@ -504,12 +557,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processBoolArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); + 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(); } - arrayResult.reverse(); return arrayResult; }, processPointArray: function bjs_processPointArray(points) { @@ -519,12 +577,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(points.length); instance.exports.bjs_processPointArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const struct = structHelpers.Point.lift(); - arrayResult.push(struct); + 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(); } - arrayResult.reverse(); return arrayResult; }, processDirectionArray: function bjs_processDirectionArray(directions) { @@ -534,12 +597,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(directions.length); instance.exports.bjs_processDirectionArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const caseId = i32Stack.pop(); - arrayResult.push(caseId); + 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(); } - arrayResult.reverse(); return arrayResult; }, processStatusArray: function bjs_processStatusArray(statuses) { @@ -549,12 +617,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(statuses.length); instance.exports.bjs_processStatusArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const rawValue = i32Stack.pop(); - arrayResult.push(rawValue); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const rawValue = i32Stack.pop(); + arrayResult.push(rawValue); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, sumIntArray: function bjs_sumIntArray(values) { @@ -583,12 +656,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processUnsafeRawPointerArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const pointer = ptrStack.pop(); - arrayResult.push(pointer); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const pointer = ptrStack.pop(); + arrayResult.push(pointer); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processUnsafeMutableRawPointerArray: function bjs_processUnsafeMutableRawPointerArray(values) { @@ -598,12 +676,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processUnsafeMutableRawPointerArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const pointer = ptrStack.pop(); - arrayResult.push(pointer); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const pointer = ptrStack.pop(); + arrayResult.push(pointer); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOpaquePointerArray: function bjs_processOpaquePointerArray(values) { @@ -613,12 +696,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processOpaquePointerArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const pointer = ptrStack.pop(); - arrayResult.push(pointer); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const pointer = ptrStack.pop(); + arrayResult.push(pointer); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOptionalIntArray: function bjs_processOptionalIntArray(values) { @@ -632,19 +720,24 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processOptionalIntArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOptionalStringArray: function bjs_processOptionalStringArray(values) { @@ -661,19 +754,24 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processOptionalStringArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOptionalArray: function bjs_processOptionalArray(values) { @@ -690,12 +788,17 @@ export async function createInstantiator(options, swift) { let optResult; if (isSome1) { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); optResult = arrayResult; } else { optResult = null; @@ -713,19 +816,24 @@ export async function createInstantiator(options, swift) { i32Stack.push(points.length); instance.exports.bjs_processOptionalPointArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOptionalDirectionArray: function bjs_processOptionalDirectionArray(directions) { @@ -739,19 +847,24 @@ export async function createInstantiator(options, swift) { i32Stack.push(directions.length); instance.exports.bjs_processOptionalDirectionArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processOptionalStatusArray: function bjs_processOptionalStatusArray(statuses) { @@ -765,19 +878,24 @@ export async function createInstantiator(options, swift) { i32Stack.push(statuses.length); instance.exports.bjs_processOptionalStatusArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processNestedIntArray: function bjs_processNestedIntArray(values) { @@ -790,18 +908,28 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processNestedIntArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - const arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const int = i32Stack.pop(); - arrayResult1.push(int); + 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); } - arrayResult1.reverse(); - arrayResult.push(arrayResult1); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processNestedStringArray: function bjs_processNestedStringArray(values) { @@ -817,18 +945,28 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_processNestedStringArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - const arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const string = strStack.pop(); - arrayResult1.push(string); + 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); } - arrayResult1.reverse(); - arrayResult.push(arrayResult1); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processNestedPointArray: function bjs_processNestedPointArray(points) { @@ -841,18 +979,28 @@ export async function createInstantiator(options, swift) { i32Stack.push(points.length); instance.exports.bjs_processNestedPointArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - const arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const struct = structHelpers.Point.lift(); - arrayResult1.push(struct); + 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); } - arrayResult1.reverse(); - arrayResult.push(arrayResult1); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processItemArray: function bjs_processItemArray(items) { @@ -862,13 +1010,18 @@ export async function createInstantiator(options, swift) { i32Stack.push(items.length); instance.exports.bjs_processItemArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - arrayResult.push(obj); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const ptr = ptrStack.pop(); + const obj = Item.__construct(ptr); + arrayResult.push(obj); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processNestedItemArray: function bjs_processNestedItemArray(items) { @@ -881,19 +1034,29 @@ export async function createInstantiator(options, swift) { i32Stack.push(items.length); instance.exports.bjs_processNestedItemArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - const arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - arrayResult1.push(obj); + 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); } - arrayResult1.reverse(); - arrayResult.push(arrayResult1); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processJSObjectArray: function bjs_processJSObjectArray(objects) { @@ -904,14 +1067,19 @@ export async function createInstantiator(options, swift) { i32Stack.push(objects.length); instance.exports.bjs_processJSObjectArray(); const arrayLen = i32Stack.pop(); - const 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(); + 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(); + } return arrayResult; }, processOptionalJSObjectArray: function bjs_processOptionalJSObjectArray(objects) { @@ -926,21 +1094,26 @@ export async function createInstantiator(options, swift) { i32Stack.push(objects.length); instance.exports.bjs_processOptionalJSObjectArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, processNestedJSObjectArray: function bjs_processNestedJSObjectArray(objects) { @@ -954,20 +1127,30 @@ export async function createInstantiator(options, swift) { i32Stack.push(objects.length); instance.exports.bjs_processNestedJSObjectArray(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - const 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); + 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); } - arrayResult1.reverse(); - arrayResult.push(arrayResult1); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, multiArrayParams: function bjs_multiArrayParams(nums, strs) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index bf368738e..a4c42674e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index 89ab29827..fd27e3d67 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -213,6 +214,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 7fd6a0d6b..6b6698377 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -212,6 +213,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index cafd250b0..8f8463bf0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -31,6 +31,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -140,6 +141,13 @@ export async function createInstantiator(options, swift) { 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_Config"] = function(objectId) { structHelpers.Config.lower(swift.memory.getObject(objectId)); } @@ -550,12 +558,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_testIntArrayDefault(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); return arrayResult; }, testStringArrayDefault: function bjs_testStringArrayDefault(names = ["a", "b", "c"]) { @@ -568,12 +581,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(names.length); instance.exports.bjs_testStringArrayDefault(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); + 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(); } - arrayResult.reverse(); return arrayResult; }, testDoubleArrayDefault: function bjs_testDoubleArrayDefault(values = [1.5, 2.5, 3.5]) { @@ -583,12 +601,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_testDoubleArrayDefault(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); + 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(); } - arrayResult.reverse(); return arrayResult; }, testBoolArrayDefault: function bjs_testBoolArrayDefault(flags = [true, false, true]) { @@ -598,12 +621,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(flags.length); instance.exports.bjs_testBoolArrayDefault(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); + 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(); } - arrayResult.reverse(); return arrayResult; }, testEmptyArrayDefault: function bjs_testEmptyArrayDefault(items = []) { @@ -613,12 +641,17 @@ export async function createInstantiator(options, swift) { i32Stack.push(items.length); instance.exports.bjs_testEmptyArrayDefault(); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); return arrayResult; }, testMixedWithArrayDefault: function bjs_testMixedWithArrayDefault(name = "test", values = [10, 20, 30], enabled = true) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 920017972..d040df41c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -139,6 +140,13 @@ export async function createInstantiator(options, swift) { 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_Counters"] = function(objectId) { structHelpers.Counters.lower(swift.memory.getObject(objectId)); } @@ -420,12 +428,17 @@ export async function createInstantiator(options, swift) { const dictResult = {}; for (let i = 0; i < dictLen; i++) { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i1 = 0; i1 < arrayLen; i1++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); const string = strStack.pop(); dictResult[string] = arrayResult; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 3d2230c6c..23819a6e8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -623,12 +624,17 @@ export async function createInstantiator(options, swift) { } case AllTypesResultValues.Tag.ArrayPayload: { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); return { tag: AllTypesResultValues.Tag.ArrayPayload, param0: arrayResult }; } case AllTypesResultValues.Tag.Empty: return { tag: AllTypesResultValues.Tag.Empty }; @@ -748,12 +754,17 @@ export async function createInstantiator(options, swift) { optValue = null; } else { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); optValue = arrayResult; } return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optValue }; @@ -831,6 +842,13 @@ export async function createInstantiator(options, swift) { 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)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index fe94c046f..5272717ec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -49,6 +49,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -122,6 +123,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 10fe31f64..ecf121aa4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -69,6 +69,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -142,6 +143,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index a6aeee4b0..247a11e54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -50,6 +50,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -123,6 +124,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 7e5334811..b004e3b74 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -100,6 +100,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -174,6 +175,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 53ddd7301..4aa424d68 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 346b74eac..f5895589d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index f74095374..77e8002f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index c2490c0ea..db876ff02 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index d970c5d77..ca958e564 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index d970c5d77..ca958e564 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 06cf6550e..613d4a10b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; @@ -193,12 +201,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_roundtrip"] = function bjs_roundtrip() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); + 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(); } - arrayResult.reverse(); let ret = imports.roundtrip(arrayResult); for (const elem of ret) { i32Stack.push((elem | 0)); @@ -211,12 +224,17 @@ export async function createInstantiator(options, swift) { TestModule["bjs_logStrings"] = function bjs_logStrings() { try { const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); + 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(); } - arrayResult.reverse(); imports.logStrings(arrayResult); } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index c469fcb58..ab4b4b34d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -137,6 +138,13 @@ export async function createInstantiator(options, swift) { 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_FooContainer"] = function(objectId) { structHelpers.FooContainer.lower(swift.memory.getObject(objectId)); } @@ -281,14 +289,19 @@ export async function createInstantiator(options, swift) { i32Stack.push(foos.length); instance.exports.bjs_processFooArray(); const arrayLen = i32Stack.pop(); - const 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); + 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(); } - arrayResult.reverse(); return arrayResult; }, processOptionalFooArray: function bjs_processOptionalFooArray(foos) { @@ -303,21 +316,26 @@ export async function createInstantiator(options, swift) { i32Stack.push(foos.length); instance.exports.bjs_processOptionalFooArray(); const arrayLen = i32Stack.pop(); - const 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; + 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.push(optValue); + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; }, roundtripFooContainer: function bjs_roundtripFooContainer(container) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 952197c2a..59c8be11d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index 88a5adb38..f3293ae52 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index 10fafb7a0..ef666149b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index ee51d4a28..b12640234 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 0258b63b6..71e66827e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -188,6 +189,13 @@ export async function createInstantiator(options, swift) { 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; @@ -302,15 +310,20 @@ export async function createInstantiator(options, swift) { TestModule["bjs_jsEchoJSValueArray"] = function bjs_jsEchoJSValueArray() { try { const arrayLen = i32Stack.pop(); - const 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); + 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(); } - arrayResult.reverse(); let ret = imports.jsEchoJSValueArray(arrayResult); for (const elem of ret) { const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); @@ -553,15 +566,20 @@ export async function createInstantiator(options, swift) { i32Stack.push(values.length); instance.exports.bjs_roundTripJSValueArray(); const arrayLen = i32Stack.pop(); - const 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); + 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(); } - arrayResult.reverse(); return arrayResult; }, roundTripOptionalJSValueArray: function bjs_roundTripOptionalJSValueArray(values) { @@ -581,15 +599,20 @@ export async function createInstantiator(options, swift) { let optResult; if (isSome1) { const arrayLen = i32Stack.pop(); - const 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); + 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(); } - arrayResult.reverse(); optResult = arrayResult; } else { optResult = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 195eef468..6c3ddb555 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index ca54493f6..70f1575b4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 3551caab2..16ec9433c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index a63df44be..d698857d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; @@ -341,13 +349,18 @@ export async function createInstantiator(options, swift) { getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const ptr = ptrStack.pop(); - const obj = Greeter.__construct(ptr); - arrayResult.push(obj); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const ptr = ptrStack.pop(); + const obj = Greeter.__construct(ptr); + arrayResult.push(obj); + } + arrayResult.reverse(); } - arrayResult.reverse(); 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 32a325bda..92b8f5dae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; @@ -341,13 +349,18 @@ export async function createInstantiator(options, swift) { getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const ptr = ptrStack.pop(); - const obj = Greeter.__construct(ptr); - arrayResult.push(obj); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const ptr = ptrStack.pop(); + const obj = Greeter.__construct(ptr); + arrayResult.push(obj); + } + arrayResult.reverse(); } - arrayResult.reverse(); 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 f276877e0..33b4e60c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -123,6 +124,13 @@ export async function createInstantiator(options, swift) { 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_User_Stats"] = function(objectId) { structHelpers.User_Stats.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 1d585ce0b..f376c1b24 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 490f2b4e2..97c1a44fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index bec07b959..a140ea232 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 7f840708e..b8116a32f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 9fb9b172b..d992bf75d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -49,6 +49,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -155,6 +156,13 @@ export async function createInstantiator(options, swift) { 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; @@ -722,14 +730,19 @@ export async function createInstantiator(options, swift) { get delegates() { instance.exports.bjs_DelegateManager_delegates_get(this.pointer); const arrayLen = i32Stack.pop(); - const arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - arrayResult.push(obj); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + arrayResult.push(obj); + } + arrayResult.reverse(); } - arrayResult.reverse(); return arrayResult; } set delegates(value) { @@ -783,14 +796,19 @@ export async function createInstantiator(options, swift) { i32Stack.push(delegates.length); instance.exports.bjs_processDelegates(); const arrayLen = i32Stack.pop(); - const 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); + 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(); } - arrayResult.reverse(); return arrayResult; }, processDelegatesByName: function bjs_processDelegatesByName(delegates) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index aefdb5679..89f84d29a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -123,6 +124,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index ef685b8a4..32a739587 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -36,6 +36,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -142,6 +143,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 1fd066076..16cf2881f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -36,6 +36,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -142,6 +143,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 5800fcb56..b616665ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -30,6 +30,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -103,6 +104,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index b81255810..f6e1fdbce 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -30,6 +30,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -103,6 +104,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 033f08cd2..885c0980f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index 8187b9e92..aab8b67fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 9ee57d692..88f04efe9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 0b4ca3dcc..c82bc5b8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -55,6 +55,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -226,6 +227,13 @@ export async function createInstantiator(options, swift) { 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_Animal"] = function(objectId) { structHelpers.Animal.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index d9df868ec..cffbdcf67 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -124,6 +125,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index abfb24d48..d55d5c095 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -30,6 +30,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -311,6 +312,13 @@ export async function createInstantiator(options, swift) { 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_DataPoint"] = function(objectId) { structHelpers.DataPoint.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index d4f1160f3..0197aefe8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -110,6 +111,13 @@ export async function createInstantiator(options, swift) { 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)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 4e0fd8341..2b51ebd3b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -123,6 +124,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index b2c381a03..9c41c3061 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -98,6 +99,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index ef81ef69e..97a00c278 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -115,6 +116,13 @@ export async function createInstantiator(options, swift) { 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_PointerFields"] = function(objectId) { structHelpers.PointerFields.lower(swift.memory.getObject(objectId)); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 97948b286..2951ef5f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -25,6 +25,7 @@ export async function createInstantiator(options, swift) { let f32Stack = []; let f64Stack = []; let ptrStack = []; + let taStack = []; const enumHelpers = {}; const structHelpers = {}; @@ -99,6 +100,13 @@ export async function createInstantiator(options, swift) { 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; diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 3dda6b28e..88e322538 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -68,6 +68,7 @@ async function createInstantiator(options, swift) { swift_js_push_i64: unexpectedBjsCall, swift_js_pop_i64: unexpectedBjsCall, swift_js_closure_unregister: unexpectedBjsCall, + swift_js_push_typed_array: unexpectedBjsCall, }; }, /** @param {WebAssembly.Instance} instance */ diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 86a1aaf3f..ff586b45b 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -154,6 +154,11 @@ public protocol _BridgedSwiftStackType { static func bridgeJSStackPopAsOptional() -> StackLiftResult? /// Specialization point for pushing an `Optional` static func bridgeJSStackPushAsOptional(_ value: consuming Self?) + + /// Specialization point for popping an `Array` from the bridge stack + static func bridgeJSStackPopAsArray() -> [StackLiftResult] + /// Specialization point for pushing an `Array` onto the bridge stack + static func bridgeJSStackPushAsArray(_ value: consuming [Self]) } extension _BridgedSwiftStackType { @@ -178,6 +183,25 @@ extension _BridgedSwiftStackType { _swift_js_push_i32(1) } } + + public static func bridgeJSStackPopAsArray() -> [StackLiftResult] { + let count = Int(_swift_js_pop_i32()) + var result: [StackLiftResult] = [] + result.reserveCapacity(count) + for _ in 0.. Float64 { _swift_js_pop_f64_extern() } +// MARK: Typed array bulk push extern + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_push_typed_array") +private func _swift_js_push_typed_array_extern(_ kind: Int32, _ ptr: UnsafeRawPointer, _ count: Int32) +#else +private func _swift_js_push_typed_array_extern(_ kind: Int32, _ ptr: UnsafeRawPointer, _ count: Int32) { + _onlyAvailableOnWasm() +} +#endif + +/// Pushes a typed array onto the JS typed-array stack via bulk copy. +@_spi(BridgeJS) @inline(never) public func _swift_js_push_typed_array( + _ kind: Int32, + _ ptr: UnsafeRawPointer, + _ count: Int32 +) { + _swift_js_push_typed_array_extern(kind, ptr, count) +} + +/// Numeric TypedArray kind identifiers (must match the JS `taCtors` table in BridgeJSLink). +public enum _BridgedNumericArrayKind: Int32 { + case int8 = 0 + case uint8 = 1 + case int16 = 2 + case uint16 = 3 + case int32 = 4 + case uint32 = 5 + case float32 = 6 + case float64 = 7 +} + +// MARK: - Numeric typed-array bulk push + +/// Numeric types that opt into bulk typed-array push. +public protocol _BridgedNumericArray: _BridgedSwiftStackType where StackLiftResult == Self { + static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { get } +} + +extension _BridgedNumericArray { + @_spi(BridgeJS) + public static func bridgeJSStackPushAsArray(_ value: consuming [Self]) { + value.withUnsafeBufferPointer { buffer in + guard let base = buffer.baseAddress else { + _swift_js_push_i32(0) + return + } + _swift_js_push_typed_array( + Self._bridgedNumericArrayKind.rawValue, + UnsafeRawPointer(base), + Int32(buffer.count) + ) + // -1 discriminator tells JS arrayLift to pop from the typed-array stack + _swift_js_push_i32(-1) + } + } +} + +extension Int8: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .int8 } +} +extension UInt8: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .uint8 } +} +extension Int16: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .int16 } +} +extension UInt16: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .uint16 } +} +extension Int32: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .int32 } +} +extension UInt32: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .uint32 } +} +extension Float: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .float32 } +} +extension Double: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { .float64 } +} +extension Int: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { + #if _pointerBitWidth(_32) + return .int32 + #else + return .int32 + #endif + } +} +extension UInt: _BridgedNumericArray { + public static var _bridgedNumericArrayKind: _BridgedNumericArrayKind { + #if _pointerBitWidth(_32) + return .uint32 + #else + return .uint32 + #endif + } +} + // MARK: Wasm externs used by type lowering/lifting #if arch(wasm32) @@ -1973,22 +2098,11 @@ extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, E public typealias StackLiftResult = [Element] @_spi(BridgeJS) public static func bridgeJSStackPop() -> [Element] { - let count = Int(_swift_js_pop_i32()) - var result: [Element] = [] - result.reserveCapacity(count) - for _ in 0.. [Element] { From d1e0f95a1ddee38a699889ba5ceb605e0ed4a6f8 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Tue, 2 Jun 2026 01:51:05 +0900 Subject: [PATCH 066/140] 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 067/140] 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 068/140] 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 069/140] 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 070/140] 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 071/140] 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 072/140] 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 073/140] 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 074/140] 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 075/140] [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 076/140] [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 077/140] [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 078/140] 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 079/140] 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 080/140] 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 081/140] 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 082/140] 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 083/140] 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 084/140] 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 085/140] 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 086/140] 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 087/140] 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 088/140] 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 089/140] 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 090/140] 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 091/140] 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 092/140] 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 093/140] 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 094/140] 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 095/140] 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 096/140] 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 097/140] 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 098/140] 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 099/140] 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 100/140] 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 101/140] 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 102/140] 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 103/140] 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 104/140] 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 105/140] 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 106/140] 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 107/140] 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 108/140] 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 109/140] 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 110/140] 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 111/140] 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 112/140] 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 113/140] =?UTF-8?q?BridgeJS:=20Don=E2=80=99t=20put=20dots?= =?UTF-8?q?=20in=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 114/140] 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 115/140] 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" ] }, From e0b98d89559f3b80f9e1585be08d1c31bff00e5d Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 4 Sep 2026 11:39:58 +0200 Subject: [PATCH 116/140] PackageToJS: Add selectable UWASI runtime --- Plugins/PackageToJS/README.md | 15 +- Plugins/PackageToJS/Sources/PackageToJS.swift | 18 +- .../Sources/PackageToJSPlugin.swift | 18 +- Plugins/PackageToJS/Templates/package.json | 4 + .../Templates/platforms/browser.js | 38 +++ .../PackageToJS/Templates/platforms/node.js | 31 ++ .../PackageToJS/Templates/platforms/uwasi.js | 65 ++++ .../Tests/Inputs/UWASIAdapterTests.mjs | 102 ++++++ .../Tests/PackagingPlannerTests.swift | 33 +- .../PackageToJS/Tests/TemplatesTests.swift | 45 ++- .../planBuild_debug.json | 24 +- .../planBuild_debug_uwasi.json | 311 ++++++++++++++++++ .../planBuild_release.json | 24 +- .../planBuild_release_dwarf.json | 24 +- .../planBuild_release_name.json | 24 +- .../planBuild_release_no_optimize.json | 24 +- .../PackagingPlannerTests/planTestBuild.json | 32 +- .../Articles/Package-Output-Structure.md | 20 +- package-lock.json | 7 + package.json | 1 + 20 files changed, 767 insertions(+), 93 deletions(-) create mode 100644 Plugins/PackageToJS/Templates/platforms/uwasi.js create mode 100644 Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs create mode 100644 Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json diff --git a/Plugins/PackageToJS/README.md b/Plugins/PackageToJS/README.md index cbcaf19c5..0e3e0e124 100644 --- a/Plugins/PackageToJS/README.md +++ b/Plugins/PackageToJS/README.md @@ -11,6 +11,20 @@ PackageToJS is a command plugin for Swift Package Manager that simplifies the pr - Build WebAssembly file and generate JavaScript wrappers - Test driver for Swift Testing and XCTest - Generated JS files can be consumed by JS bundler tools like Vite +- Select `@bjorn3/browser_wasi_shim` or `uwasi` for generated WASI packages + +## WASI Runtime + +PackageToJS uses `@bjorn3/browser_wasi_shim` by default. Pass `--wasi-runtime uwasi` +to generate browser and Node platform wrappers backed by `uwasi` instead: + +```bash +swift package --swift-sdk wasm32-unknown-wasi js --wasi-runtime uwasi +``` + +The generated browser main-thread setup rejects blocking WASI waits. Run guests that +require `poll_oneoff` clock waits in a worker. Node and browser workers use `uwasi`'s +blocking implementation. ## Requirements @@ -42,4 +56,3 @@ Please define the following environment variables when you want to run E2E tests - `SWIFT_SDK_ID`: Specifies the Swift SDK identifier to use - `SWIFT_BIN_PATH`: Specifies the `bin` path to the Swift toolchain to use - diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index c8adb9346..cf236c5cc 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -10,6 +10,11 @@ struct PackageToJS { case node } + enum WASIRuntime: String, CaseIterable { + case browserWASIShim = "browser-wasi-shim" + case uwasi + } + /// Path to the output directory var outputPath: String? /// The build configuration to use (default: debug) @@ -18,6 +23,8 @@ struct PackageToJS { var packageName: String? /// Target platform for the generated JavaScript (default: browser) var defaultPlatform: Platform = .browser + /// WASI runtime used by generated JavaScript (default: browser-wasi-shim) + var wasiRuntime: WASIRuntime = .browserWASIShim /// Whether to explain the build plan (default: false) var explain: Bool = false /// Whether to print verbose output @@ -625,7 +632,7 @@ struct PackagingPlanner { } // Copy the template files - for (file, output) in [ + var templateFiles = [ ("Plugins/PackageToJS/Templates/index.js", "index.js"), ("Plugins/PackageToJS/Templates/index.d.ts", "index.d.ts"), ("Plugins/PackageToJS/Templates/instantiate.js", "instantiate.js"), @@ -637,7 +644,13 @@ struct PackagingPlanner { ("Plugins/PackageToJS/Templates/platforms/node.d.ts", "platforms/node.d.ts"), ("Sources/JavaScriptKit/Runtime/index.mjs", "runtime.js"), ("Sources/JavaScriptKit/Runtime/index.d.ts", "runtime.d.ts"), - ] { + ] + if options.wasiRuntime == .uwasi { + templateFiles.append( + ("Plugins/PackageToJS/Templates/platforms/uwasi.js", "platforms/uwasi.js") + ) + } + for (file, output) in templateFiles { packageInputs.append( planCopyTemplateFile( make: &make, @@ -943,6 +956,7 @@ struct PackagingPlanner { // this task instead, so a change in them still re-runs the preprocessing. let staticConditions: [String: Bool] = [ "USE_WASI_CDN": options.useCDN, + "USE_UWASI": options.wasiRuntime == .uwasi, "HAS_BRIDGE": skeletons.count > 0, "HAS_IMPORTS": skeletons.count > 0, "TARGET_DEFAULT_PLATFORM_NODE": options.defaultPlatform == .node, diff --git a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift index 560b3e980..5ee298624 100644 --- a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift +++ b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift @@ -599,6 +599,19 @@ extension ArgumentExtractor { } return platform } + + mutating func extractWASIRuntimeOption(named name: String) throws -> PackageToJS.PackageOptions.WASIRuntime { + guard let stringValue = self.extractOption(named: name).last else { + return .browserWASIShim + } + + guard let runtime = PackageToJS.PackageOptions.WASIRuntime(rawValue: stringValue) else { + throw PackageToJSError( + "Invalid WASI runtime: \(stringValue), expected one of \(PackageToJS.PackageOptions.WASIRuntime.allCases.map(\.rawValue).joined(separator: ", "))" + ) + } + return runtime + } } extension PackageToJS.PackageOptions { @@ -608,6 +621,7 @@ extension PackageToJS.PackageOptions { (extractor.extractOption(named: "configuration") + extractor.extractSingleDashOption(named: "c")).last let packageName = extractor.extractOption(named: "package-name").last let defaultPlatform = try extractor.extractPlatformOption(named: "default-platform") + let wasiRuntime = try extractor.extractWASIRuntimeOption(named: "wasi-runtime") let explain = extractor.extractFlag(named: "explain") let useCDN = extractor.extractFlag(named: "use-cdn") let verbose = extractor.extractFlag(named: "verbose") @@ -617,6 +631,7 @@ extension PackageToJS.PackageOptions { configuration: configuration, packageName: packageName, defaultPlatform: defaultPlatform, + wasiRuntime: wasiRuntime, explain: explain != 0, verbose: verbose != 0, useCDN: useCDN != 0, @@ -629,7 +644,8 @@ extension PackageToJS.PackageOptions { --output Path to the output directory (default: .build/plugins/PackageToJS/outputs/Package) -c, --configuration The build configuration to use (values: debug, release; default: debug) --package-name Name of the package (default: lowercased Package.swift name) - --platform Target platform for generated JavaScript (values: \(PackageToJS.PackageOptions.Platform.allCases.map(\.rawValue).joined(separator: ", ")); default: \(PackageToJS.PackageOptions.Platform.browser)) + --default-platform Target platform for generated JavaScript (values: \(PackageToJS.PackageOptions.Platform.allCases.map(\.rawValue).joined(separator: ", ")); default: \(PackageToJS.PackageOptions.Platform.browser)) + --wasi-runtime WASI runtime for generated JavaScript (values: \(PackageToJS.PackageOptions.WASIRuntime.allCases.map(\.rawValue).joined(separator: ", ")); default: \(PackageToJS.PackageOptions.WASIRuntime.browserWASIShim.rawValue)) --use-cdn Whether to use CDN for dependency packages --enable-code-coverage Whether to enable code coverage collection --explain Whether to explain the build plan diff --git a/Plugins/PackageToJS/Templates/package.json b/Plugins/PackageToJS/Templates/package.json index a3e7074bb..02354e496 100644 --- a/Plugins/PackageToJS/Templates/package.json +++ b/Plugins/PackageToJS/Templates/package.json @@ -8,6 +8,10 @@ "./wasm": "./@PACKAGE_TO_JS_MODULE_PATH@" }, "dependencies": { +/* #if USE_UWASI */ + "uwasi": "1.6.0" +/* #else */ "@bjorn3/browser_wasi_shim": "0.3.0" +/* #endif */ } } diff --git a/Plugins/PackageToJS/Templates/platforms/browser.js b/Plugins/PackageToJS/Templates/platforms/browser.js index d471e8415..2b036699d 100644 --- a/Plugins/PackageToJS/Templates/platforms/browser.js +++ b/Plugins/PackageToJS/Templates/platforms/browser.js @@ -1,6 +1,15 @@ // @ts-check import { MODULE_PATH /* #if USE_SHARED_MEMORY */, MEMORY_TYPE /* #endif */} from "../instantiate.js" /* #if IS_WASI */ +/* #if USE_UWASI */ +/* #if USE_WASI_CDN */ +// @ts-ignore +import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'https://cdn.jsdelivr.net/npm/uwasi@1.6.0/+esm'; +/* #else */ +import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'uwasi'; +/* #endif */ +import { browserMainThreadSleep, createUwasi } from './uwasi.js'; +/* #else */ /* #if USE_WASI_CDN */ // @ts-ignore import { WASI, File, OpenFile, ConsoleStdout, PreopenDirectory } from 'https://cdn.jsdelivr.net/npm/@bjorn3/browser_wasi_shim@0.4.1/+esm'; @@ -9,6 +18,7 @@ import { WASI, File, OpenFile, ConsoleStdout, PreopenDirectory } from 'https://c import { WASI, File, OpenFile, ConsoleStdout, PreopenDirectory } from '@bjorn3/browser_wasi_shim'; /* #endif */ /* #endif */ +/* #endif */ /* #if USE_SHARED_MEMORY */ export async function defaultBrowserThreadSetup() { @@ -27,6 +37,12 @@ export async function defaultBrowserThreadSetup() { } /* #if IS_WASI */ +/* #if USE_UWASI */ + const { wasi } = createUwasi( + { WASI, MemoryFileSystem, useAll, lineBuffered }, + { modulePath: MODULE_PATH } + ) +/* #else */ const wasi = new WASI(/* args */[MODULE_PATH], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin ConsoleStdout.lineBuffered((stdout) => { @@ -37,14 +53,19 @@ export async function defaultBrowserThreadSetup() { }), new PreopenDirectory("/", new Map()), ], { debug: false }) +/* #endif */ /* #endif */ return { /* #if IS_WASI */ +/* #if USE_UWASI */ + wasi, +/* #else */ wasi: Object.assign(wasi, { setInstance(instance) { wasi.inst = instance; } }), +/* #endif */ /* #endif */ threadChannel, } @@ -105,6 +126,18 @@ export async function defaultBrowserSetup(options) { const args = options.args ?? [] const onStdoutLine = options.onStdoutLine ?? ((line) => console.log(line)) const onStderrLine = options.onStderrLine ?? ((line) => console.error(line)) +/* #if USE_UWASI */ + const { wasi } = createUwasi( + { WASI, MemoryFileSystem, useAll, lineBuffered }, + { + modulePath: MODULE_PATH, + args, + onStdoutLine, + onStderrLine, + sleep: browserMainThreadSleep(), + } + ) +/* #else */ const wasi = new WASI(/* args */[MODULE_PATH, ...args], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin ConsoleStdout.lineBuffered((stdout) => { @@ -116,6 +149,7 @@ export async function defaultBrowserSetup(options) { new PreopenDirectory("/", new Map()), ], { debug: false }) /* #endif */ +/* #endif */ /* #if USE_SHARED_MEMORY */ const memory = new WebAssembly.Memory(MEMORY_TYPE); const threadChannel = new DefaultBrowserThreadRegistry(options.spawnWorker || createDefaultWorkerFactory()) @@ -127,12 +161,16 @@ export async function defaultBrowserSetup(options) { getImports() { return options.getImports() }, /* #endif */ /* #if IS_WASI */ +/* #if USE_UWASI */ + wasi, +/* #else */ wasi: Object.assign(wasi, { setInstance(instance) { wasi.inst = instance; } }), /* #endif */ +/* #endif */ /* #if USE_SHARED_MEMORY */ memory, threadChannel, /* #endif */ diff --git a/Plugins/PackageToJS/Templates/platforms/node.js b/Plugins/PackageToJS/Templates/platforms/node.js index 3e1253965..b01290252 100644 --- a/Plugins/PackageToJS/Templates/platforms/node.js +++ b/Plugins/PackageToJS/Templates/platforms/node.js @@ -3,8 +3,13 @@ import { fileURLToPath } from "node:url"; import { Worker, parentPort } from "node:worker_threads"; import { MODULE_PATH /* #if USE_SHARED_MEMORY */, MEMORY_TYPE /* #endif */} from "../instantiate.js" /* #if IS_WASI */ +/* #if USE_UWASI */ +import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'uwasi'; +import { createUwasi } from './uwasi.js'; +/* #else */ import { WASI, File, OpenFile, ConsoleStdout, PreopenDirectory, Directory, Inode } from '@bjorn3/browser_wasi_shim'; /* #endif */ +/* #endif */ /* #if USE_SHARED_MEMORY */ export async function defaultNodeThreadSetup() { @@ -22,6 +27,12 @@ export async function defaultNodeThreadSetup() { } } +/* #if USE_UWASI */ + const { wasi } = createUwasi( + { WASI, MemoryFileSystem, useAll, lineBuffered }, + { modulePath: MODULE_PATH } + ) +/* #else */ const wasi = new WASI(/* args */[MODULE_PATH], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin ConsoleStdout.lineBuffered((stdout) => { @@ -32,13 +43,18 @@ export async function defaultNodeThreadSetup() { }), new PreopenDirectory("/", new Map()), ], { debug: false }) +/* #endif */ return { +/* #if USE_UWASI */ + wasi, +/* #else */ wasi: Object.assign(wasi, { setInstance(instance) { wasi.inst = instance; } }), +/* #endif */ threadChannel, } } @@ -119,6 +135,16 @@ export async function defaultNodeSetup(options = {}) { const { readFile } = await import("node:fs/promises") const args = options.args ?? process.argv.slice(2) +/* #if USE_UWASI */ + const { wasi } = createUwasi( + { WASI, MemoryFileSystem, useAll, lineBuffered }, + { + modulePath: MODULE_PATH, + args, + withExtractFile: true, + } + ) +/* #else */ const rootFs = new Map(); const wasi = new WASI(/* args */[MODULE_PATH, ...args], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin @@ -130,6 +156,7 @@ export async function defaultNodeSetup(options = {}) { }), new PreopenDirectory("/", rootFs), ], { debug: false }) +/* #endif */ const pkgDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))) const module = await WebAssembly.compile(new Uint8Array(await readFile(path.join(pkgDir, MODULE_PATH)))) /* #if USE_SHARED_MEMORY */ @@ -143,6 +170,9 @@ export async function defaultNodeSetup(options = {}) { getImports() { return {} }, /* #endif */ /* #if IS_WASI */ +/* #if USE_UWASI */ + wasi, +/* #else */ wasi: Object.assign(wasi, { setInstance(instance) { wasi.inst = instance; @@ -184,6 +214,7 @@ export async function defaultNodeSetup(options = {}) { return undefined; } }), +/* #endif */ addToCoreImports(importObject) { importObject["wasi_snapshot_preview1"]["proc_exit"] = (code) => { if (options.onExit) { diff --git a/Plugins/PackageToJS/Templates/platforms/uwasi.js b/Plugins/PackageToJS/Templates/platforms/uwasi.js new file mode 100644 index 000000000..e7a9ce1bc --- /dev/null +++ b/Plugins/PackageToJS/Templates/platforms/uwasi.js @@ -0,0 +1,65 @@ +// @ts-check + +/** + * Refuse blocking waits on the browser main thread, where UWASI would otherwise + * busy-wait. Workers and non-browser hosts can use UWASI's blocking default. + * + * @returns {((milliseconds: number) => void) | undefined} + */ +export function browserMainThreadSleep() { + if (typeof document === "undefined") return undefined; + return (milliseconds) => { + throw new Error( + `A WASI poll_oneoff wait of ${milliseconds}ms cannot block the browser main thread. ` + + "Run the guest in a worker to support blocking waits.", + ); + }; +} + +/** + * @param {{ WASI: any, MemoryFileSystem: any, useAll: any, lineBuffered: any }} runtime + * @param {{ + * modulePath: string, + * args?: string[], + * onStdoutLine?: (line: string) => void, + * onStderrLine?: (line: string) => void, + * sleep?: (milliseconds: number) => void, + * withExtractFile?: boolean, + * }} options + */ +export function createUwasi(runtime, options) { + const args = options.args ?? []; + const onStdoutLine = options.onStdoutLine ?? ((line) => console.log(line)); + const onStderrLine = + options.onStderrLine ?? ((line) => console.error(line)); + const fileSystem = new runtime.MemoryFileSystem({ "/": "/" }); + const stdout = runtime.lineBuffered(onStdoutLine); + const stderr = runtime.lineBuffered(onStderrLine); + const wasi = new runtime.WASI({ + args: [options.modulePath, ...args], + env: {}, + features: [ + runtime.useAll({ + withFileSystem: fileSystem, + withStdio: { + stdin: () => "", + stdout, + stderr, + outputBuffers: true, + }, + sleep: options.sleep, + }), + ], + }); + + if (options.withExtractFile) { + Object.assign(wasi, { + extractFile(filePath) { + const node = fileSystem.lookup(filePath); + return node && node.type === "file" ? node.content : undefined; + }, + }); + } + + return { wasi, fileSystem }; +} diff --git a/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs new file mode 100644 index 000000000..3a1b37f26 --- /dev/null +++ b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { MemoryFileSystem, useAll, WASI } from "uwasi"; + +import { + browserMainThreadSleep, + createUwasi, +} from "../../Templates/platforms/uwasi.js"; + +test("PackageToJS UWASI adapter preserves its host contracts", () => { + const stdout = []; + const stderr = []; + let lineBufferedCalls = 0; + const lineBuffered = (writeLine) => { + lineBufferedCalls += 1; + return (chunk) => { + const line = new TextDecoder().decode(chunk).replace(/\n$/, ""); + writeLine(line); + }; + }; + const { wasi, fileSystem } = createUwasi( + { WASI, MemoryFileSystem, useAll, lineBuffered }, + { + modulePath: "main.wasm", + onStdoutLine: (line) => stdout.push(line), + onStderrLine: (line) => stderr.push(line), + withExtractFile: true, + }, + ); + const memory = new WebAssembly.Memory({ initial: 1 }); + wasi.setInstance({ exports: { memory } }); + + const view = new DataView(memory.buffer); + const bytes = new Uint8Array(memory.buffer); + const write = (fd, chunk) => { + bytes.set(chunk, 64); + view.setUint32(0, 64, true); + view.setUint32(4, chunk.length, true); + assert.equal(wasi.wasiImport.fd_write(fd, 0, 1, 8), 0); + assert.equal(view.getUint32(8, true), chunk.length); + }; + + write(1, new TextEncoder().encode("output\n")); + write(2, new TextEncoder().encode("error\n")); + assert.equal(lineBufferedCalls, 2); + assert.deepEqual(stdout, ["output"]); + assert.deepEqual(stderr, ["error"]); + + fileSystem.addFile("/output.txt", "result"); + assert.equal( + new TextDecoder().decode(wasi.extractFile("/output.txt")), + "result", + ); +}); + +test("PackageToJS forwards the host sleep policy", () => { + const { wasi } = createUwasi( + { + WASI, + MemoryFileSystem, + useAll, + lineBuffered: (writeLine) => writeLine, + }, + { + modulePath: "main.wasm", + sleep(milliseconds) { + throw new Error(`cannot block for ${milliseconds}ms`); + }, + }, + ); + const memory = new WebAssembly.Memory({ initial: 1 }); + wasi.setInstance({ exports: { memory } }); + + const view = new DataView(memory.buffer); + view.setBigUint64(0, 0n, true); + view.setUint8(8, 0); + view.setUint32(16, 1, true); + view.setBigUint64(24, 1_000_000n, true); + view.setBigUint64(32, 0n, true); + view.setUint16(40, 0, true); + + assert.throws( + () => wasi.wasiImport.poll_oneoff(0, 128, 1, 256), + /cannot block for 1ms/, + ); +}); + +test("PackageToJS blocks waits only on the browser main thread", () => { + assert.equal(browserMainThreadSleep(), undefined); + + globalThis.document = {}; + try { + const sleep = browserMainThreadSleep(); + assert.equal(typeof sleep, "function"); + assert.throws( + () => sleep(5), + /cannot block the browser main thread.*Run the guest in a worker/, + ); + } finally { + delete globalThis.document; + } +}); diff --git a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift index 4cff48e6c..2341f59af 100644 --- a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift +++ b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift @@ -47,24 +47,43 @@ import Testing } typealias DebugInfoFormat = PackageToJS.DebugInfoFormat + typealias WASIRuntime = PackageToJS.PackageOptions.WASIRuntime @Test(arguments: [ - (variant: "debug", configuration: "debug", noOptimize: false, debugInfoFormat: DebugInfoFormat.none), - (variant: "release", configuration: "release", noOptimize: false, debugInfoFormat: DebugInfoFormat.none), + ( + variant: "debug", configuration: "debug", noOptimize: false, + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + ), + ( + variant: "debug_uwasi", configuration: "debug", noOptimize: false, + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.uwasi + ), + ( + variant: "release", configuration: "release", noOptimize: false, + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + ), ( variant: "release_no_optimize", configuration: "release", noOptimize: true, - debugInfoFormat: DebugInfoFormat.none + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + ), + ( + variant: "release_dwarf", configuration: "release", noOptimize: false, + debugInfoFormat: DebugInfoFormat.dwarf, wasiRuntime: WASIRuntime.browserWASIShim + ), + ( + variant: "release_name", configuration: "release", noOptimize: false, + debugInfoFormat: DebugInfoFormat.name, wasiRuntime: WASIRuntime.browserWASIShim ), - (variant: "release_dwarf", configuration: "release", noOptimize: false, debugInfoFormat: DebugInfoFormat.dwarf), - (variant: "release_name", configuration: "release", noOptimize: false, debugInfoFormat: DebugInfoFormat.name), ]) func planBuild( variant: String, configuration: String, noOptimize: Bool, - debugInfoFormat: PackageToJS.DebugInfoFormat + debugInfoFormat: PackageToJS.DebugInfoFormat, + wasiRuntime: WASIRuntime ) throws { - let options = PackageToJS.PackageOptions() + var options = PackageToJS.PackageOptions() + options.wasiRuntime = wasiRuntime let system = TestPackagingSystem() let planner = PackagingPlanner( options: options, diff --git a/Plugins/PackageToJS/Tests/TemplatesTests.swift b/Plugins/PackageToJS/Tests/TemplatesTests.swift index 5a27259c3..cc2b4d2a0 100644 --- a/Plugins/PackageToJS/Tests/TemplatesTests.swift +++ b/Plugins/PackageToJS/Tests/TemplatesTests.swift @@ -15,9 +15,14 @@ import Foundation .appendingPathComponent("TemporaryDirectory") /// `npx tsc -p Templates/tsconfig.json` - /// Test both node and browser platform variants - @Test(arguments: ["node", "browser"]) - func tscCheck(platform: String) throws { + /// Test both WASI runtimes in node and browser platform variants. + @Test(arguments: [ + (platform: "node", runtime: "browser-wasi-shim", sharedMemory: false), + (platform: "browser", runtime: "browser-wasi-shim", sharedMemory: false), + (platform: "node", runtime: "uwasi", sharedMemory: false), + (platform: "browser", runtime: "uwasi", sharedMemory: true), + ]) + func tscCheck(platform: String, runtime: String, sharedMemory: Bool) throws { // Use a local temporary directory to place instantiated templates so that // they can reference repo-root node_modules packages like @types/node. try FileManager.default.createDirectory( @@ -32,9 +37,10 @@ import Foundation // Setup preprocessing conditions let conditions: [String: Bool] = [ - "USE_SHARED_MEMORY": false, + "USE_SHARED_MEMORY": sharedMemory, "IS_WASI": true, "USE_WASI_CDN": false, + "USE_UWASI": runtime == "uwasi", "HAS_BRIDGE": false, "HAS_IMPORTS": false, "TARGET_DEFAULT_PLATFORM_NODE": platform == "node", @@ -47,6 +53,7 @@ import Foundation while let fileURL = enumerator?.nextObject() as? URL { guard !fileURL.hasDirectoryPath, fileURL.pathExtension == "js" || fileURL.pathExtension == "ts" + || fileURL.pathExtension == "json" else { continue } @@ -63,6 +70,36 @@ import Foundation try tsc.run() tsc.waitUntilExit() #expect(tsc.terminationStatus == 0) + + let platformSource = try String( + contentsOf: destination.appending(path: "platforms/") + .appending(path: "\(platform).js"), + encoding: .utf8 + ) + let expectedImport = runtime == "uwasi" ? "from 'uwasi'" : "from '@bjorn3/browser_wasi_shim'" + #expect(platformSource.contains(expectedImport)) + + let manifestData = try Data(contentsOf: destination.appending(path: "package.json")) + let manifest = try #require( + JSONSerialization.jsonObject(with: manifestData) as? [String: Any] + ) + let dependencies = try #require(manifest["dependencies"] as? [String: String]) + let expectedDependency = runtime == "uwasi" ? "uwasi" : "@bjorn3/browser_wasi_shim" + #expect(dependencies.keys.sorted() == [expectedDependency]) } } + + @Test func uwasiAdapterBehavior() throws { + let node = Process() + node.executableURL = try which("node") + node.arguments = [ + "--test", + Self.pluginPackagePath + .appending(path: "Tests/Inputs/UWASIAdapterTests.mjs") + .path, + ] + try node.run() + node.waitUntilExit() + #expect(node.terminationStatus == 0) + } } diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json index fefcda9b2..a21b94fd6 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json new file mode 100644 index 000000000..0948e2b74 --- /dev/null +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json @@ -0,0 +1,311 @@ +[ + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$INTERMEDIATES", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$WASM_PRODUCT_ARTIFACT" + ], + "output" : "$INTERMEDIATES\/wasm-imports.json", + "wants" : [ + "$INTERMEDIATES" + ] + }, + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$OUTPUT", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/index.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/index.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/index.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/index.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/instantiate.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/instantiate.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/instantiate.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/instantiate.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$WASM_PRODUCT_ARTIFACT" + ], + "output" : "$OUTPUT\/main.wasm", + "wants" : [ + "$OUTPUT" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/package.json", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" + ] + }, + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$OUTPUT\/platforms", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.worker.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.worker.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/node.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/node.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/node.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/node.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/uwasi.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/uwasi.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Sources\/JavaScriptKit\/Runtime\/index.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/runtime.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Sources\/JavaScriptKit\/Runtime\/index.mjs", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/runtime.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + "phony", + "silent" + ], + "inputs" : [ + + ], + "output" : "all", + "wants" : [ + "$OUTPUT\/main.wasm", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/package.json", + "$OUTPUT\/index.js", + "$OUTPUT\/index.d.ts", + "$OUTPUT\/instantiate.js", + "$OUTPUT\/instantiate.d.ts", + "$OUTPUT\/platforms\/browser.js", + "$OUTPUT\/platforms\/browser.d.ts", + "$OUTPUT\/platforms\/browser.worker.js", + "$OUTPUT\/platforms\/node.js", + "$OUTPUT\/platforms\/node.d.ts", + "$OUTPUT\/runtime.js", + "$OUTPUT\/runtime.d.ts", + "$OUTPUT\/platforms\/uwasi.js" + ] + } +] \ No newline at end of file diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json index 32fc2b670..d2f0d0f38 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json @@ -60,7 +60,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -77,7 +77,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -94,7 +94,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -111,7 +111,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -142,7 +142,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -187,7 +187,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -204,7 +204,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -221,7 +221,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -238,7 +238,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -255,7 +255,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -272,7 +272,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json index fefcda9b2..a21b94fd6 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json index 32fc2b670..d2f0d0f38 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json @@ -60,7 +60,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -77,7 +77,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -94,7 +94,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -111,7 +111,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -142,7 +142,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -187,7 +187,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -204,7 +204,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -221,7 +221,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -238,7 +238,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -255,7 +255,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -272,7 +272,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", 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 fefcda9b2..a21b94fd6 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json index b6b382ae3..3c4029927 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json @@ -72,7 +72,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/bin\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -89,7 +89,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -106,7 +106,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -123,7 +123,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -140,7 +140,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -198,7 +198,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -215,7 +215,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -232,7 +232,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -249,7 +249,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -266,7 +266,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -283,7 +283,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -300,7 +300,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -317,7 +317,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.browser.html", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -334,7 +334,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -351,7 +351,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md index af9b0d2bd..3ad1eed93 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md @@ -22,7 +22,8 @@ The output package has the following structure: ├── browser.js # Browser-specific platform setup ├── browser.d.ts # TypeScript definitions for browser.js ├── node.js # Node.js-specific platform setup - └── node.d.ts # TypeScript definitions for node.js + ├── node.d.ts # TypeScript definitions for node.js + └── uwasi.js # Shared uwasi adapter, when selected ``` ## Using the Package @@ -123,6 +124,14 @@ The `platforms/` directory contains platform-specific setup functions: - `platforms/browser.js` - Provides `defaultBrowserSetup()` for browser environments - `platforms/node.js` - Provides `defaultNodeSetup()` for Node.js environments +PackageToJS uses `@bjorn3/browser_wasi_shim` for WASI packages by default. Pass +`--wasi-runtime uwasi` to generate both platform wrappers against `uwasi`; this also +adds `platforms/uwasi.js` to the package. + +The browser main-thread setup rejects blocking `poll_oneoff` clock waits instead of +freezing the page. Run guests that require blocking waits in a worker. Node and browser +workers use `uwasi`'s blocking implementation. + ## Package Metadata (`package.json`) The generated `package.json` includes: @@ -143,6 +152,14 @@ The generated `package.json` includes: } ``` +With `--wasi-runtime uwasi`, the generated dependency is instead: + +```json +"dependencies": { + "uwasi": "1.6.0" +} +``` + The `exports` field allows importing the package as an npm dependency: ```javascript @@ -152,4 +169,3 @@ import { init } from '.build/plugins/PackageToJS/outputs/Package'; ## TypeScript Support All JavaScript files have corresponding `.d.ts` TypeScript definition files, providing full type safety when using the package in TypeScript projects. - diff --git a/package-lock.json b/package-lock.json index ea24d1645..7f846142a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", "typescript": "^5.8.2", + "uwasi": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", "vitest": "^4.0.18" } }, @@ -1581,6 +1582,12 @@ "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", "dev": true }, + "node_modules/uwasi": { + "version": "1.6.0-pending.pr25.pr26", + "resolved": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/vite": { "version": "7.3.2", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz", diff --git a/package.json b/package.json index 866b2bb6f..a8af35ac8 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", "typescript": "^5.8.2", + "uwasi": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", "vitest": "^4.0.18" } } From a5cbe7a4c6a9136542cb2a8d45f347303e8dd139 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 7 Sep 2026 13:10:38 +0200 Subject: [PATCH 117/140] PackageToJS: Use released UWASI 1.5.2 and stabilize sleep test --- Plugins/PackageToJS/Templates/package.json | 2 +- Plugins/PackageToJS/Templates/platforms/browser.js | 2 +- Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs | 3 ++- .../Articles/Package-Output-Structure.md | 2 +- package-lock.json | 7 ++++--- package.json | 2 +- 6 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Plugins/PackageToJS/Templates/package.json b/Plugins/PackageToJS/Templates/package.json index 02354e496..482b7fe9d 100644 --- a/Plugins/PackageToJS/Templates/package.json +++ b/Plugins/PackageToJS/Templates/package.json @@ -9,7 +9,7 @@ }, "dependencies": { /* #if USE_UWASI */ - "uwasi": "1.6.0" + "uwasi": "1.5.2" /* #else */ "@bjorn3/browser_wasi_shim": "0.3.0" /* #endif */ diff --git a/Plugins/PackageToJS/Templates/platforms/browser.js b/Plugins/PackageToJS/Templates/platforms/browser.js index 2b036699d..e8c596308 100644 --- a/Plugins/PackageToJS/Templates/platforms/browser.js +++ b/Plugins/PackageToJS/Templates/platforms/browser.js @@ -4,7 +4,7 @@ import { MODULE_PATH /* #if USE_SHARED_MEMORY */, MEMORY_TYPE /* #endif */} from /* #if USE_UWASI */ /* #if USE_WASI_CDN */ // @ts-ignore -import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'https://cdn.jsdelivr.net/npm/uwasi@1.6.0/+esm'; +import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'https://cdn.jsdelivr.net/npm/uwasi@1.5.2/+esm'; /* #else */ import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'uwasi'; /* #endif */ diff --git a/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs index 3a1b37f26..94dfab59e 100644 --- a/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs +++ b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs @@ -53,7 +53,8 @@ test("PackageToJS UWASI adapter preserves its host contracts", () => { ); }); -test("PackageToJS forwards the host sleep policy", () => { +test("PackageToJS forwards the host sleep policy", (t) => { + t.mock.method(performance, "now", () => 0); const { wasi } = createUwasi( { WASI, diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md index 3ad1eed93..6f3d30ac9 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md @@ -156,7 +156,7 @@ With `--wasi-runtime uwasi`, the generated dependency is instead: ```json "dependencies": { - "uwasi": "1.6.0" + "uwasi": "1.5.2" } ``` diff --git a/package-lock.json b/package-lock.json index 7f846142a..7dd81a320 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", "typescript": "^5.8.2", - "uwasi": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", + "uwasi": "1.5.2", "vitest": "^4.0.18" } }, @@ -1583,8 +1583,9 @@ "dev": true }, "node_modules/uwasi": { - "version": "1.6.0-pending.pr25.pr26", - "resolved": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/uwasi/-/uwasi-1.5.2.tgz", + "integrity": "sha512-gglUvZ3Q5ye1DXUiSF7jnKT8dYqOzOpanIqT7Jd3brJ23V91JnvzK43F+f4SfHBA+IrhLXgfBWWF393Hp7xYFw==", "dev": true, "license": "Apache-2.0" }, diff --git a/package.json b/package.json index a8af35ac8..4e4fdd7bb 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", "typescript": "^5.8.2", - "uwasi": "git+https://github.com/PassiveLogic/uwasi.git#ddd111bd2cbd03189de184e5dd27e7cb02802d3f", + "uwasi": "1.5.2", "vitest": "^4.0.18" } } From 712c3a7509280e61ec3742b548415dc29cb094a9 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 7 Sep 2026 15:19:12 +0200 Subject: [PATCH 118/140] BridgeJS: Diagnose unsupported protocol conformers before lowering --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 8 +- .../Sources/BridgeJSCore/ExportSwift.swift | 30 +++--- .../Sources/BridgeJSCore/ImportTS.swift | 8 +- .../BridgeJSCore/SwiftToSkeleton.swift | 95 +++++++++++++++++++ .../BridgeJSCore/TypeDeclResolver.swift | 7 ++ .../CrossModuleResolutionTests.swift | 21 ++++ .../BridgeJSToolTests/DiagnosticsTests.swift | 92 ++++++++++++++++++ .../BridgeJSCodegenTests/Alias.swift | 2 +- .../BridgeJSCodegenTests/Protocol.swift | 12 +-- .../ProtocolInClosure.swift | 10 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 17 ++++ .../Generated/BridgeJS.swift | 26 ++--- 12 files changed, 283 insertions(+), 45 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 969b3c01e..25de94da1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -182,15 +182,15 @@ public struct ClosureCodegen { } else { printer.write("let result = \(closureCallExpr)") switch signature.returnType { - case .swiftProtocol: + case .swiftProtocol(let protocolName): printer.write( - "return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" + "return _bridgeJSUnwrapProtocolExportable(result, \"\(protocolName)\").bridgeJSLowerAsProtocolReturn()" ) - case .nullable(.swiftProtocol, _): + case .nullable(.swiftProtocol(let protocolName), _): printer.write("if let result {") printer.indent { printer.write( - "_swift_js_return_optional_object(1, (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + "_swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(result, \"\(protocolName)\").bridgeJSLowerAsProtocolReturn())" ) } printer.write("} else {") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 55b5889fe..d976c9a39 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -262,8 +262,8 @@ public class ExportSwift { private func protocolCastSuffix(for returnType: BridgeType) -> (prefix: String, suffix: String) { switch returnType { - case .swiftProtocol: - return ("", " as! _BridgedSwiftProtocolExportable") + case .swiftProtocol(let name): + return ("_bridgeJSUnwrapProtocolExportable(", ", \"\(name)\")") default: return ("", "") } @@ -424,11 +424,11 @@ public class ExportSwift { } case .swiftProtocol: append("return ret.bridgeJSLowerAsProtocolReturn()") - case .nullable(.swiftProtocol, _): + case .nullable(.swiftProtocol(let protocolName), _): append( """ if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "\(raw: protocolName)").bridgeJSLowerAsProtocolReturn()) } else { _swift_js_return_optional_object(0, 0) } @@ -993,9 +993,9 @@ struct StackCodegen { return ["\(raw: accessor).bridgeJSStackPush()"] case .jsObject(_?): return ["\(raw: accessor).jsObject.bridgeJSStackPush()"] - case .swiftProtocol: + case .swiftProtocol(let protocolName): return [ - "_swift_js_push_i32((\(raw: accessor) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + "_swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(\(raw: accessor), \"\(raw: protocolName)\").bridgeJSLowerAsProtocolReturn())" ] case .void, .namespaceEnum: return [] @@ -1016,8 +1016,8 @@ struct StackCodegen { varPrefix: String ) -> [CodeBlockItemSyntax] { switch elementType { - case .swiftProtocol: - return lowerProtocolArrayStatements(accessor: accessor, varPrefix: varPrefix) + case .swiftProtocol(let protocolName): + return lowerProtocolArrayStatements(protocolName: protocolName, accessor: accessor, varPrefix: varPrefix) case .void, .namespaceEnum: fatalError("Invalid array element type: \(elementType)") default: @@ -1026,6 +1026,7 @@ struct StackCodegen { } private func lowerProtocolArrayStatements( + protocolName: String, accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { @@ -1033,7 +1034,7 @@ struct StackCodegen { return [ """ for \(raw: elemVar) in \(raw: accessor) { - _swift_js_push_i32((\(raw: elemVar) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(\(raw: elemVar), "\(raw: protocolName)").bridgeJSLowerAsProtocolReturn()) } """, "_swift_js_push_i32(Int32(\(raw: accessor).count))", @@ -1048,8 +1049,12 @@ struct StackCodegen { switch valueType { case .jsObject(let className?) where className != "JSObject": return ["\(raw: accessor).mapValues { $0.jsObject }.bridgeJSStackPush()"] - case .swiftProtocol: - return lowerProtocolDictionaryStatements(accessor: accessor, varPrefix: varPrefix) + case .swiftProtocol(let protocolName): + return lowerProtocolDictionaryStatements( + protocolName: protocolName, + accessor: accessor, + varPrefix: varPrefix + ) case .nullable, .closure: return lowerDictionaryStatementsInline( valueType: valueType, @@ -1107,6 +1112,7 @@ struct StackCodegen { } private func lowerProtocolDictionaryStatements( + protocolName: String, accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { @@ -1115,7 +1121,7 @@ struct StackCodegen { """ for \(raw: pairVar) in \(raw: accessor) { \(raw: pairVar).key.bridgeJSStackPush() - _swift_js_push_i32((\(raw: pairVar).value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(\(raw: pairVar).value, "\(raw: protocolName)").bridgeJSLowerAsProtocolReturn()) } """, "_swift_js_push_i32(Int32(\(raw: accessor).count))", diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index cff1aa979..09bee37d6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -188,12 +188,12 @@ public struct ImportTS { } ) ) - } else if case .nullable(.swiftProtocol, _) = param.type, context == .exportSwift { + } else if case .nullable(.swiftProtocol(let protocolName), _) = param.type, context == .exportSwift { body.write("let \(pattern): (Int32, Int32)") body.write("if let \(param.name) {") body.indent { body.write( - "\(pattern) = (1, (\(param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn())" + "\(pattern) = (1, _bridgeJSUnwrapProtocolExportable(\(param.name), \"\(protocolName)\").bridgeJSLowerAsProtocolReturn())" ) } body.write("} else {") @@ -203,9 +203,9 @@ public struct ImportTS { body.write("}") } else { let initializerExpr: ExprSyntax - if case .swiftProtocol = param.type, context == .exportSwift { + if case .swiftProtocol(let protocolName) = param.type, context == .exportSwift { initializerExpr = ExprSyntax( - "(\(raw: param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" + "_bridgeJSUnwrapProtocolExportable(\(raw: param.name), \"\(raw: protocolName)\").bridgeJSLowerAsProtocolReturn()" ) } else { initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index fb81d9089..2fc6f8db3 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -295,6 +295,8 @@ public final class SwiftToSkeleton { collector.finalize(&exported) } + perSourceErrors.append(contentsOf: diagnoseProtocolConformances(in: exported)) + if !perSourceErrors.isEmpty { let diagnostics = perSourceErrors.flatMap { inputFilePath, errors in errors.map { (file: inputFilePath, diagnostic: $0) } @@ -318,6 +320,99 @@ public final class SwiftToSkeleton { ) } + private func diagnoseProtocolConformances( + in exported: ExportedSkeleton + ) -> [(inputFilePath: String, errors: [DiagnosticError])] { + var loweredProtocols: Set = [] + func collect(_ type: BridgeType, loweredBySwift: Bool) { + switch type { + case .swiftProtocol(let name): + if loweredBySwift { loweredProtocols.insert(name) } + case .array(let element), .dictionary(let element), .nullable(let element, _), .alias(_, let element): + collect(element, loweredBySwift: loweredBySwift) + case .closure(let signature, _): + for parameter in signature.parameters { + collect(parameter, loweredBySwift: !loweredBySwift) + } + collect(signature.returnType, loweredBySwift: loweredBySwift) + default: + break + } + } + func collect(_ function: ExportedFunction, loweredReturn: Bool = true) { + for parameter in function.parameters { collect(parameter.type, loweredBySwift: !loweredReturn) } + collect(function.returnType, loweredBySwift: loweredReturn) + } + + for function in exported.functions + exported.classes.flatMap(\.methods) + + exported.structs.flatMap(\.methods) + exported.enums.flatMap(\.staticMethods) + { + collect(function) + } + for constructor in exported.classes.compactMap(\.constructor) + exported.structs.compactMap(\.constructor) { + for parameter in constructor.parameters { collect(parameter.type, loweredBySwift: false) } + } + for property in exported.classes.flatMap(\.properties) + exported.enums.flatMap(\.staticProperties) { + collect(property.type, loweredBySwift: true) + if !property.isReadonly { collect(property.type, loweredBySwift: false) } + } + for property in exported.structs.flatMap(\.properties) { + collect(property.type, loweredBySwift: true) + if !property.isStatic || !property.isReadonly { collect(property.type, loweredBySwift: false) } + } + for value in exported.enums.flatMap(\.cases).flatMap(\.associatedValues) { + collect(value.type, loweredBySwift: true) + } + for protocolDef in exported.protocols { + for method in protocolDef.methods { collect(method, loweredReturn: false) } + for property in protocolDef.properties { + collect(property.type, loweredBySwift: false) + if !property.isReadonly { collect(property.type, loweredBySwift: true) } + } + } + + guard !loweredProtocols.isEmpty else { return [] } + var diagnostics: [(inputFilePath: String, errors: [DiagnosticError])] = [] + for declaration in typeDeclResolver.declarationsWithInheritance where !declaration.is(ProtocolDeclSyntax.self) { + let extendedType = declaration.as(ExtensionDeclSyntax.self)?.extendedType + let target = extendedType.flatMap { typeDeclResolver.resolveExtensionTarget($0) } + let classDecl = declaration.as(ClassDeclSyntax.self) ?? target?.as(ClassDeclSyntax.self) + if classDecl?.attributes.hasJSAttribute() == true { continue } + if let extendedType, target == nil { + var errors: [DiagnosticError] = [] + if case .swiftHeapObject = resolveExternal(for: extendedType, errors: &errors) { continue } + } + guard + let name = declaration.asProtocol(NamedDeclSyntax.self)?.name.text ?? extendedType?.trimmedDescription, + let inputFilePath = sourceFiles.first(where: { $0.sourceFile.id == declaration.root.id })?.inputFilePath + else { continue } + for inherited in declaration.inheritanceClause?.inheritedTypes ?? [] { + guard let protocolDecl = typeDeclResolver.resolve(inherited.type)?.as(ProtocolDeclSyntax.self), + protocolDecl.attributes.hasJSAttribute(), loweredProtocols.contains(protocolDecl.name.text) + else { continue } + let protocolName = protocolDecl.name.text + diagnostics.append( + ( + inputFilePath, + [ + DiagnosticError( + node: declaration, + message: + "'\(name)' conforms to '\(protocolName)', a @JS protocol that exported APIs " + + "bridge to JavaScript, but '\(name)' is not a '@JS class'. Passing it to " + + "JavaScript as 'any \(protocolName)' would trap at runtime.", + hint: + "Mark '\(name)' as a '@JS class' so it can cross the bridge, or avoid using " + + "'\(protocolName)' as an existential in exported APIs." + ) + ] + ) + ) + } + } + return diagnostics + } + private static let jsTypedArrayTypealiasNames: [String: String] = [ "Int8": "JSInt8Array", "UInt8": "JSUint8Array", diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift index 4df546b8a..f88f67084 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift @@ -9,6 +9,7 @@ class TypeDeclResolver { typealias QualifiedName = [String] private var typeDeclByQualifiedName: [QualifiedName: TypeDecl] = [:] private var typeAliasByQualifiedName: [QualifiedName: TypeAliasDeclSyntax] = [:] + private(set) var declarationsWithInheritance: [any DeclGroupSyntax] = [] enum Error: Swift.Error { case typeNotFound(QualifiedName) @@ -24,6 +25,9 @@ class TypeDeclResolver { } func visitNominalDecl(_ node: TypeDecl) -> SyntaxVisitorContinueKind { + if node.inheritanceClause != nil { + resolver.declarationsWithInheritance.append(node) + } let name = node.name.text let qualifiedName = scope + [name] resolver.typeDeclByQualifiedName[qualifiedName] = node @@ -74,6 +78,9 @@ class TypeDeclResolver { } override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { + if node.inheritanceClause != nil { + resolver.declarationsWithInheritance.append(node) + } guard let components = node.memberScopeComponents else { return .skipChildren } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift index 3f0ee88db..afd87b9df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift @@ -487,6 +487,27 @@ import Testing } } + @Test func exportedClassConformanceInAnotherModule() throws { + let core = try makeSkeleton( + """ + @JS public class MyImpl { + @JS public init() {} + @JS public func ok() -> Int { 42 } + } + """, + moduleName: "Core" + ) + _ = try makeSkeleton( + """ + import Core + @JS protocol P { func ok() -> Int } + extension MyImpl: P {} + @JS func get() -> P { MyImpl() } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + } + // MARK: - Utillites private func resolveApp( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 4f45a9880..ea8ae9402 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -791,4 +791,96 @@ import Testing // No line 3 in source, so output must not show a " 3 |" context line after the pointer #expect(!description.contains(" 3 |")) } + + @Test(arguments: [ + "struct MyImpl: P { func ok() -> Int { 42 } }", + "class MyImpl: P { func ok() -> Int { 42 } }", + "struct MyImpl {}\nextension MyImpl: P { func ok() -> Int { 42 } }", + ]) + func unsupportedProtocolConformer(conformer: String) { + expectDiagnostic( + source: """ + @JS protocol P { func ok() -> Int } + \(conformer) + @JS func get() -> P { MyImpl() } + """, + contains: "'MyImpl' is not a '@JS class'" + ) + } + + @Test(arguments: [ + "@JS func get() -> [P] { fatalError() }", + "@JS func get() -> P? { fatalError() }", + "@JS func get() -> [String: P] { fatalError() }", + "@JS func subscribe(_ callback: (P) -> Void) {}", + "@JS class Holder { @JS var value: P = MyImpl() }", + "@JS protocol Sink { func consume(_ value: P) }", + "@JS class Holder { @JS var callback: (P) -> Void = { _ in } }", + "@JS struct Holder { let callback: (P) -> Void }", + "@JS enum Holder { @JS static var callback: (P) -> Void = { _ in } }", + "@JS protocol Holder { var callback: (P) -> Void { get set } }", + "@JS protocol Holder { var callback: (P) -> Void { get } }", + ]) + func loweredProtocolConformer(declaration: String) { + expectDiagnostic( + source: """ + @JS protocol P { func ok() -> Int } + struct MyImpl: P { func ok() -> Int { 42 } } + \(declaration) + """, + contains: "'MyImpl' conforms to 'P'" + ) + } + + @Test(arguments: [ + "@JS func take(_ value: P) -> Int { value.ok() }", + "@JS class Holder { @JS let callback: (P) -> Void = { _ in } }", + ]) + func protocolConformerWithoutLowering(declaration: String) throws { + _ = try makeSkeleton( + """ + @JS protocol P { func ok() -> Int } + struct MyImpl: P { func ok() -> Int { 42 } } + \(declaration) + """ + ) + } + + @Test func exportedProtocolConformer() throws { + _ = try makeSkeleton( + """ + @JS protocol P { func ok() -> Int } + @JS class MyImpl: P { + @JS init() {} + @JS func ok() -> Int { 42 } + } + @JS func get() -> P { MyImpl() } + """ + ) + } + + @Test func unusedJSProtocolConformer() throws { + _ = try makeSkeleton( + """ + @JS protocol P { var id: String { get } } + @JS struct Building: P { var id: String } + @JS func describe(_ building: Building) -> String { building.id } + """ + ) + } + + @Test func protocolRefinementIsNotAConcreteConformance() throws { + _ = try makeSkeleton( + """ + @JS protocol Base { func ok() -> Int } + @JS protocol Refined: Base { func extra() -> Int } + @JS class MyImpl: Refined { + @JS init() {} + @JS func ok() -> Int { 1 } + @JS func extra() -> Int { 2 } + } + @JS func get() -> Base { MyImpl() } + """ + ) + } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index 4483de428..b88c6717e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -133,7 +133,7 @@ public func _bjs_roundtripTags() -> Void { @_cdecl("bjs_describeUser") public func _bjs_describeUser(_ owner: Int32) -> Int32 { #if arch(wasm32) - let ret = describeUser(_: AnyHasOptionalUserId.bridgeJSLiftParameter(owner)) as! _BridgedSwiftProtocolExportable + let ret = _bridgeJSUnwrapProtocolExportable(describeUser(_: AnyHasOptionalUserId.bridgeJSLiftParameter(owner)), "HasOptionalUserId") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 7c2db9a98..6afb7e6b8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -698,7 +698,7 @@ public func _bjs_processDelegates() -> Void { #if arch(wasm32) let ret = processDelegates(_: [AnyMyViewControllerDelegate].bridgeJSStackPop()) for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else @@ -713,7 +713,7 @@ public func _bjs_processDelegatesByName() -> Void { let ret = processDelegatesByName(_: [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter()) 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(_bridgeJSUnwrapProtocolExportable(__bjs_kv_ret.value, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else @@ -871,7 +871,7 @@ public func _bjs_MyViewController_sendHelper(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_MyViewController_delegate_get") public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).delegate as! _BridgedSwiftProtocolExportable + let ret = _bridgeJSUnwrapProtocolExportable(MyViewController.bridgeJSLiftParameter(_self).delegate, "MyViewControllerDelegate") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -894,7 +894,7 @@ public func _bjs_MyViewController_secondDelegate_get(_ _self: UnsafeMutableRawPo #if arch(wasm32) let ret = MyViewController.bridgeJSLiftParameter(_self).secondDelegate if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } else { _swift_js_return_optional_object(0, 0) } @@ -971,7 +971,7 @@ public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) #if arch(wasm32) let ret = DelegateManager.bridgeJSLiftParameter(_self).delegates for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else @@ -996,7 +996,7 @@ public func _bjs_DelegateManager_delegatesByName_get(_ _self: UnsafeMutableRawPo let ret = DelegateManager.bridgeJSLiftParameter(_self).delegatesByName 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(_bridgeJSUnwrapProtocolExportable(__bjs_kv_ret.value, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift index d956a6f3a..78765e3f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift @@ -27,7 +27,7 @@ private enum _BJS_Closure_10TestModule10RenderableP_10RenderableP { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let param0ObjectId = _bridgeJSUnwrapProtocolExportable(param0, "Renderable").bridgeJSLowerAsProtocolReturn() let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP(callbackValue, param0ObjectId) return AnyRenderable.bridgeJSLiftReturn(ret) @@ -55,7 +55,7 @@ public func _invoke_swift_closure_TestModule_10TestModule10RenderableP_10Rendera #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any Renderable) -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure(AnyRenderable.bridgeJSLiftParameter(param0)) - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + return _bridgeJSUnwrapProtocolExportable(result, "Renderable").bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -90,7 +90,7 @@ private enum _BJS_Closure_10TestModule10RenderableP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let param0ObjectId = _bridgeJSUnwrapProtocolExportable(param0, "Renderable").bridgeJSLowerAsProtocolReturn() let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_SS(callbackValue, param0ObjectId) return String.bridgeJSLiftReturn(ret) @@ -155,7 +155,7 @@ private enum _BJS_Closure_10TestModuleSq10RenderableP_SS { #if arch(wasm32) let (param0IsSome, param0ObjectId): (Int32, Int32) if let param0 { - (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + (param0IsSome, param0ObjectId) = (1, _bridgeJSUnwrapProtocolExportable(param0, "Renderable").bridgeJSLowerAsProtocolReturn()) } else { (param0IsSome, param0ObjectId) = (0, 0) } @@ -248,7 +248,7 @@ public func _invoke_swift_closure_TestModule_10TestModuley_10RenderableP(_ boxPt #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure() - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + return _bridgeJSUnwrapProtocolExportable(result, "Renderable").bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index ab0a9f4f0..f62c6aff0 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1145,6 +1145,23 @@ extension _BridgedSwiftProtocolExportable where Self: _BridgedSwiftProtocolWrapp } } +#if !hasFeature(Embedded) +/// Checks that a protocol value can be lowered to JavaScript. +@_spi(BridgeJS) public func _bridgeJSUnwrapProtocolExportable( + _ value: Any, + _ protocolName: StaticString +) -> any _BridgedSwiftProtocolExportable { + guard let exportable = value as? any _BridgedSwiftProtocolExportable else { + fatalError( + "BridgeJS: cannot bridge a value of type '\(type(of: value))' to JavaScript as " + + "'any \(protocolName)': the concrete type is not exported with @JS. Only '@JS class' " + + "types and JavaScript-provided implementations can cross the bridge as protocol values." + ) + } + return exportable +} +#endif + /// A protocol that Swift enum types that do not have a payload can conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index f16bce9f2..748a95129 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -100,7 +100,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessor let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let param0ObjectId = _bridgeJSUnwrapProtocolExportable(param0, "DataProcessor").bridgeJSLowerAsProtocolReturn() let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(callbackValue, param0ObjectId) return AnyDataProcessor.bridgeJSLiftReturn(ret) @@ -128,7 +128,7 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13D #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any DataProcessor) -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure(AnyDataProcessor.bridgeJSLiftParameter(param0)) - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + return _bridgeJSUnwrapProtocolExportable(result, "DataProcessor").bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -163,7 +163,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let param0ObjectId = _bridgeJSUnwrapProtocolExportable(param0, "DataProcessor").bridgeJSLowerAsProtocolReturn() let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(callbackValue, param0ObjectId) return String.bridgeJSLiftReturn(ret) @@ -1670,7 +1670,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_SS { #if arch(wasm32) let (param0IsSome, param0ObjectId): (Int32, Int32) if let param0 { - (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + (param0IsSome, param0ObjectId) = (1, _bridgeJSUnwrapProtocolExportable(param0, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } else { (param0IsSome, param0ObjectId) = (0, 0) } @@ -3480,7 +3480,7 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1 #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure() - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + return _bridgeJSUnwrapProtocolExportable(result, "DataProcessor").bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -4581,7 +4581,7 @@ public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { #if arch(wasm32) let ret = ArraySupportExports.roundTripProtocolArray(_: [AnyArrayElementProtocol].bridgeJSStackPop()) for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "ArrayElementProtocol").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else @@ -12699,7 +12699,7 @@ public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_processor_get") public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).processor as! _BridgedSwiftProtocolExportable + let ret = _bridgeJSUnwrapProtocolExportable(DataProcessorManager.bridgeJSLiftParameter(_self).processor, "DataProcessor") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -12722,7 +12722,7 @@ public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutable #if arch(wasm32) let ret = DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } else { _swift_js_return_optional_object(0, 0) } @@ -13136,7 +13136,7 @@ fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRaw @_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessor") public func _bjs_ProtocolReturnTests_static_createNativeProcessor() -> Int32 { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessor() as! _BridgedSwiftProtocolExportable + let ret = _bridgeJSUnwrapProtocolExportable(ProtocolReturnTests.createNativeProcessor(), "DataProcessor") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -13149,7 +13149,7 @@ public func _bjs_ProtocolReturnTests_static_createNativeProcessorOptional() -> V #if arch(wasm32) let ret = ProtocolReturnTests.createNativeProcessorOptional() if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } else { _swift_js_return_optional_object(0, 0) } @@ -13164,7 +13164,7 @@ public func _bjs_ProtocolReturnTests_static_createNativeProcessorNil() -> Void { #if arch(wasm32) let ret = ProtocolReturnTests.createNativeProcessorNil() if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } else { _swift_js_return_optional_object(0, 0) } @@ -13179,7 +13179,7 @@ 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(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else @@ -13194,7 +13194,7 @@ public func _bjs_ProtocolReturnTests_static_createNativeProcessorDictionary() -> 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(_bridgeJSUnwrapProtocolExportable(__bjs_kv_ret.value, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } _swift_js_push_i32(Int32(ret.count)) #else From 78cebea21360448197d7d524a45b6e8b62d3ba40 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 11 Sep 2026 11:24:29 +0200 Subject: [PATCH 119/140] BridgeJS: Unify thunk argument preparation --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 162 ++---------------- .../Sources/BridgeJSCore/ExportSwift.swift | 91 +++------- .../Sources/BridgeJSCore/ImportTS.swift | 4 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 7 + .../Sources/BridgeJSLink/JSGlueGen.swift | 27 +-- .../JavaScriptKit/BridgeJSIntrinsics.swift | 8 +- 6 files changed, 62 insertions(+), 237 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 25de94da1..7459d6058 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -112,11 +112,14 @@ public struct ClosureCodegen { let helperEnumDecl: DeclSyntax = "\(raw: helperEnumDeclPrinter.lines.joined(separator: "\n"))" - let initAccessModifier = accessLevel.modifierKeyword.map { "\($0) " } ?? "" + let accessModifier = accessLevel.modifierKeyword.map { "\($0) " } ?? "" + let declaration = signature.sendingParameters ? "static func sending" : "init" + let returnClause = signature.sendingParameters ? " -> Self" : "" + let initializer = signature.sendingParameters ? "Self" : "self.init" let typedClosureExtension: DeclSyntax = """ extension JSTypedClosure where Signature == \(raw: swiftClosureType) { - \(raw: initAccessModifier)init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType)) { - self.init( + \(raw: accessModifier)\(raw: declaration)(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType))\(raw: returnClause) { + \(raw: initializer)( makeClosure: \(raw: externABIName), body: body, fileID: fileID, @@ -135,149 +138,22 @@ public struct ClosureCodegen { let swiftClosureType = swiftClosureType(for: signature) let boxType = "_BridgeJSTypedClosureBox<\(swiftClosureType)>" let abiName = "invoke_swift_closure_\(signature.moduleName)_\(signature.mangleName)" - - // Build ABI parameters directly with WasmCoreType (no string conversion needed) - var abiParams: [(name: String, type: WasmCoreType)] = [("boxPtr", .pointer)] - var liftedParams: [String] = [] - - for (index, paramType) in signature.parameters.enumerated() { - let paramName = "param\(index)" - let liftInfo = try paramType.liftParameterInfo() - - for (argName, wasmType) in liftInfo.parameters { - let fullName = - liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName - abiParams.append((fullName, wasmType)) - } - - let argNames = liftInfo.parameters.map { (argName, _) in - liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName - } - liftedParams.append( - "\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))" - ) - } - - let 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 builder = try ExportSwift.ExportedThunkBuilder( + effects: Effects(isAsync: signature.isAsync, isThrows: signature.isThrows), + returnType: signature.returnType ) - - let abiReturnWasmType = - signature.isAsync - ? try BridgeType.jsObject(nil).loweringReturnInfo().returnType - : try signature.returnType.loweringReturnInfo().returnType - - // Build signature using SwiftSignatureBuilder - let funcSignature = SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: abiParams, - returnType: abiReturnWasmType + builder.abiParameterSignatures.append(("boxPtr", .pointer)) + builder.parameterBindings.append( + "let closure = Unmanaged<\(raw: boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure" ) - - let emitCallAndLower: (CodeFragmentPrinter) -> Void = { printer in - if signature.returnType == .void { - printer.write(closureCallExpr.description) - } else { - printer.write("let result = \(closureCallExpr)") - switch signature.returnType { - case .swiftProtocol(let protocolName): - printer.write( - "return _bridgeJSUnwrapProtocolExportable(result, \"\(protocolName)\").bridgeJSLowerAsProtocolReturn()" - ) - case .nullable(.swiftProtocol(let protocolName), _): - printer.write("if let result {") - printer.indent { - printer.write( - "_swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(result, \"\(protocolName)\").bridgeJSLowerAsProtocolReturn())" - ) - } - printer.write("} else {") - printer.indent { - printer.write("_swift_js_return_optional_object(0, 0)") - } - printer.write("}") - default: - printer.write("return result.bridgeJSLowerReturn()") - } - } - } - - 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) - } + for (index, paramType) in signature.parameters.enumerated() { + try builder.liftParameter( + param: Parameter(label: nil, name: "param\(index)", type: paramType) + ) } - - return DeclSyntax(funcDecl) + builder.call(name: "closure", returnType: signature.returnType) + try builder.lowerReturnValue(returnType: signature.returnType) + return builder.render(abiName: abiName) } public func renderSupport(for skeleton: BridgeJSSkeleton) throws -> String? { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index d976c9a39..55e3b063c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -179,7 +179,6 @@ public class ExportSwift { class ExportedThunkBuilder { var body: [CodeBlockItemSyntax] = [] - var liftedParameterExprs: [ExprSyntax] = [] var parameters: [Parameter] = [] var abiParameterSignatures: [(name: String, type: WasmCoreType)] = [] var abiReturnType: WasmCoreType? @@ -190,8 +189,7 @@ public class ExportSwift { /// helper. Set for every `async` thunk. var asyncResolveReturnType: BridgeType? - /// Stack-using parameter lifts hoisted ahead of the deferred async closure. - var asyncHoistedBindings: [CodeBlockItemSyntax] = [] + var parameterBindings: [CodeBlockItemSyntax] = [] init(effects: Effects, returnType: BridgeType) throws { self.effects = effects @@ -254,7 +252,7 @@ public class ExportSwift { ) } - liftedParameterExprs.append(liftingExpr) + parameterBindings.insert("let \(raw: param.name) = \(liftingExpr)", at: 0) for (name, type) in zip(argumentsToLift, liftingInfo.parameters.map { $0.type }) { abiParameterSignatures.append((name, type)) } @@ -269,15 +267,16 @@ public class ExportSwift { } } - private func removeFirstLiftedParameter() -> (parameter: Parameter, expr: ExprSyntax) { - let parameter = parameters.removeFirst() - let expr = liftedParameterExprs.removeFirst() - return (parameter, expr) + private func removeFirstLiftedParameter() -> String { + return parameters.removeFirst().name } private func renderCallStatement(callee: ExprSyntax, returnType: BridgeType) -> CodeBlockItemSyntax { - let labeledParams = zip(parameters, liftedParameterExprs).map { param, expr in - LabeledExprSyntax(label: param.label, expression: expr) + let labeledParams = parameters.map { param in + LabeledExprSyntax( + label: param.label, + expression: DeclReferenceExprSyntax(baseName: .identifier(param.name)) + ) } var callExpr: ExprSyntax = "\(raw: callee)(\(raw: labeledParams.map { $0.description }.joined(separator: ", ")))" @@ -310,7 +309,6 @@ public class ExportSwift { } func call(name: String, returnType: BridgeType) { - generateParameterLifting() let item = renderCallStatement(callee: "\(raw: name)", returnType: returnType) append(item) } @@ -325,8 +323,7 @@ public class ExportSwift { } func callMethod(methodName: String, returnType: BridgeType) { - let (_, selfExpr) = removeFirstLiftedParameter() - generateParameterLifting() + let selfExpr = removeFirstLiftedParameter() let item = renderCallStatement( callee: "\(raw: selfExpr).\(raw: methodName)", returnType: returnType @@ -334,42 +331,8 @@ public class ExportSwift { append(item) } - /// Generates intermediate variables for stack-using parameters if needed for LIFO compatibility - private func generateParameterLifting() { - let stackParamIndices = parameters.enumerated().compactMap { index, param -> Int? in - 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() { - let param = parameters[index] - let expr = liftedParameterExprs[index] - let varName = "_tmp_\(param.name)" - - append("let \(raw: varName) = \(expr)") - liftedParameterExprs[index] = ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier(varName))) - } - } - func callPropertyGetter(propertyName: String, returnType: BridgeType) { - let (_, selfExpr) = removeFirstLiftedParameter() + let selfExpr = removeFirstLiftedParameter() if returnType == .void { append("\(raw: selfExpr).\(raw: propertyName)") } else { @@ -379,13 +342,13 @@ public class ExportSwift { } func callPropertySetter(propertyName: String) { - let (_, selfExpr) = removeFirstLiftedParameter() - let (_, newValueExpr) = removeFirstLiftedParameter() + let selfExpr = removeFirstLiftedParameter() + let newValueExpr = removeFirstLiftedParameter() append("\(raw: selfExpr).\(raw: propertyName) = \(raw: newValueExpr)") } func callStaticPropertySetter(klassName: String, propertyName: String) { - let (_, newValueExpr) = removeFirstLiftedParameter() + let newValueExpr = removeFirstLiftedParameter() append("\(raw: klassName).\(raw: propertyName) = \(raw: newValueExpr)") } @@ -456,10 +419,11 @@ public class ExportSwift { /// 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 + effects.isThrows && parameterBindings.isEmpty } func render(abiName: String) -> DeclSyntax { + var bindings = parameterBindings let body: CodeBlockItemListSyntax if effects.isAsync, let resolveType = asyncResolveReturnType { let resolveName = "Promise_resolve_\(resolveType.mangleTypeName)" @@ -468,17 +432,15 @@ public class ExportSwift { returnSpelling: resolveType.swiftType, forcesCapture: forcesCapture ) - var hoistedBindings = asyncHoistedBindings var bodyItems = self.body if forcesCapture { - hoistedBindings.append("let __bjs_capture = 0") + bindings.append("let __bjs_capture = 0") if !bodyItems.isEmpty { bodyItems[0] = bodyItems[0].with(\.leadingTrivia, .newline) } bodyItems.insert("_ = __bjs_capture", at: 0) } body = """ - \(CodeBlockItemListSyntax(hoistedBindings)) return _bjs_makePromise(resolve: \(raw: resolveName), reject: Promise_reject) {\(raw: closureHead) \(CodeBlockItemListSyntax(bodyItems)) } @@ -504,6 +466,10 @@ public class ExportSwift { } else { body = CodeBlockItemListSyntax(self.body) } + let preparedBody: CodeBlockItemListSyntax = """ + \(CodeBlockItemListSyntax(bindings.map { $0.with(\.leadingTrivia, .newline) })) + \(body) + """ // Build function signature using SwiftSignatureBuilder let signature = SwiftSignatureBuilder.buildABIFunctionSignature( abiParameters: abiParameterSignatures, @@ -515,7 +481,7 @@ public class ExportSwift { abiName: abiName, signature: signature ) { printer in - printer.write(multilineString: body.description) + printer.write(multilineString: preparedBody.description) } return DeclSyntax(funcDecl) @@ -1744,19 +1710,6 @@ extension BridgeType { return false } - var isStackUsingParameter: Bool { - switch self { - case .swiftStruct, .array, .dictionary, .associatedValueEnum: - return true - case .nullable(let wrapped, _): - return wrapped.isStackUsingParameter - case .alias(_, let underlying): - return underlying.isStackUsingParameter - default: - return false - } - } - struct LiftingIntrinsicInfo: Sendable { let parameters: [(name: String, type: WasmCoreType)] diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 09bee37d6..0ec5457fa 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -339,7 +339,7 @@ public struct ImportTS { body = CodeFragmentPrinter() let tryKeyword = effects.isThrows ? "try" : "try!" - let rejectFactory = "makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }" + let rejectFactory = "makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }" if returnType == .void { let resolveFactory = "makeResolveClosure: { JSTypedClosure<() -> Void>($0) }" body.write( @@ -348,7 +348,7 @@ public struct ImportTS { } else { let resolveSwiftType = returnType.closureSwiftType let resolveFactory = - "makeResolveClosure: { JSTypedClosure<(sending \(resolveSwiftType)) -> Void>($0) }" + "makeResolveClosure: { JSTypedClosure<(sending \(resolveSwiftType)) -> Void>.sending($0) }" body.write( "let resolved = \(tryKeyword) await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" ) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 163b7db6b..cf6eab60c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1574,6 +1574,13 @@ public struct BridgeJSLink { ) } + init(effects: Effects, context: IntrinsicJSFragment.PrintCodeContext) { + self.effects = effects + self.scope = context.scope.makeChildScope() + self.body = CodeFragmentPrinter() + self.context = context.with(\.scope, scope).with(\.printer, body) + } + func lowerParameter(param: Parameter) throws { let loweringFragment = try IntrinsicJSFragment.lowerParameter(type: param.type) assert( diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 3f8530c55..cb79b5625 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2570,29 +2570,18 @@ struct IntrinsicJSFragment: Sendable { "\(instanceVar).\(method.resolvedJSName) = function(\(paramList)) {" ) try printer.indent { - printer.write( + let builder = BridgeJSLink.ExportedThunkBuilder( + effects: method.effects, + context: context + ) + builder.body.write( "\(JSGlueVariableScope.reservedStructHelpers).\(context.scope.helperKey(forTypeNamed: structDef.swiftCallName)).lower(this);" ) - - var paramForwardings: [String] = [] for param in method.parameters { - let fragment = try IntrinsicJSFragment.lowerParameter(type: param.type) - let loweredValues = try fragment.printCode([param.name], context) - paramForwardings.append(contentsOf: loweredValues) - } - - let callExpr = "instance.exports.\(method.abiName)(\(paramForwardings.joined(separator: ", ")))" - if method.returnType == .void { - printer.write("\(callExpr);") - } else { - let liftFragment = try IntrinsicJSFragment.liftReturn(type: method.returnType) - 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);") - } + try builder.lowerParameter(param: param) } + let returnExpr = try builder.call(abiName: method.abiName, returnType: method.returnType) + builder.renderFunctionBody(into: printer, returnExpr: returnExpr) } printer.write("}.bind(\(instanceVar));") } diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index f62c6aff0..6946d6a59 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -2591,13 +2591,13 @@ where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Val /// /// The closure factories are dependency-injected because this library cannot /// reference per-module generated `make_swift_closure_*` externs. The generated -/// code passes `{ JSTypedClosure<(T) -> Void>($0) }` which uses the per-module -/// convenience init. +/// code passes `{ JSTypedClosure<(sending T) -> Void>.sending($0) }` using the +/// per-module callback factory. /// /// - Parameters: -/// - makeResolveClosure: A factory that wraps a `(T) -> Void` Swift closure +/// - makeResolveClosure: A factory that wraps a `(sending T) -> Void` Swift closure /// into a typed `JSTypedClosure`, creating the corresponding JS function. -/// - makeRejectClosure: A factory that wraps a `(JSValue) -> Void` Swift closure +/// - makeRejectClosure: A factory that wraps a `(sending JSValue) -> Void` Swift closure /// into a `JSTypedClosure`, for the rejection path. /// - body: A closure that receives the resolve and reject JS object refs /// (as `Int32`) and should pass them to the appropriate JS extern function. From 4ac72886e341e7b4852b5b7c83980f204c7fb380 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 11 Sep 2026 11:24:29 +0200 Subject: [PATCH 120/140] Tests: Cover thunk argument lifting and refresh generated bindings --- Benchmarks/Sources/Generated/BridgeJS.swift | 413 ++- .../PlayBridgeJS/Generated/BridgeJS.swift | 5 +- .../Inputs/MacroSwift/SwiftStruct.swift | 4 + .../BridgeJSCodegenTests/Alias.swift | 34 +- .../BridgeJSCodegenTests/AliasInClosure.swift | 12 +- .../BridgeJSCodegenTests/ArrayTypes.swift | 103 +- .../BridgeJSCodegenTests/Async.swift | 64 +- .../AsyncAssociatedValueEnum.swift | 8 +- .../BridgeJSCodegenTests/AsyncImport.swift | 64 +- .../AsyncStaticImport.swift | 20 +- .../ClassWithNestedTypes.swift | 19 +- .../CrossFileExtension.swift | 9 +- .../CrossFileExtensionOrderIndependence.swift | 6 +- .../CrossFileFunctionTypes.ReverseOrder.swift | 21 +- .../CrossFileFunctionTypes.swift | 21 +- .../CrossFileNestedTypeExtension.swift | 6 +- ...CrossFileTypeResolution.ReverseOrder.swift | 7 +- .../CrossFileTypeResolution.swift | 7 +- .../DefaultParameters.swift | 130 +- .../DictionaryTypes.swift | 18 +- .../BridgeJSCodegenTests/DocComments.swift | 30 +- .../BridgeJSCodegenTests/EnumAlias.swift | 6 +- .../EnumAssociatedValue.swift | 51 +- .../BridgeJSCodegenTests/EnumCase.swift | 15 +- .../EnumNamespace.Global.swift | 32 +- .../BridgeJSCodegenTests/EnumNamespace.swift | 32 +- .../BridgeJSCodegenTests/EnumRawType.swift | 81 +- .../ExtensionNestedTypes.swift | 33 +- .../ExtensionOrderIndependence.swift | 6 +- .../ExtensionScopeParity.swift | 3 +- .../FixedWidthIntegers.swift | 24 +- .../BridgeJSCodegenTests/GenericImports.swift | 13 +- .../IdentityModeClass.swift | 30 +- .../ImportedTypeInExportedInterface.swift | 9 +- .../BridgeJSCodegenTests/JSNameOverride.swift | 46 +- .../JSTypedArrayTypes.swift | 12 +- .../BridgeJSCodegenTests/JSValue.swift | 43 +- .../BridgeJSCodegenTests/MixedGlobal.swift | 3 +- .../BridgeJSCodegenTests/MixedPrivate.swift | 3 +- .../NamespacedClassSignature.swift | 9 +- .../Namespaces.Global.swift | 20 +- .../BridgeJSCodegenTests/Namespaces.swift | 20 +- .../BridgeJSCodegenTests/NestedType.swift | 6 +- .../NestedTypeNameCollision.swift | 12 +- .../BridgeJSCodegenTests/Optionals.swift | 110 +- .../PrimitiveParameters.swift | 7 +- .../BridgeJSCodegenTests/PropertyTypes.swift | 110 +- .../BridgeJSCodegenTests/Protocol.swift | 79 +- .../ProtocolInClosure.swift | 42 +- .../RelativeQualifiedTypes.swift | 10 +- .../StaticFunctions.Global.swift | 29 +- .../StaticFunctions.swift | 29 +- .../StaticProperties.Global.swift | 30 +- .../StaticProperties.swift | 30 +- .../StringParameter.swift | 6 +- .../StructWithNestedTypes.swift | 10 +- .../BridgeJSCodegenTests/SwiftClass.swift | 26 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 257 +- .../SwiftClosureImports.swift | 37 +- .../BridgeJSCodegenTests/SwiftStruct.json | 29 + .../BridgeJSCodegenTests/SwiftStruct.swift | 58 +- .../SwiftTypedClosureAccess.swift | 9 +- .../BridgeJSCodegenTests/UnsafePointer.swift | 25 +- .../BridgeJSLinkTests/DefaultParameters.js | 4 +- .../BridgeJSLinkTests/ExtensionNestedTypes.js | 6 +- .../ExtensionOrderIndependence.js | 6 +- .../BridgeJSLinkTests/SwiftStruct.d.ts | 1 + .../BridgeJSLinkTests/SwiftStruct.js | 15 +- .../Generated/BridgeJS.swift | 28 +- .../Generated/BridgeJS.swift | 39 +- .../ClosureAsyncAPIs.swift | 8 + .../ClosureSupportTests.swift | 110 +- .../Generated/BridgeJS.swift | 2881 ++++++++++++----- .../Generated/JavaScript/BridgeJS.json | 607 ++++ .../JavaScript/ClosureAsyncTests.mjs | 9 + .../JavaScript/ClosureSupportTests.mjs | 3 + Tests/BridgeJSRuntimeTests/StructAPIs.swift | 15 + Tests/prelude.mjs | 4 + 78 files changed, 4591 insertions(+), 1588 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 5e3e11db8..86f2516e6 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -399,7 +399,9 @@ public func _bjs_EnumRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_EnumRoundtrip_take") public func _bjs_EnumRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - EnumRoundtrip.bridgeJSLiftParameter(_self).take(_: APIResult.bridgeJSLiftParameter(value)) + let value = APIResult.bridgeJSLiftParameter(value) + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + _self.take(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -409,7 +411,8 @@ public func _bjs_EnumRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ value: I @_cdecl("bjs_EnumRoundtrip_makeSuccess") public func _bjs_EnumRoundtrip_makeSuccess(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makeSuccess() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeSuccess() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -420,7 +423,8 @@ public func _bjs_EnumRoundtrip_makeSuccess(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_EnumRoundtrip_makeFailure") public func _bjs_EnumRoundtrip_makeFailure(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makeFailure() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeFailure() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -431,7 +435,8 @@ public func _bjs_EnumRoundtrip_makeFailure(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_EnumRoundtrip_makeFlag") public func _bjs_EnumRoundtrip_makeFlag(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makeFlag() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeFlag() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -442,7 +447,8 @@ public func _bjs_EnumRoundtrip_makeFlag(_ _self: UnsafeMutableRawPointer) -> Voi @_cdecl("bjs_EnumRoundtrip_makeRate") public func _bjs_EnumRoundtrip_makeRate(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makeRate() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeRate() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -453,7 +459,8 @@ public func _bjs_EnumRoundtrip_makeRate(_ _self: UnsafeMutableRawPointer) -> Voi @_cdecl("bjs_EnumRoundtrip_makePrecise") public func _bjs_EnumRoundtrip_makePrecise(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makePrecise() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makePrecise() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -464,7 +471,8 @@ public func _bjs_EnumRoundtrip_makePrecise(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_EnumRoundtrip_makeInfo") public func _bjs_EnumRoundtrip_makeInfo(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).makeInfo() + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeInfo() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -475,7 +483,9 @@ public func _bjs_EnumRoundtrip_makeInfo(_ _self: UnsafeMutableRawPointer) -> Voi @_cdecl("bjs_EnumRoundtrip_roundtrip") public func _bjs_EnumRoundtrip_roundtrip(_ _self: UnsafeMutableRawPointer, _ result: Int32) -> Void { #if arch(wasm32) - let ret = EnumRoundtrip.bridgeJSLiftParameter(_self).roundtrip(_: APIResult.bridgeJSLiftParameter(result)) + let result = APIResult.bridgeJSLiftParameter(result) + let _self = EnumRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtrip(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -528,7 +538,9 @@ public func _bjs_ComplexResultRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ComplexResultRoundtrip_take") public func _bjs_ComplexResultRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ComplexResultRoundtrip.bridgeJSLiftParameter(_self).take(_: ComplexResult.bridgeJSLiftParameter(value)) + let value = ComplexResult.bridgeJSLiftParameter(value) + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + _self.take(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -538,7 +550,8 @@ public func _bjs_ComplexResultRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_ComplexResultRoundtrip_makeSuccess") public func _bjs_ComplexResultRoundtrip_makeSuccess(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeSuccess() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeSuccess() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -549,7 +562,8 @@ public func _bjs_ComplexResultRoundtrip_makeSuccess(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ComplexResultRoundtrip_makeError") public func _bjs_ComplexResultRoundtrip_makeError(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeError() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeError() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -560,7 +574,8 @@ public func _bjs_ComplexResultRoundtrip_makeError(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_ComplexResultRoundtrip_makeLocation") public func _bjs_ComplexResultRoundtrip_makeLocation(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeLocation() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeLocation() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -571,7 +586,8 @@ public func _bjs_ComplexResultRoundtrip_makeLocation(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ComplexResultRoundtrip_makeStatus") public func _bjs_ComplexResultRoundtrip_makeStatus(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeStatus() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeStatus() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -582,7 +598,8 @@ public func _bjs_ComplexResultRoundtrip_makeStatus(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_ComplexResultRoundtrip_makeCoordinates") public func _bjs_ComplexResultRoundtrip_makeCoordinates(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeCoordinates() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeCoordinates() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -593,7 +610,8 @@ public func _bjs_ComplexResultRoundtrip_makeCoordinates(_ _self: UnsafeMutableRa @_cdecl("bjs_ComplexResultRoundtrip_makeComprehensive") public func _bjs_ComplexResultRoundtrip_makeComprehensive(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeComprehensive() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeComprehensive() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -604,7 +622,8 @@ public func _bjs_ComplexResultRoundtrip_makeComprehensive(_ _self: UnsafeMutable @_cdecl("bjs_ComplexResultRoundtrip_makeInfo") public func _bjs_ComplexResultRoundtrip_makeInfo(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).makeInfo() + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeInfo() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -615,7 +634,9 @@ public func _bjs_ComplexResultRoundtrip_makeInfo(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_ComplexResultRoundtrip_roundtrip") public func _bjs_ComplexResultRoundtrip_roundtrip(_ _self: UnsafeMutableRawPointer, _ result: Int32) -> Void { #if arch(wasm32) - let ret = ComplexResultRoundtrip.bridgeJSLiftParameter(_self).roundtrip(_: ComplexResult.bridgeJSLiftParameter(result)) + let result = ComplexResult.bridgeJSLiftParameter(result) + let _self = ComplexResultRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtrip(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -668,7 +689,9 @@ public func _bjs_StringRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_StringRoundtrip_take") public func _bjs_StringRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - StringRoundtrip.bridgeJSLiftParameter(_self).take(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = StringRoundtrip.bridgeJSLiftParameter(_self) + _self.take(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -678,7 +701,8 @@ public func _bjs_StringRoundtrip_take(_ _self: UnsafeMutableRawPointer, _ valueB @_cdecl("bjs_StringRoundtrip_make") public func _bjs_StringRoundtrip_make(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StringRoundtrip.bridgeJSLiftParameter(_self).make() + let _self = StringRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.make() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -731,7 +755,8 @@ public func _bjs_OptionalReturnRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_OptionalReturnRoundtrip_makeIntSome") public func _bjs_OptionalReturnRoundtrip_makeIntSome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeIntSome() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeIntSome() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -742,7 +767,8 @@ public func _bjs_OptionalReturnRoundtrip_makeIntSome(_ _self: UnsafeMutableRawPo @_cdecl("bjs_OptionalReturnRoundtrip_makeIntNone") public func _bjs_OptionalReturnRoundtrip_makeIntNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeIntNone() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeIntNone() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -753,7 +779,8 @@ public func _bjs_OptionalReturnRoundtrip_makeIntNone(_ _self: UnsafeMutableRawPo @_cdecl("bjs_OptionalReturnRoundtrip_makeBoolSome") public func _bjs_OptionalReturnRoundtrip_makeBoolSome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeBoolSome() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeBoolSome() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -764,7 +791,8 @@ public func _bjs_OptionalReturnRoundtrip_makeBoolSome(_ _self: UnsafeMutableRawP @_cdecl("bjs_OptionalReturnRoundtrip_makeBoolNone") public func _bjs_OptionalReturnRoundtrip_makeBoolNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeBoolNone() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeBoolNone() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -775,7 +803,8 @@ public func _bjs_OptionalReturnRoundtrip_makeBoolNone(_ _self: UnsafeMutableRawP @_cdecl("bjs_OptionalReturnRoundtrip_makeDoubleSome") public func _bjs_OptionalReturnRoundtrip_makeDoubleSome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeDoubleSome() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeDoubleSome() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -786,7 +815,8 @@ public func _bjs_OptionalReturnRoundtrip_makeDoubleSome(_ _self: UnsafeMutableRa @_cdecl("bjs_OptionalReturnRoundtrip_makeDoubleNone") public func _bjs_OptionalReturnRoundtrip_makeDoubleNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeDoubleNone() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeDoubleNone() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -797,7 +827,8 @@ public func _bjs_OptionalReturnRoundtrip_makeDoubleNone(_ _self: UnsafeMutableRa @_cdecl("bjs_OptionalReturnRoundtrip_makeStringSome") public func _bjs_OptionalReturnRoundtrip_makeStringSome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeStringSome() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeStringSome() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -808,7 +839,8 @@ public func _bjs_OptionalReturnRoundtrip_makeStringSome(_ _self: UnsafeMutableRa @_cdecl("bjs_OptionalReturnRoundtrip_makeStringNone") public func _bjs_OptionalReturnRoundtrip_makeStringNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self).makeStringNone() + let _self = OptionalReturnRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeStringNone() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -861,7 +893,9 @@ public func _bjs_StructRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_StructRoundtrip_takeSimple") public func _bjs_StructRoundtrip_takeSimple(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - StructRoundtrip.bridgeJSLiftParameter(_self).takeSimple(_: SimpleStruct.bridgeJSLiftParameter()) + let value = SimpleStruct.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + _self.takeSimple(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -871,7 +905,8 @@ public func _bjs_StructRoundtrip_takeSimple(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_StructRoundtrip_makeSimple") public func _bjs_StructRoundtrip_makeSimple(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).makeSimple() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeSimple() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -882,7 +917,9 @@ public func _bjs_StructRoundtrip_makeSimple(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_StructRoundtrip_roundtripSimple") public func _bjs_StructRoundtrip_roundtripSimple(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).roundtripSimple(_: SimpleStruct.bridgeJSLiftParameter()) + let value = SimpleStruct.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripSimple(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -893,7 +930,9 @@ public func _bjs_StructRoundtrip_roundtripSimple(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_StructRoundtrip_takeAddress") public func _bjs_StructRoundtrip_takeAddress(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - StructRoundtrip.bridgeJSLiftParameter(_self).takeAddress(_: Address.bridgeJSLiftParameter()) + let value = Address.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + _self.takeAddress(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -903,7 +942,8 @@ public func _bjs_StructRoundtrip_takeAddress(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_StructRoundtrip_makeAddress") public func _bjs_StructRoundtrip_makeAddress(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).makeAddress() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeAddress() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -914,7 +954,9 @@ public func _bjs_StructRoundtrip_makeAddress(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_StructRoundtrip_roundtripAddress") public func _bjs_StructRoundtrip_roundtripAddress(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).roundtripAddress(_: Address.bridgeJSLiftParameter()) + let value = Address.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripAddress(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -925,7 +967,9 @@ public func _bjs_StructRoundtrip_roundtripAddress(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_StructRoundtrip_takePerson") public func _bjs_StructRoundtrip_takePerson(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - StructRoundtrip.bridgeJSLiftParameter(_self).takePerson(_: Person.bridgeJSLiftParameter()) + let value = Person.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + _self.takePerson(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -935,7 +979,8 @@ public func _bjs_StructRoundtrip_takePerson(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_StructRoundtrip_makePerson") public func _bjs_StructRoundtrip_makePerson(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).makePerson() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makePerson() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -946,7 +991,9 @@ public func _bjs_StructRoundtrip_makePerson(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_StructRoundtrip_roundtripPerson") public func _bjs_StructRoundtrip_roundtripPerson(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).roundtripPerson(_: Person.bridgeJSLiftParameter()) + let value = Person.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripPerson(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -957,7 +1004,9 @@ public func _bjs_StructRoundtrip_roundtripPerson(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_StructRoundtrip_takeComplex") public func _bjs_StructRoundtrip_takeComplex(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - StructRoundtrip.bridgeJSLiftParameter(_self).takeComplex(_: ComplexStruct.bridgeJSLiftParameter()) + let value = ComplexStruct.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + _self.takeComplex(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -967,7 +1016,8 @@ public func _bjs_StructRoundtrip_takeComplex(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_StructRoundtrip_makeComplex") public func _bjs_StructRoundtrip_makeComplex(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).makeComplex() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeComplex() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -978,7 +1028,9 @@ public func _bjs_StructRoundtrip_makeComplex(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_StructRoundtrip_roundtripComplex") public func _bjs_StructRoundtrip_roundtripComplex(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StructRoundtrip.bridgeJSLiftParameter(_self).roundtripComplex(_: ComplexStruct.bridgeJSLiftParameter()) + let value = ComplexStruct.bridgeJSLiftParameter() + let _self = StructRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripComplex(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1020,7 +1072,12 @@ fileprivate func _bjs_StructRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPoi @_cdecl("bjs_SimpleClass_init") public func _bjs_SimpleClass_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ flag: Int32, _ rate: Float32, _ precise: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SimpleClass(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), flag: Bool.bridgeJSLiftParameter(flag), rate: Float.bridgeJSLiftParameter(rate), precise: Double.bridgeJSLiftParameter(precise)) + let precise = Double.bridgeJSLiftParameter(precise) + let rate = Float.bridgeJSLiftParameter(rate) + let flag = Bool.bridgeJSLiftParameter(flag) + let count = Int.bridgeJSLiftParameter(count) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = SimpleClass(name: name, count: count, flag: flag, rate: rate, precise: precise) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1031,7 +1088,8 @@ public func _bjs_SimpleClass_init(_ nameBytes: Int32, _ nameLength: Int32, _ cou @_cdecl("bjs_SimpleClass_name_get") public func _bjs_SimpleClass_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SimpleClass.bridgeJSLiftParameter(_self).name + let _self = SimpleClass.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1042,7 +1100,9 @@ public func _bjs_SimpleClass_name_get(_ _self: UnsafeMutableRawPointer) -> Void @_cdecl("bjs_SimpleClass_name_set") public func _bjs_SimpleClass_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - SimpleClass.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = SimpleClass.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -1052,7 +1112,8 @@ public func _bjs_SimpleClass_name_set(_ _self: UnsafeMutableRawPointer, _ valueB @_cdecl("bjs_SimpleClass_count_get") public func _bjs_SimpleClass_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SimpleClass.bridgeJSLiftParameter(_self).count + let _self = SimpleClass.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1063,7 +1124,9 @@ public func _bjs_SimpleClass_count_get(_ _self: UnsafeMutableRawPointer) -> Int3 @_cdecl("bjs_SimpleClass_count_set") public func _bjs_SimpleClass_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - SimpleClass.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = SimpleClass.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif @@ -1073,7 +1136,8 @@ public func _bjs_SimpleClass_count_set(_ _self: UnsafeMutableRawPointer, _ value @_cdecl("bjs_SimpleClass_flag_get") public func _bjs_SimpleClass_flag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SimpleClass.bridgeJSLiftParameter(_self).flag + let _self = SimpleClass.bridgeJSLiftParameter(_self) + let ret = _self.flag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1084,7 +1148,9 @@ public func _bjs_SimpleClass_flag_get(_ _self: UnsafeMutableRawPointer) -> Int32 @_cdecl("bjs_SimpleClass_flag_set") public func _bjs_SimpleClass_flag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - SimpleClass.bridgeJSLiftParameter(_self).flag = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + let _self = SimpleClass.bridgeJSLiftParameter(_self) + _self.flag = value #else fatalError("Only available on WebAssembly") #endif @@ -1094,7 +1160,8 @@ public func _bjs_SimpleClass_flag_set(_ _self: UnsafeMutableRawPointer, _ value: @_cdecl("bjs_SimpleClass_rate_get") public func _bjs_SimpleClass_rate_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = SimpleClass.bridgeJSLiftParameter(_self).rate + let _self = SimpleClass.bridgeJSLiftParameter(_self) + let ret = _self.rate return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1105,7 +1172,9 @@ public func _bjs_SimpleClass_rate_get(_ _self: UnsafeMutableRawPointer) -> Float @_cdecl("bjs_SimpleClass_rate_set") public func _bjs_SimpleClass_rate_set(_ _self: UnsafeMutableRawPointer, _ value: Float32) -> Void { #if arch(wasm32) - SimpleClass.bridgeJSLiftParameter(_self).rate = Float.bridgeJSLiftParameter(value) + let value = Float.bridgeJSLiftParameter(value) + let _self = SimpleClass.bridgeJSLiftParameter(_self) + _self.rate = value #else fatalError("Only available on WebAssembly") #endif @@ -1115,7 +1184,8 @@ public func _bjs_SimpleClass_rate_set(_ _self: UnsafeMutableRawPointer, _ value: @_cdecl("bjs_SimpleClass_precise_get") public func _bjs_SimpleClass_precise_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = SimpleClass.bridgeJSLiftParameter(_self).precise + let _self = SimpleClass.bridgeJSLiftParameter(_self) + let ret = _self.precise return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1126,7 +1196,9 @@ public func _bjs_SimpleClass_precise_get(_ _self: UnsafeMutableRawPointer) -> Fl @_cdecl("bjs_SimpleClass_precise_set") public func _bjs_SimpleClass_precise_set(_ _self: UnsafeMutableRawPointer, _ value: Float64) -> Void { #if arch(wasm32) - SimpleClass.bridgeJSLiftParameter(_self).precise = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + let _self = SimpleClass.bridgeJSLiftParameter(_self) + _self.precise = value #else fatalError("Only available on WebAssembly") #endif @@ -1167,7 +1239,10 @@ fileprivate func _bjs_SimpleClass_wrap_extern(_ pointer: UnsafeMutableRawPointer @_cdecl("bjs_AddressClass_init") public func _bjs_AddressClass_init(_ streetBytes: Int32, _ streetLength: Int32, _ cityBytes: Int32, _ cityLength: Int32, _ zipCode: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = AddressClass(street: String.bridgeJSLiftParameter(streetBytes, streetLength), city: String.bridgeJSLiftParameter(cityBytes, cityLength), zipCode: Int.bridgeJSLiftParameter(zipCode)) + let zipCode = Int.bridgeJSLiftParameter(zipCode) + let city = String.bridgeJSLiftParameter(cityBytes, cityLength) + let street = String.bridgeJSLiftParameter(streetBytes, streetLength) + let ret = AddressClass(street: street, city: city, zipCode: zipCode) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1178,7 +1253,8 @@ public func _bjs_AddressClass_init(_ streetBytes: Int32, _ streetLength: Int32, @_cdecl("bjs_AddressClass_street_get") public func _bjs_AddressClass_street_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = AddressClass.bridgeJSLiftParameter(_self).street + let _self = AddressClass.bridgeJSLiftParameter(_self) + let ret = _self.street return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1189,7 +1265,9 @@ public func _bjs_AddressClass_street_get(_ _self: UnsafeMutableRawPointer) -> Vo @_cdecl("bjs_AddressClass_street_set") public func _bjs_AddressClass_street_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - AddressClass.bridgeJSLiftParameter(_self).street = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = AddressClass.bridgeJSLiftParameter(_self) + _self.street = value #else fatalError("Only available on WebAssembly") #endif @@ -1199,7 +1277,8 @@ public func _bjs_AddressClass_street_set(_ _self: UnsafeMutableRawPointer, _ val @_cdecl("bjs_AddressClass_city_get") public func _bjs_AddressClass_city_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = AddressClass.bridgeJSLiftParameter(_self).city + let _self = AddressClass.bridgeJSLiftParameter(_self) + let ret = _self.city return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1210,7 +1289,9 @@ public func _bjs_AddressClass_city_get(_ _self: UnsafeMutableRawPointer) -> Void @_cdecl("bjs_AddressClass_city_set") public func _bjs_AddressClass_city_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - AddressClass.bridgeJSLiftParameter(_self).city = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = AddressClass.bridgeJSLiftParameter(_self) + _self.city = value #else fatalError("Only available on WebAssembly") #endif @@ -1220,7 +1301,8 @@ public func _bjs_AddressClass_city_set(_ _self: UnsafeMutableRawPointer, _ value @_cdecl("bjs_AddressClass_zipCode_get") public func _bjs_AddressClass_zipCode_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = AddressClass.bridgeJSLiftParameter(_self).zipCode + let _self = AddressClass.bridgeJSLiftParameter(_self) + let ret = _self.zipCode return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1231,7 +1313,9 @@ public func _bjs_AddressClass_zipCode_get(_ _self: UnsafeMutableRawPointer) -> I @_cdecl("bjs_AddressClass_zipCode_set") public func _bjs_AddressClass_zipCode_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - AddressClass.bridgeJSLiftParameter(_self).zipCode = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = AddressClass.bridgeJSLiftParameter(_self) + _self.zipCode = value #else fatalError("Only available on WebAssembly") #endif @@ -1283,7 +1367,9 @@ public func _bjs_ClassRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ClassRoundtrip_takeSimpleClass") public func _bjs_ClassRoundtrip_takeSimpleClass(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassRoundtrip.bridgeJSLiftParameter(_self).takeSimpleClass(_: SimpleClass.bridgeJSLiftParameter(value)) + let value = SimpleClass.bridgeJSLiftParameter(value) + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + _self.takeSimpleClass(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -1293,7 +1379,8 @@ public func _bjs_ClassRoundtrip_takeSimpleClass(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ClassRoundtrip_makeSimpleClass") public func _bjs_ClassRoundtrip_makeSimpleClass(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtrip.bridgeJSLiftParameter(_self).makeSimpleClass() + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeSimpleClass() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1304,7 +1391,9 @@ public func _bjs_ClassRoundtrip_makeSimpleClass(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ClassRoundtrip_roundtripSimpleClass") public func _bjs_ClassRoundtrip_roundtripSimpleClass(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtrip.bridgeJSLiftParameter(_self).roundtripSimpleClass(_: SimpleClass.bridgeJSLiftParameter(value)) + let value = SimpleClass.bridgeJSLiftParameter(value) + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripSimpleClass(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1315,7 +1404,9 @@ public func _bjs_ClassRoundtrip_roundtripSimpleClass(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ClassRoundtrip_takeAddressClass") public func _bjs_ClassRoundtrip_takeAddressClass(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassRoundtrip.bridgeJSLiftParameter(_self).takeAddressClass(_: AddressClass.bridgeJSLiftParameter(value)) + let value = AddressClass.bridgeJSLiftParameter(value) + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + _self.takeAddressClass(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -1325,7 +1416,8 @@ public func _bjs_ClassRoundtrip_takeAddressClass(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_ClassRoundtrip_makeAddressClass") public func _bjs_ClassRoundtrip_makeAddressClass(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtrip.bridgeJSLiftParameter(_self).makeAddressClass() + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeAddressClass() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1336,7 +1428,9 @@ public func _bjs_ClassRoundtrip_makeAddressClass(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_ClassRoundtrip_roundtripAddressClass") public func _bjs_ClassRoundtrip_roundtripAddressClass(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtrip.bridgeJSLiftParameter(_self).roundtripAddressClass(_: AddressClass.bridgeJSLiftParameter(value)) + let value = AddressClass.bridgeJSLiftParameter(value) + let _self = ClassRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripAddressClass(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1389,7 +1483,9 @@ public func _bjs_ClassArrayRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ClassArrayRoundtrip_setupPool") public func _bjs_ClassArrayRoundtrip_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { #if arch(wasm32) - ClassArrayRoundtrip.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let _self = ClassArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.setupPool(_: count) #else fatalError("Only available on WebAssembly") #endif @@ -1399,7 +1495,8 @@ public func _bjs_ClassArrayRoundtrip_setupPool(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_ClassArrayRoundtrip_getPool") public func _bjs_ClassArrayRoundtrip_getPool(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).getPool() + let _self = ClassArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.getPool() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1410,7 +1507,8 @@ public func _bjs_ClassArrayRoundtrip_getPool(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_ClassArrayRoundtrip_makeClassArray") public func _bjs_ClassArrayRoundtrip_makeClassArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).makeClassArray() + let _self = ClassArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeClassArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1421,7 +1519,9 @@ public func _bjs_ClassArrayRoundtrip_makeClassArray(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ClassArrayRoundtrip_takeClassArray") public func _bjs_ClassArrayRoundtrip_takeClassArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassArrayRoundtrip.bridgeJSLiftParameter(_self).takeClassArray(_: [SimpleClass].bridgeJSStackPop()) + let values = [SimpleClass].bridgeJSStackPop() + let _self = ClassArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeClassArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -1431,7 +1531,9 @@ public func _bjs_ClassArrayRoundtrip_takeClassArray(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ClassArrayRoundtrip_roundtripClassArray") public func _bjs_ClassArrayRoundtrip_roundtripClassArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClassArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripClassArray(_: [SimpleClass].bridgeJSStackPop()) + let values = [SimpleClass].bridgeJSStackPop() + let _self = ClassArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripClassArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1484,7 +1586,9 @@ public func _bjs_IdentityCacheBenchmark_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_IdentityCacheBenchmark_setupPool") public func _bjs_IdentityCacheBenchmark_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { #if arch(wasm32) - IdentityCacheBenchmark.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let _self = IdentityCacheBenchmark.bridgeJSLiftParameter(_self) + _self.setupPool(_: count) #else fatalError("Only available on WebAssembly") #endif @@ -1494,7 +1598,8 @@ public func _bjs_IdentityCacheBenchmark_setupPool(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_IdentityCacheBenchmark_getPoolRepeated") public func _bjs_IdentityCacheBenchmark_getPoolRepeated(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = IdentityCacheBenchmark.bridgeJSLiftParameter(_self).getPoolRepeated() + let _self = IdentityCacheBenchmark.bridgeJSLiftParameter(_self) + let ret = _self.getPoolRepeated() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1536,7 +1641,12 @@ fileprivate func _bjs_IdentityCacheBenchmark_wrap_extern(_ pointer: UnsafeMutabl @_cdecl("bjs_SimpleClassIdentity_init") public func _bjs_SimpleClassIdentity_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ flag: Int32, _ rate: Float32, _ precise: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SimpleClassIdentity(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), flag: Bool.bridgeJSLiftParameter(flag), rate: Float.bridgeJSLiftParameter(rate), precise: Double.bridgeJSLiftParameter(precise)) + let precise = Double.bridgeJSLiftParameter(precise) + let rate = Float.bridgeJSLiftParameter(rate) + let flag = Bool.bridgeJSLiftParameter(flag) + let count = Int.bridgeJSLiftParameter(count) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = SimpleClassIdentity(name: name, count: count, flag: flag, rate: rate, precise: precise) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1547,7 +1657,8 @@ public func _bjs_SimpleClassIdentity_init(_ nameBytes: Int32, _ nameLength: Int3 @_cdecl("bjs_SimpleClassIdentity_name_get") public func _bjs_SimpleClassIdentity_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).name + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1558,7 +1669,9 @@ public func _bjs_SimpleClassIdentity_name_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_SimpleClassIdentity_name_set") public func _bjs_SimpleClassIdentity_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - SimpleClassIdentity.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -1568,7 +1681,8 @@ public func _bjs_SimpleClassIdentity_name_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SimpleClassIdentity_count_get") public func _bjs_SimpleClassIdentity_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).count + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1579,7 +1693,9 @@ public func _bjs_SimpleClassIdentity_count_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_SimpleClassIdentity_count_set") public func _bjs_SimpleClassIdentity_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - SimpleClassIdentity.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif @@ -1589,7 +1705,8 @@ public func _bjs_SimpleClassIdentity_count_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SimpleClassIdentity_flag_get") public func _bjs_SimpleClassIdentity_flag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).flag + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + let ret = _self.flag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1600,7 +1717,9 @@ public func _bjs_SimpleClassIdentity_flag_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_SimpleClassIdentity_flag_set") public func _bjs_SimpleClassIdentity_flag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - SimpleClassIdentity.bridgeJSLiftParameter(_self).flag = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + _self.flag = value #else fatalError("Only available on WebAssembly") #endif @@ -1610,7 +1729,8 @@ public func _bjs_SimpleClassIdentity_flag_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SimpleClassIdentity_rate_get") public func _bjs_SimpleClassIdentity_rate_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).rate + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + let ret = _self.rate return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1621,7 +1741,9 @@ public func _bjs_SimpleClassIdentity_rate_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_SimpleClassIdentity_rate_set") public func _bjs_SimpleClassIdentity_rate_set(_ _self: UnsafeMutableRawPointer, _ value: Float32) -> Void { #if arch(wasm32) - SimpleClassIdentity.bridgeJSLiftParameter(_self).rate = Float.bridgeJSLiftParameter(value) + let value = Float.bridgeJSLiftParameter(value) + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + _self.rate = value #else fatalError("Only available on WebAssembly") #endif @@ -1631,7 +1753,8 @@ public func _bjs_SimpleClassIdentity_rate_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SimpleClassIdentity_precise_get") public func _bjs_SimpleClassIdentity_precise_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = SimpleClassIdentity.bridgeJSLiftParameter(_self).precise + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + let ret = _self.precise return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1642,7 +1765,9 @@ public func _bjs_SimpleClassIdentity_precise_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_SimpleClassIdentity_precise_set") public func _bjs_SimpleClassIdentity_precise_set(_ _self: UnsafeMutableRawPointer, _ value: Float64) -> Void { #if arch(wasm32) - SimpleClassIdentity.bridgeJSLiftParameter(_self).precise = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + let _self = SimpleClassIdentity.bridgeJSLiftParameter(_self) + _self.precise = value #else fatalError("Only available on WebAssembly") #endif @@ -1694,7 +1819,9 @@ public func _bjs_ClassRoundtripIdentity_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity") public func _bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity(_ _self: UnsafeMutableRawPointer, _ obj: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtripIdentity.bridgeJSLiftParameter(_self).roundtripSimpleClassIdentity(_: SimpleClassIdentity.bridgeJSLiftParameter(obj)) + let obj = SimpleClassIdentity.bridgeJSLiftParameter(obj) + let _self = ClassRoundtripIdentity.bridgeJSLiftParameter(_self) + let ret = _self.roundtripSimpleClassIdentity(_: obj) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1705,7 +1832,8 @@ public func _bjs_ClassRoundtripIdentity_roundtripSimpleClassIdentity(_ _self: Un @_cdecl("bjs_ClassRoundtripIdentity_makeSimpleClassIdentity") public func _bjs_ClassRoundtripIdentity_makeSimpleClassIdentity(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ClassRoundtripIdentity.bridgeJSLiftParameter(_self).makeSimpleClassIdentity() + let _self = ClassRoundtripIdentity.bridgeJSLiftParameter(_self) + let ret = _self.makeSimpleClassIdentity() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -1716,7 +1844,9 @@ public func _bjs_ClassRoundtripIdentity_makeSimpleClassIdentity(_ _self: UnsafeM @_cdecl("bjs_ClassRoundtripIdentity_takeSimpleClassIdentity") public func _bjs_ClassRoundtripIdentity_takeSimpleClassIdentity(_ _self: UnsafeMutableRawPointer, _ obj: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassRoundtripIdentity.bridgeJSLiftParameter(_self).takeSimpleClassIdentity(_: SimpleClassIdentity.bridgeJSLiftParameter(obj)) + let obj = SimpleClassIdentity.bridgeJSLiftParameter(obj) + let _self = ClassRoundtripIdentity.bridgeJSLiftParameter(_self) + _self.takeSimpleClassIdentity(_: obj) #else fatalError("Only available on WebAssembly") #endif @@ -1768,7 +1898,9 @@ public func _bjs_IdentityCacheBenchmarkIdentity_init() -> UnsafeMutableRawPointe @_cdecl("bjs_IdentityCacheBenchmarkIdentity_setupPool") public func _bjs_IdentityCacheBenchmarkIdentity_setupPool(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Void { #if arch(wasm32) - IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self).setupPool(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let _self = IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self) + _self.setupPool(_: count) #else fatalError("Only available on WebAssembly") #endif @@ -1778,7 +1910,8 @@ public func _bjs_IdentityCacheBenchmarkIdentity_setupPool(_ _self: UnsafeMutable @_cdecl("bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated") public func _bjs_IdentityCacheBenchmarkIdentity_getPoolRepeated(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self).getPoolRepeated() + let _self = IdentityCacheBenchmarkIdentity.bridgeJSLiftParameter(_self) + let ret = _self.getPoolRepeated() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1831,7 +1964,9 @@ public func _bjs_ArrayRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ArrayRoundtrip_takeIntArray") public func _bjs_ArrayRoundtrip_takeIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeIntArray(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeIntArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -1841,7 +1976,8 @@ public func _bjs_ArrayRoundtrip_takeIntArray(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_ArrayRoundtrip_makeIntArray") public func _bjs_ArrayRoundtrip_makeIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeIntArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeIntArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1852,7 +1988,9 @@ public func _bjs_ArrayRoundtrip_makeIntArray(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_ArrayRoundtrip_roundtripIntArray") public func _bjs_ArrayRoundtrip_roundtripIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripIntArray(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1863,7 +2001,8 @@ public func _bjs_ArrayRoundtrip_roundtripIntArray(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_ArrayRoundtrip_makeIntArrayLarge") public func _bjs_ArrayRoundtrip_makeIntArrayLarge(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeIntArrayLarge() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeIntArrayLarge() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1874,7 +2013,9 @@ public func _bjs_ArrayRoundtrip_makeIntArrayLarge(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_ArrayRoundtrip_takeDoubleArray") public func _bjs_ArrayRoundtrip_takeDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeDoubleArray(_: [Double].bridgeJSStackPop()) + let values = [Double].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeDoubleArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -1884,7 +2025,8 @@ public func _bjs_ArrayRoundtrip_takeDoubleArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_makeDoubleArray") public func _bjs_ArrayRoundtrip_makeDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeDoubleArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeDoubleArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1895,7 +2037,9 @@ public func _bjs_ArrayRoundtrip_makeDoubleArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_roundtripDoubleArray") public func _bjs_ArrayRoundtrip_roundtripDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripDoubleArray(_: [Double].bridgeJSStackPop()) + let values = [Double].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripDoubleArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1906,7 +2050,9 @@ public func _bjs_ArrayRoundtrip_roundtripDoubleArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_takeStringArray") public func _bjs_ArrayRoundtrip_takeStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeStringArray(_: [String].bridgeJSStackPop()) + let values = [String].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeStringArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -1916,7 +2062,8 @@ public func _bjs_ArrayRoundtrip_takeStringArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_makeStringArray") public func _bjs_ArrayRoundtrip_makeStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeStringArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeStringArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1927,7 +2074,9 @@ public func _bjs_ArrayRoundtrip_makeStringArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_roundtripStringArray") public func _bjs_ArrayRoundtrip_roundtripStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripStringArray(_: [String].bridgeJSStackPop()) + let values = [String].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripStringArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1938,7 +2087,9 @@ public func _bjs_ArrayRoundtrip_roundtripStringArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_takePointArray") public func _bjs_ArrayRoundtrip_takePointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takePointArray(_: [Point].bridgeJSStackPop()) + let points = [Point].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takePointArray(_: points) #else fatalError("Only available on WebAssembly") #endif @@ -1948,7 +2099,8 @@ public func _bjs_ArrayRoundtrip_takePointArray(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ArrayRoundtrip_makePointArray") public func _bjs_ArrayRoundtrip_makePointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makePointArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makePointArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1959,7 +2111,9 @@ public func _bjs_ArrayRoundtrip_makePointArray(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ArrayRoundtrip_roundtripPointArray") public func _bjs_ArrayRoundtrip_roundtripPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripPointArray(_: [Point].bridgeJSStackPop()) + let points = [Point].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1970,7 +2124,8 @@ public func _bjs_ArrayRoundtrip_roundtripPointArray(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ArrayRoundtrip_makePointArrayLarge") public func _bjs_ArrayRoundtrip_makePointArrayLarge(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makePointArrayLarge() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makePointArrayLarge() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -1981,7 +2136,9 @@ public func _bjs_ArrayRoundtrip_makePointArrayLarge(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ArrayRoundtrip_takeNestedIntArray") public func _bjs_ArrayRoundtrip_takeNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedIntArray(_: [[Int]].bridgeJSStackPop()) + let values = [[Int]].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeNestedIntArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -1991,7 +2148,8 @@ public func _bjs_ArrayRoundtrip_takeNestedIntArray(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_ArrayRoundtrip_makeNestedIntArray") public func _bjs_ArrayRoundtrip_makeNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeNestedIntArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeNestedIntArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2002,7 +2160,9 @@ public func _bjs_ArrayRoundtrip_makeNestedIntArray(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_ArrayRoundtrip_roundtripNestedIntArray") public func _bjs_ArrayRoundtrip_roundtripNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedIntArray(_: [[Int]].bridgeJSStackPop()) + let values = [[Int]].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripNestedIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2013,7 +2173,9 @@ public func _bjs_ArrayRoundtrip_roundtripNestedIntArray(_ _self: UnsafeMutableRa @_cdecl("bjs_ArrayRoundtrip_takeNestedPointArray") public func _bjs_ArrayRoundtrip_takeNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedPointArray(_: [[Point]].bridgeJSStackPop()) + let points = [[Point]].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeNestedPointArray(_: points) #else fatalError("Only available on WebAssembly") #endif @@ -2023,7 +2185,8 @@ public func _bjs_ArrayRoundtrip_takeNestedPointArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_makeNestedPointArray") public func _bjs_ArrayRoundtrip_makeNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeNestedPointArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeNestedPointArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2034,7 +2197,9 @@ public func _bjs_ArrayRoundtrip_makeNestedPointArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_roundtripNestedPointArray") public func _bjs_ArrayRoundtrip_roundtripNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedPointArray(_: [[Point]].bridgeJSStackPop()) + let points = [[Point]].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripNestedPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2045,7 +2210,9 @@ public func _bjs_ArrayRoundtrip_roundtripNestedPointArray(_ _self: UnsafeMutable @_cdecl("bjs_ArrayRoundtrip_takeOptionalIntArray") public func _bjs_ArrayRoundtrip_takeOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalIntArray(_: [Optional].bridgeJSStackPop()) + let values = [Optional].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeOptionalIntArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -2055,7 +2222,8 @@ public func _bjs_ArrayRoundtrip_takeOptionalIntArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_makeOptionalIntArray") public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalIntArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalIntArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2066,7 +2234,9 @@ public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalIntArray") public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalIntArray(_: [Optional].bridgeJSStackPop()) + let values = [Optional].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripOptionalIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2077,7 +2247,9 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutable @_cdecl("bjs_ArrayRoundtrip_takeOptionalPointArray") public func _bjs_ArrayRoundtrip_takeOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalPointArray(_: [Optional].bridgeJSStackPop()) + let points = [Optional].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeOptionalPointArray(_: points) #else fatalError("Only available on WebAssembly") #endif @@ -2087,7 +2259,8 @@ public func _bjs_ArrayRoundtrip_takeOptionalPointArray(_ _self: UnsafeMutableRaw @_cdecl("bjs_ArrayRoundtrip_makeOptionalPointArray") public func _bjs_ArrayRoundtrip_makeOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalPointArray() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalPointArray() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2098,7 +2271,9 @@ public func _bjs_ArrayRoundtrip_makeOptionalPointArray(_ _self: UnsafeMutableRaw @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalPointArray") public func _bjs_ArrayRoundtrip_roundtripOptionalPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalPointArray(_: [Optional].bridgeJSStackPop()) + let points = [Optional].bridgeJSStackPop() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripOptionalPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2109,7 +2284,9 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalPointArray(_ _self: UnsafeMutab @_cdecl("bjs_ArrayRoundtrip_takeOptionalArray") public func _bjs_ArrayRoundtrip_takeOptionalArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + let values = Optional<[Int]>.bridgeJSLiftParameter() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + _self.takeOptionalArray(_: values) #else fatalError("Only available on WebAssembly") #endif @@ -2119,7 +2296,8 @@ public func _bjs_ArrayRoundtrip_takeOptionalArray(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_ArrayRoundtrip_makeOptionalArraySome") public func _bjs_ArrayRoundtrip_makeOptionalArraySome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalArraySome() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalArraySome() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2130,7 +2308,8 @@ public func _bjs_ArrayRoundtrip_makeOptionalArraySome(_ _self: UnsafeMutableRawP @_cdecl("bjs_ArrayRoundtrip_makeOptionalArrayNone") public func _bjs_ArrayRoundtrip_makeOptionalArrayNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalArrayNone() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalArrayNone() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -2141,7 +2320,9 @@ public func _bjs_ArrayRoundtrip_makeOptionalArrayNone(_ _self: UnsafeMutableRawP @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalArray") public func _bjs_ArrayRoundtrip_roundtripOptionalArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + let values = Optional<[Int]>.bridgeJSLiftParameter() + let _self = ArrayRoundtrip.bridgeJSLiftParameter(_self) + let ret = _self.roundtripOptionalArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 328ae0610..eed55bdea 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -179,8 +179,11 @@ public func _bjs_PlayBridgeJS_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_PlayBridgeJS_updateDetailed") public func _bjs_PlayBridgeJS_updateDetailed(_ _self: UnsafeMutableRawPointer, _ swiftSourceBytes: Int32, _ swiftSourceLength: Int32, _ dtsSourceBytes: Int32, _ dtsSourceLength: Int32) -> Void { #if arch(wasm32) + let dtsSource = String.bridgeJSLiftParameter(dtsSourceBytes, dtsSourceLength) + let swiftSource = String.bridgeJSLiftParameter(swiftSourceBytes, swiftSourceLength) + let _self = PlayBridgeJS.bridgeJSLiftParameter(_self) do { - let ret = try PlayBridgeJS.bridgeJSLiftParameter(_self).updateDetailed(swiftSource: String.bridgeJSLiftParameter(swiftSourceBytes, swiftSourceLength), dtsSource: String.bridgeJSLiftParameter(dtsSourceBytes, dtsSourceLength)) + let ret = try _self.updateDetailed(swiftSource: swiftSource, dtsSource: dtsSource) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 4d2a84763..b77fc962d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -78,6 +78,10 @@ extension Vector2D { @JS func describe() -> String { return "Vector2D(\(dx), \(dy))" } + + @JS func dot(_ components: [Double]) -> Double { + return zip([dx, dy], components).map(*).reduce(0, +) + } } extension DataPoint { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index b88c6717e..af8a8a453 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -53,7 +53,8 @@ extension InnerTag: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_roundtripPolygon") public func _bjs_roundtripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundtripPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = roundtripPolygon(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -64,7 +65,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)) + let polygon = Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue) + let ret = optionalPolygon(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -75,7 +77,8 @@ public func _bjs_optionalPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeM @_cdecl("bjs_polygonArray") public func _bjs_polygonArray() -> Void { #if arch(wasm32) - let ret = polygonArray(_: [Polygon].bridgeJSStackPop()) + let polygons = [Polygon].bridgeJSStackPop() + let ret = polygonArray(_: polygons) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -86,8 +89,9 @@ public func _bjs_polygonArray() -> Void { @_cdecl("bjs_validatePolygon") public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) + let polygon = Polygon.bridgeJSLiftParameter(polygon) do { - let ret = try validatePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let ret = try validatePolygon(_: polygon) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -111,7 +115,8 @@ public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMu @_cdecl("bjs_makeTag") public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = makeTag(_: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -122,7 +127,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()) + let xs = [Optional].bridgeJSStackPop() + let ret = roundtripTags(_: xs) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -133,7 +139,8 @@ public func _bjs_roundtripTags() -> Void { @_cdecl("bjs_describeUser") public func _bjs_describeUser(_ owner: Int32) -> Int32 { #if arch(wasm32) - let ret = _bridgeJSUnwrapProtocolExportable(describeUser(_: AnyHasOptionalUserId.bridgeJSLiftParameter(owner)), "HasOptionalUserId") + let owner = AnyHasOptionalUserId.bridgeJSLiftParameter(owner) + let ret = _bridgeJSUnwrapProtocolExportable(describeUser(_: owner), "HasOptionalUserId") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -144,7 +151,8 @@ 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.bridgeJSLiftParameter(underlying)) + let underlying = Polygon.bridgeJSLiftParameter(underlying) + let ret = PolygonReference(underlying: underlying) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -155,7 +163,8 @@ public func _bjs_PolygonReference_init(_ underlying: UnsafeMutableRawPointer) -> @_cdecl("bjs_PolygonReference_snapshot") public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.snapshot() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -166,7 +175,9 @@ 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.bridgeJSLiftParameter(other)) + let other = Polygon.bridgeJSLiftParameter(other) + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.merge(_: other) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -219,7 +230,8 @@ 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.bridgeJSLiftParameter(underlying)) + let underlying = Tag.bridgeJSLiftParameter(underlying) + let ret = TagReference(underlying: underlying) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index 0a208bf70..dc9c97c06 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -53,9 +53,10 @@ extension JSTypedClosure where Signature == (Polygon) -> Int { @_cdecl("invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si") public func _invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) + let param0 = Polygon.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Polygon.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -116,8 +117,8 @@ extension JSTypedClosure where Signature == () -> Polygon { 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.bridgeJSLowerReturn() + let ret = closure() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -149,7 +150,8 @@ public func _bjs_makePolygonInspector() -> Int32 { @_cdecl("bjs_PolygonReference_init") public func _bjs_PolygonReference_init(_ sides: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference(sides: Int.bridgeJSLiftParameter(sides)) + let sides = Int.bridgeJSLiftParameter(sides) + let ret = PolygonReference(sides: sides) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index 94b8eb208..2ee2de3b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -96,7 +96,8 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { @_cdecl("bjs_processIntArray") public func _bjs_processIntArray() -> Void { #if arch(wasm32) - let ret = processIntArray(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let ret = processIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -107,7 +108,8 @@ public func _bjs_processIntArray() -> Void { @_cdecl("bjs_processStringArray") public func _bjs_processStringArray() -> Void { #if arch(wasm32) - let ret = processStringArray(_: [String].bridgeJSStackPop()) + let values = [String].bridgeJSStackPop() + let ret = processStringArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -118,7 +120,8 @@ public func _bjs_processStringArray() -> Void { @_cdecl("bjs_processDoubleArray") public func _bjs_processDoubleArray() -> Void { #if arch(wasm32) - let ret = processDoubleArray(_: [Double].bridgeJSStackPop()) + let values = [Double].bridgeJSStackPop() + let ret = processDoubleArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -129,7 +132,8 @@ public func _bjs_processDoubleArray() -> Void { @_cdecl("bjs_processBoolArray") public func _bjs_processBoolArray() -> Void { #if arch(wasm32) - let ret = processBoolArray(_: [Bool].bridgeJSStackPop()) + let values = [Bool].bridgeJSStackPop() + let ret = processBoolArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -140,7 +144,8 @@ public func _bjs_processBoolArray() -> Void { @_cdecl("bjs_processPointArray") public func _bjs_processPointArray() -> Void { #if arch(wasm32) - let ret = processPointArray(_: [Point].bridgeJSStackPop()) + let points = [Point].bridgeJSStackPop() + let ret = processPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -151,7 +156,8 @@ public func _bjs_processPointArray() -> Void { @_cdecl("bjs_processDirectionArray") public func _bjs_processDirectionArray() -> Void { #if arch(wasm32) - let ret = processDirectionArray(_: [Direction].bridgeJSStackPop()) + let directions = [Direction].bridgeJSStackPop() + let ret = processDirectionArray(_: directions) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -162,7 +168,8 @@ public func _bjs_processDirectionArray() -> Void { @_cdecl("bjs_processStatusArray") public func _bjs_processStatusArray() -> Void { #if arch(wasm32) - let ret = processStatusArray(_: [Status].bridgeJSStackPop()) + let statuses = [Status].bridgeJSStackPop() + let ret = processStatusArray(_: statuses) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -173,7 +180,8 @@ public func _bjs_processStatusArray() -> Void { @_cdecl("bjs_sumIntArray") public func _bjs_sumIntArray() -> Int32 { #if arch(wasm32) - let ret = sumIntArray(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let ret = sumIntArray(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -184,7 +192,9 @@ public func _bjs_sumIntArray() -> Int32 { @_cdecl("bjs_findFirstPoint") public func _bjs_findFirstPoint(_ matchingBytes: Int32, _ matchingLength: Int32) -> Void { #if arch(wasm32) - let ret = findFirstPoint(_: [Point].bridgeJSStackPop(), matching: String.bridgeJSLiftParameter(matchingBytes, matchingLength)) + let matching = String.bridgeJSLiftParameter(matchingBytes, matchingLength) + let points = [Point].bridgeJSStackPop() + let ret = findFirstPoint(_: points, matching: matching) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -195,7 +205,8 @@ public func _bjs_findFirstPoint(_ matchingBytes: Int32, _ matchingLength: Int32) @_cdecl("bjs_processUnsafeRawPointerArray") public func _bjs_processUnsafeRawPointerArray() -> Void { #if arch(wasm32) - let ret = processUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) + let values = [UnsafeRawPointer].bridgeJSStackPop() + let ret = processUnsafeRawPointerArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -206,7 +217,8 @@ public func _bjs_processUnsafeRawPointerArray() -> Void { @_cdecl("bjs_processUnsafeMutableRawPointerArray") public func _bjs_processUnsafeMutableRawPointerArray() -> Void { #if arch(wasm32) - let ret = processUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) + let values = [UnsafeMutableRawPointer].bridgeJSStackPop() + let ret = processUnsafeMutableRawPointerArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -217,7 +229,8 @@ public func _bjs_processUnsafeMutableRawPointerArray() -> Void { @_cdecl("bjs_processOpaquePointerArray") public func _bjs_processOpaquePointerArray() -> Void { #if arch(wasm32) - let ret = processOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) + let values = [OpaquePointer].bridgeJSStackPop() + let ret = processOpaquePointerArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -228,7 +241,8 @@ public func _bjs_processOpaquePointerArray() -> Void { @_cdecl("bjs_processOptionalIntArray") public func _bjs_processOptionalIntArray() -> Void { #if arch(wasm32) - let ret = processOptionalIntArray(_: [Optional].bridgeJSStackPop()) + let values = [Optional].bridgeJSStackPop() + let ret = processOptionalIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -239,7 +253,8 @@ public func _bjs_processOptionalIntArray() -> Void { @_cdecl("bjs_processOptionalStringArray") public func _bjs_processOptionalStringArray() -> Void { #if arch(wasm32) - let ret = processOptionalStringArray(_: [Optional].bridgeJSStackPop()) + let values = [Optional].bridgeJSStackPop() + let ret = processOptionalStringArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -250,7 +265,8 @@ public func _bjs_processOptionalStringArray() -> Void { @_cdecl("bjs_processOptionalArray") public func _bjs_processOptionalArray() -> Void { #if arch(wasm32) - let ret = processOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + let values = Optional<[Int]>.bridgeJSLiftParameter() + let ret = processOptionalArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -261,7 +277,8 @@ public func _bjs_processOptionalArray() -> Void { @_cdecl("bjs_processOptionalPointArray") public func _bjs_processOptionalPointArray() -> Void { #if arch(wasm32) - let ret = processOptionalPointArray(_: [Optional].bridgeJSStackPop()) + let points = [Optional].bridgeJSStackPop() + let ret = processOptionalPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -272,7 +289,8 @@ public func _bjs_processOptionalPointArray() -> Void { @_cdecl("bjs_processOptionalDirectionArray") public func _bjs_processOptionalDirectionArray() -> Void { #if arch(wasm32) - let ret = processOptionalDirectionArray(_: [Optional].bridgeJSStackPop()) + let directions = [Optional].bridgeJSStackPop() + let ret = processOptionalDirectionArray(_: directions) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -283,7 +301,8 @@ public func _bjs_processOptionalDirectionArray() -> Void { @_cdecl("bjs_processOptionalStatusArray") public func _bjs_processOptionalStatusArray() -> Void { #if arch(wasm32) - let ret = processOptionalStatusArray(_: [Optional].bridgeJSStackPop()) + let statuses = [Optional].bridgeJSStackPop() + let ret = processOptionalStatusArray(_: statuses) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -294,7 +313,8 @@ public func _bjs_processOptionalStatusArray() -> Void { @_cdecl("bjs_processNestedIntArray") public func _bjs_processNestedIntArray() -> Void { #if arch(wasm32) - let ret = processNestedIntArray(_: [[Int]].bridgeJSStackPop()) + let values = [[Int]].bridgeJSStackPop() + let ret = processNestedIntArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -305,7 +325,8 @@ public func _bjs_processNestedIntArray() -> Void { @_cdecl("bjs_processNestedStringArray") public func _bjs_processNestedStringArray() -> Void { #if arch(wasm32) - let ret = processNestedStringArray(_: [[String]].bridgeJSStackPop()) + let values = [[String]].bridgeJSStackPop() + let ret = processNestedStringArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -316,7 +337,8 @@ public func _bjs_processNestedStringArray() -> Void { @_cdecl("bjs_processNestedPointArray") public func _bjs_processNestedPointArray() -> Void { #if arch(wasm32) - let ret = processNestedPointArray(_: [[Point]].bridgeJSStackPop()) + let points = [[Point]].bridgeJSStackPop() + let ret = processNestedPointArray(_: points) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -327,7 +349,8 @@ public func _bjs_processNestedPointArray() -> Void { @_cdecl("bjs_processItemArray") public func _bjs_processItemArray() -> Void { #if arch(wasm32) - let ret = processItemArray(_: [Item].bridgeJSStackPop()) + let items = [Item].bridgeJSStackPop() + let ret = processItemArray(_: items) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -338,7 +361,8 @@ public func _bjs_processItemArray() -> Void { @_cdecl("bjs_processNestedItemArray") public func _bjs_processNestedItemArray() -> Void { #if arch(wasm32) - let ret = processNestedItemArray(_: [[Item]].bridgeJSStackPop()) + let items = [[Item]].bridgeJSStackPop() + let ret = processNestedItemArray(_: items) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -349,7 +373,8 @@ public func _bjs_processNestedItemArray() -> Void { @_cdecl("bjs_processJSObjectArray") public func _bjs_processJSObjectArray() -> Void { #if arch(wasm32) - let ret = processJSObjectArray(_: [JSObject].bridgeJSStackPop()) + let objects = [JSObject].bridgeJSStackPop() + let ret = processJSObjectArray(_: objects) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -360,7 +385,8 @@ public func _bjs_processJSObjectArray() -> Void { @_cdecl("bjs_processOptionalJSObjectArray") public func _bjs_processOptionalJSObjectArray() -> Void { #if arch(wasm32) - let ret = processOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) + let objects = [Optional].bridgeJSStackPop() + let ret = processOptionalJSObjectArray(_: objects) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -371,7 +397,8 @@ public func _bjs_processOptionalJSObjectArray() -> Void { @_cdecl("bjs_processNestedJSObjectArray") public func _bjs_processNestedJSObjectArray() -> Void { #if arch(wasm32) - let ret = processNestedJSObjectArray(_: [[JSObject]].bridgeJSStackPop()) + let objects = [[JSObject]].bridgeJSStackPop() + let ret = processNestedJSObjectArray(_: objects) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -382,9 +409,9 @@ public func _bjs_processNestedJSObjectArray() -> Void { @_cdecl("bjs_multiArrayParams") public func _bjs_multiArrayParams() -> Int32 { #if arch(wasm32) - let _tmp_strs = [String].bridgeJSStackPop() - let _tmp_nums = [Int].bridgeJSStackPop() - let ret = multiArrayParams(nums: _tmp_nums, strs: _tmp_strs) + let strs = [String].bridgeJSStackPop() + let nums = [Int].bridgeJSStackPop() + let ret = multiArrayParams(nums: nums, strs: strs) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -395,9 +422,9 @@ public func _bjs_multiArrayParams() -> Int32 { @_cdecl("bjs_multiOptionalArrayParams") public func _bjs_multiOptionalArrayParams() -> Int32 { #if arch(wasm32) - let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() - let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() - let ret = multiOptionalArrayParams(a: _tmp_a, b: _tmp_b) + let b = Optional<[String]>.bridgeJSLiftParameter() + let a = Optional<[Int]>.bridgeJSLiftParameter() + let ret = multiOptionalArrayParams(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -439,9 +466,9 @@ fileprivate func _bjs_Item_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> In @_cdecl("bjs_MultiArrayContainer_init") public func _bjs_MultiArrayContainer_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let _tmp_strs = [String].bridgeJSStackPop() - let _tmp_nums = [Int].bridgeJSStackPop() - let ret = MultiArrayContainer(nums: _tmp_nums, strs: _tmp_strs) + let strs = [String].bridgeJSStackPop() + let nums = [Int].bridgeJSStackPop() + let ret = MultiArrayContainer(nums: nums, strs: strs) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -452,7 +479,8 @@ public func _bjs_MultiArrayContainer_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_MultiArrayContainer_numbers_get") public func _bjs_MultiArrayContainer_numbers_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MultiArrayContainer.bridgeJSLiftParameter(_self).numbers + let _self = MultiArrayContainer.bridgeJSLiftParameter(_self) + let ret = _self.numbers ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -463,7 +491,8 @@ public func _bjs_MultiArrayContainer_numbers_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_MultiArrayContainer_strings_get") public func _bjs_MultiArrayContainer_strings_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MultiArrayContainer.bridgeJSLiftParameter(_self).strings + let _self = MultiArrayContainer.bridgeJSLiftParameter(_self) + let ret = _self.strings ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 35618554c..ae03fc475 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -100,8 +100,9 @@ public func _bjs_asyncReturnVoid() -> Int32 { @_cdecl("bjs_asyncRoundTripInt") public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = Int.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { - return await asyncRoundTripInt(_: Int.bridgeJSLiftParameter(v)) + return await asyncRoundTripInt(_: v) } #else fatalError("Only available on WebAssembly") @@ -112,8 +113,9 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripString") public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = String.bridgeJSLiftParameter(vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { - return await asyncRoundTripString(_: String.bridgeJSLiftParameter(vBytes, vLength)) + return await asyncRoundTripString(_: v) } #else fatalError("Only available on WebAssembly") @@ -124,8 +126,9 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 @_cdecl("bjs_asyncRoundTripBool") public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = Bool.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { - return await asyncRoundTripBool(_: Bool.bridgeJSLiftParameter(v)) + return await asyncRoundTripBool(_: v) } #else fatalError("Only available on WebAssembly") @@ -136,8 +139,9 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripFloat") public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) + let v = Float.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { - return await asyncRoundTripFloat(_: Float.bridgeJSLiftParameter(v)) + return await asyncRoundTripFloat(_: v) } #else fatalError("Only available on WebAssembly") @@ -148,8 +152,9 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { @_cdecl("bjs_asyncRoundTripDouble") public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) + let v = Double.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { - return await asyncRoundTripDouble(_: Double.bridgeJSLiftParameter(v)) + return await asyncRoundTripDouble(_: v) } #else fatalError("Only available on WebAssembly") @@ -160,8 +165,9 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { @_cdecl("bjs_asyncRoundTripJSObject") public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = JSObject.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { - return await asyncRoundTripJSObject(_: JSObject.bridgeJSLiftParameter(v)) + return await asyncRoundTripJSObject(_: v) } #else fatalError("Only available on WebAssembly") @@ -172,9 +178,9 @@ public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripStruct") public func _bjs_asyncRoundTripStruct() -> Int32 { #if arch(wasm32) - let _tmp_v = AsyncPoint.bridgeJSLiftParameter() + let v = AsyncPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { - return await asyncRoundTripStruct(_: _tmp_v) + return await asyncRoundTripStruct(_: v) } #else fatalError("Only available on WebAssembly") @@ -185,9 +191,9 @@ public func _bjs_asyncRoundTripStruct() -> Int32 { @_cdecl("bjs_asyncRoundTripStructThrows") public func _bjs_asyncRoundTripStructThrows() -> Int32 { #if arch(wasm32) - let _tmp_v = AsyncPoint.bridgeJSLiftParameter() + let v = AsyncPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { () async throws(JSException) -> AsyncPoint in - return try await asyncRoundTripStructThrows(_: _tmp_v) + return try await asyncRoundTripStructThrows(_: v) } #else fatalError("Only available on WebAssembly") @@ -212,10 +218,10 @@ public func _bjs_asyncThrowsZeroArg() -> Int32 { @_cdecl("bjs_asyncCombineStructs") public func _bjs_asyncCombineStructs() -> Int32 { #if arch(wasm32) - let _tmp_b = AsyncPoint.bridgeJSLiftParameter() - let _tmp_a = AsyncPoint.bridgeJSLiftParameter() + let b = AsyncPoint.bridgeJSLiftParameter() + let a = AsyncPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { - return await asyncCombineStructs(_: _tmp_a, _: _tmp_b) + return await asyncCombineStructs(_: a, _: b) } #else fatalError("Only available on WebAssembly") @@ -226,8 +232,9 @@ public func _bjs_asyncCombineStructs() -> Int32 { @_cdecl("bjs_asyncRoundTripEnum") public func _bjs_asyncRoundTripEnum(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = AsyncDirection.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_14AsyncDirectionO, reject: Promise_reject) { - return await asyncRoundTripEnum(_: AsyncDirection.bridgeJSLiftParameter(v)) + return await asyncRoundTripEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -238,8 +245,9 @@ public func _bjs_asyncRoundTripEnum(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripRawEnum") public func _bjs_asyncRoundTripRawEnum(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = AsyncTheme.bridgeJSLiftParameter(vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_10AsyncThemeO, reject: Promise_reject) { - return await asyncRoundTripRawEnum(_: AsyncTheme.bridgeJSLiftParameter(vBytes, vLength)) + return await asyncRoundTripRawEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -250,8 +258,9 @@ public func _bjs_asyncRoundTripRawEnum(_ vBytes: Int32, _ vLength: Int32) -> Int @_cdecl("bjs_asyncRoundTripOptionalEnum") public func _bjs_asyncRoundTripOptionalEnum(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { #if arch(wasm32) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) return _bjs_makePromise(resolve: Promise_resolve_Sq14AsyncDirectionO, reject: Promise_reject) { - return await asyncRoundTripOptionalEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return await asyncRoundTripOptionalEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -262,8 +271,9 @@ public func _bjs_asyncRoundTripOptionalEnum(_ vIsSome: Int32, _ vValue: Int32) - @_cdecl("bjs_asyncRoundTripOptionalRawEnum") public func _bjs_asyncRoundTripOptionalRawEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_Sq10AsyncThemeO, reject: Promise_reject) { - return await asyncRoundTripOptionalRawEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) + return await asyncRoundTripOptionalRawEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -274,9 +284,9 @@ public func _bjs_asyncRoundTripOptionalRawEnum(_ vIsSome: Int32, _ vBytes: Int32 @_cdecl("bjs_asyncRoundTripOptionalStruct") public func _bjs_asyncRoundTripOptionalStruct() -> Int32 { #if arch(wasm32) - let _tmp_v = Optional.bridgeJSLiftParameter() + let v = Optional.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_Sq10AsyncPointV, reject: Promise_reject) { - return await asyncRoundTripOptionalStruct(_: _tmp_v) + return await asyncRoundTripOptionalStruct(_: v) } #else fatalError("Only available on WebAssembly") @@ -287,9 +297,9 @@ public func _bjs_asyncRoundTripOptionalStruct() -> Int32 { @_cdecl("bjs_asyncRoundTripStructArray") public func _bjs_asyncRoundTripStructArray() -> Int32 { #if arch(wasm32) - let _tmp_v = [AsyncPoint].bridgeJSStackPop() + let v = [AsyncPoint].bridgeJSStackPop() return _bjs_makePromise(resolve: Promise_resolve_Sa10AsyncPointV, reject: Promise_reject) { - return await asyncRoundTripStructArray(_: _tmp_v) + return await asyncRoundTripStructArray(_: v) } #else fatalError("Only available on WebAssembly") @@ -300,9 +310,9 @@ public func _bjs_asyncRoundTripStructArray() -> Int32 { @_cdecl("bjs_asyncRoundTripEnumArray") public func _bjs_asyncRoundTripEnumArray() -> Int32 { #if arch(wasm32) - let _tmp_v = [AsyncDirection].bridgeJSStackPop() + let v = [AsyncDirection].bridgeJSStackPop() return _bjs_makePromise(resolve: Promise_resolve_Sa14AsyncDirectionO, reject: Promise_reject) { - return await asyncRoundTripEnumArray(_: _tmp_v) + return await asyncRoundTripEnumArray(_: v) } #else fatalError("Only available on WebAssembly") @@ -313,9 +323,9 @@ public func _bjs_asyncRoundTripEnumArray() -> Int32 { @_cdecl("bjs_asyncRoundTripStructDictionary") public func _bjs_asyncRoundTripStructDictionary() -> Int32 { #if arch(wasm32) - let _tmp_v = [String: AsyncPoint].bridgeJSLiftParameter() + let v = [String: AsyncPoint].bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_SD10AsyncPointV, reject: Promise_reject) { - return await asyncRoundTripStructDictionary(_: _tmp_v) + return await asyncRoundTripStructDictionary(_: v) } #else fatalError("Only available on WebAssembly") @@ -326,9 +336,9 @@ public func _bjs_asyncRoundTripStructDictionary() -> Int32 { @_cdecl("bjs_asyncRoundTripEnumDictionary") public func _bjs_asyncRoundTripEnumDictionary() -> Int32 { #if arch(wasm32) - let _tmp_v = [String: AsyncDirection].bridgeJSLiftParameter() + let v = [String: AsyncDirection].bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_SD14AsyncDirectionO, reject: Promise_reject) { - return await asyncRoundTripEnumDictionary(_: _tmp_v) + return await asyncRoundTripEnumDictionary(_: v) } #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift index 6776998bc..3d6691c51 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -30,9 +30,9 @@ extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_asyncRoundTripAssociatedValueEnum") public func _bjs_asyncRoundTripAssociatedValueEnum(_ value: Int32) -> Int32 { #if arch(wasm32) - let _tmp_value = AsyncPayloadResult.bridgeJSLiftParameter(value) + let value = AsyncPayloadResult.bridgeJSLiftParameter(value) return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripAssociatedValueEnum(_: _tmp_value) + return await asyncRoundTripAssociatedValueEnum(_: value) } #else fatalError("Only available on WebAssembly") @@ -43,9 +43,9 @@ public func _bjs_asyncRoundTripAssociatedValueEnum(_ value: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { #if arch(wasm32) - let _tmp_value = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_value) + return await asyncRoundTripOptionalAssociatedValueEnum(_: value) } #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift index 9568a4426..509f79578 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift @@ -38,8 +38,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { } extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, body: body, fileID: fileID, @@ -52,8 +52,9 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { @_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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -99,8 +100,8 @@ private enum _BJS_Closure_10TestModules8JSObjectC_y { } extension JSTypedClosure where Signature == (sending JSObject) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSObject) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSObject) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules8JSObjectC_y, body: body, fileID: fileID, @@ -113,8 +114,9 @@ extension JSTypedClosure where Signature == (sending JSObject) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModules8JSObjectC_y") public func _invoke_swift_closure_TestModule_10TestModules8JSObjectC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = JSObject.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSObject) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSObject.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -161,8 +163,8 @@ private enum _BJS_Closure_10TestModulesSS_y { } extension JSTypedClosure where Signature == (sending String) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSS_y, body: body, fileID: fileID, @@ -175,8 +177,9 @@ extension JSTypedClosure where Signature == (sending String) -> Void { @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -222,8 +225,8 @@ private enum _BJS_Closure_10TestModulesSb_y { } extension JSTypedClosure where Signature == (sending Bool) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSb_y, body: body, fileID: fileID, @@ -236,8 +239,9 @@ extension JSTypedClosure where Signature == (sending Bool) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModulesSb_y") public func _invoke_swift_closure_TestModule_10TestModulesSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = Bool.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Bool.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -283,8 +287,8 @@ private enum _BJS_Closure_10TestModulesSd_y { } extension JSTypedClosure where Signature == (sending Double) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSd_y, body: body, fileID: fileID, @@ -297,8 +301,9 @@ extension JSTypedClosure where Signature == (sending Double) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModulesSd_y") public func _invoke_swift_closure_TestModule_10TestModulesSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Double.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -344,8 +349,8 @@ private enum _BJS_Closure_10TestModulesSi_y { } extension JSTypedClosure where Signature == (sending Int) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Int) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Int) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSi_y, body: body, fileID: fileID, @@ -358,8 +363,9 @@ extension JSTypedClosure where Signature == (sending Int) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModulesSi_y") public func _invoke_swift_closure_TestModule_10TestModulesSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Int.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -441,7 +447,7 @@ func _$asyncReturnVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in bjs_asyncReturnVoid(resolveRef, rejectRef) } @@ -461,9 +467,9 @@ fileprivate func bjs_asyncRoundTripInt_extern(_ resolveRef: Int32, _ rejectRef: func _$asyncRoundTripInt(_ v: Int) async throws(JSException) -> Int { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Int) -> Void>($0) + JSTypedClosure<(sending Int) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_asyncRoundTripInt(resolveRef, rejectRef, vValue) @@ -485,9 +491,9 @@ fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRe func _$asyncRoundTripString(_ v: String) async throws(JSException) -> String { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in v.bridgeJSWithLoweredParameter { (vBytes, vLength) in bjs_asyncRoundTripString(resolveRef, rejectRef, vBytes, vLength) @@ -510,9 +516,9 @@ fileprivate func bjs_asyncRoundTripBool_extern(_ resolveRef: Int32, _ rejectRef: func _$asyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Bool) -> Void>($0) + JSTypedClosure<(sending Bool) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_asyncRoundTripBool(resolveRef, rejectRef, vValue) @@ -534,9 +540,9 @@ fileprivate func bjs_asyncRoundTripDouble_extern(_ resolveRef: Int32, _ rejectRe func _$asyncRoundTripDouble(_ v: Double) async throws(JSException) -> Double { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Double) -> Void>($0) + JSTypedClosure<(sending Double) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_asyncRoundTripDouble(resolveRef, rejectRef, vValue) @@ -558,9 +564,9 @@ fileprivate func bjs_asyncRoundTripJSObject_extern(_ resolveRef: Int32, _ reject func _$asyncRoundTripJSObject(_ v: JSObject) async throws(JSException) -> JSObject { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending JSObject) -> Void>($0) + JSTypedClosure<(sending JSObject) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_asyncRoundTripJSObject(resolveRef, rejectRef, vValue) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift index 40b2a009e..4cc76ef28 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift @@ -38,8 +38,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { } extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, body: body, fileID: fileID, @@ -52,8 +52,9 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { @_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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -99,8 +100,8 @@ private enum _BJS_Closure_10TestModulesSd_y { } extension JSTypedClosure where Signature == (sending Double) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSd_y, body: body, fileID: fileID, @@ -113,8 +114,9 @@ extension JSTypedClosure where Signature == (sending Double) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModulesSd_y") public func _invoke_swift_closure_TestModule_10TestModulesSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Double.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -206,9 +208,9 @@ fileprivate func bjs_AsyncBox_asyncStaticVoid_static_extern(_ resolveRef: Int32, func _$AsyncBox_asyncStaticRoundTrip(_ v: Double) async throws(JSException) -> Double { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Double) -> Void>($0) + JSTypedClosure<(sending Double) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_AsyncBox_asyncStaticRoundTrip_static(resolveRef, rejectRef, vValue) @@ -220,7 +222,7 @@ func _$AsyncBox_asyncStaticVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in bjs_AsyncBox_asyncStaticVoid_static(resolveRef, rejectRef) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift index c9c291317..82930bdd7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -51,7 +51,8 @@ fileprivate func _bjs_struct_lift_Account_Credentials_extern() -> Int32 { @_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)) + let token = String.bridgeJSLiftParameter(tokenBytes, tokenLength) + let ret = Account.Credentials(token: token) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -84,7 +85,8 @@ public func _bjs_Account_Credentials_static_empty() -> Void { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Account(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -95,7 +97,8 @@ public func _bjs_Account_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Account_describe") public func _bjs_Account_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Account.bridgeJSLiftParameter(_self).describe() + let _self = Account.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -106,7 +109,8 @@ public func _bjs_Account_describe(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Account_name_get") public func _bjs_Account_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Account.bridgeJSLiftParameter(_self).name + let _self = Account.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -117,7 +121,9 @@ public func _bjs_Account_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Account.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -127,7 +133,8 @@ public func _bjs_Account_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes @_cdecl("bjs_Account_role_get") public func _bjs_Account_role_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Account.bridgeJSLiftParameter(_self).role + let _self = Account.bridgeJSLiftParameter(_self) + let ret = _self.role return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift index 521e8b595..66d7ee1db 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.swift @@ -2,7 +2,8 @@ @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_greetFormally") public func _bjs_Greeter_greetFormally(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetFormally() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greetFormally() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift index c8df6b29e..c3e715a55 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift @@ -48,7 +48,8 @@ fileprivate func _bjs_struct_lift_Archive_Record_extern() -> Int32 { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Archive.Record(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -59,7 +60,8 @@ public func _bjs_Archive_Record_init(_ labelBytes: Int32, _ labelLength: Int32) @_cdecl("bjs_Archive_Record_describeRecord") public func _bjs_Archive_Record_describeRecord() -> Void { #if arch(wasm32) - let ret = Archive.Record.bridgeJSLiftParameter().describeRecord() + let _self = Archive.Record.bridgeJSLiftParameter() + let ret = _self.describeRecord() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift index d12d48eef..16a94ecfb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_standaloneFunction") public func _bjs_standaloneFunction(_ b: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = standaloneFunction(b: FunctionB.bridgeJSLiftParameter(b)) + let b = FunctionB.bridgeJSLiftParameter(b) + let ret = standaloneFunction(b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +25,9 @@ public func _bjs_FunctionA_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_FunctionA_processB") public func _bjs_FunctionA_processB(_ _self: UnsafeMutableRawPointer, _ b: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = FunctionA.bridgeJSLiftParameter(_self).processB(b: FunctionB.bridgeJSLiftParameter(b)) + let b = FunctionB.bridgeJSLiftParameter(b) + let _self = FunctionA.bridgeJSLiftParameter(_self) + let ret = _self.processB(b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,9 @@ public func _bjs_FunctionA_processB(_ _self: UnsafeMutableRawPointer, _ b: Unsaf @_cdecl("bjs_FunctionA_createB") public func _bjs_FunctionA_createB(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = FunctionA.bridgeJSLiftParameter(_self).createB(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = FunctionA.bridgeJSLiftParameter(_self) + let ret = _self.createB(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -77,7 +82,8 @@ fileprivate func _bjs_FunctionA_wrap_extern(_ pointer: UnsafeMutableRawPointer) @_cdecl("bjs_FunctionB_init") public func _bjs_FunctionB_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = FunctionB(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = FunctionB(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -88,7 +94,8 @@ public func _bjs_FunctionB_init(_ valueBytes: Int32, _ valueLength: Int32) -> Un @_cdecl("bjs_FunctionB_value_get") public func _bjs_FunctionB_value_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = FunctionB.bridgeJSLiftParameter(_self).value + let _self = FunctionB.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -99,7 +106,9 @@ public func _bjs_FunctionB_value_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_FunctionB_value_set") public func _bjs_FunctionB_value_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - FunctionB.bridgeJSLiftParameter(_self).value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = FunctionB.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift index bf720af76..b2b7e36d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_standaloneFunction") public func _bjs_standaloneFunction(_ b: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = standaloneFunction(b: FunctionB.bridgeJSLiftParameter(b)) + let b = FunctionB.bridgeJSLiftParameter(b) + let ret = standaloneFunction(b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_standaloneFunction(_ b: UnsafeMutableRawPointer) -> UnsafeMutab @_cdecl("bjs_FunctionB_init") public func _bjs_FunctionB_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = FunctionB(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = FunctionB(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_FunctionB_init(_ valueBytes: Int32, _ valueLength: Int32) -> Un @_cdecl("bjs_FunctionB_value_get") public func _bjs_FunctionB_value_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = FunctionB.bridgeJSLiftParameter(_self).value + let _self = FunctionB.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,9 @@ public func _bjs_FunctionB_value_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_FunctionB_value_set") public func _bjs_FunctionB_value_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - FunctionB.bridgeJSLiftParameter(_self).value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = FunctionB.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -87,7 +92,9 @@ public func _bjs_FunctionA_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_FunctionA_processB") public func _bjs_FunctionA_processB(_ _self: UnsafeMutableRawPointer, _ b: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = FunctionA.bridgeJSLiftParameter(_self).processB(b: FunctionB.bridgeJSLiftParameter(b)) + let b = FunctionB.bridgeJSLiftParameter(b) + let _self = FunctionA.bridgeJSLiftParameter(_self) + let ret = _self.processB(b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -98,7 +105,9 @@ public func _bjs_FunctionA_processB(_ _self: UnsafeMutableRawPointer, _ b: Unsaf @_cdecl("bjs_FunctionA_createB") public func _bjs_FunctionA_createB(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = FunctionA.bridgeJSLiftParameter(_self).createB(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = FunctionA.bridgeJSLiftParameter(_self) + let ret = _self.createB(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift index 7601f0f72..d5d82b80b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift @@ -5,7 +5,8 @@ extension Workspace.Kind: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Workspace(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -16,7 +17,8 @@ public func _bjs_Workspace_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsa @_cdecl("bjs_Workspace_describe") public func _bjs_Workspace_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Workspace.bridgeJSLiftParameter(_self).describe() + let _self = Workspace.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift index 7c43c393f..73a745ab0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_ClassA_linkedB_get") public func _bjs_ClassA_linkedB_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClassA.bridgeJSLiftParameter(_self).linkedB + let _self = ClassA.bridgeJSLiftParameter(_self) + let ret = _self.linkedB return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,9 @@ public func _bjs_ClassA_linkedB_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_ClassA_linkedB_set") public func _bjs_ClassA_linkedB_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassA.bridgeJSLiftParameter(_self).linkedB = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = ClassA.bridgeJSLiftParameter(_self) + _self.linkedB = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift index c381c7cab..e0443c55f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift @@ -44,7 +44,8 @@ fileprivate func _bjs_ClassB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> @_cdecl("bjs_ClassA_linkedB_get") public func _bjs_ClassA_linkedB_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClassA.bridgeJSLiftParameter(_self).linkedB + let _self = ClassA.bridgeJSLiftParameter(_self) + let ret = _self.linkedB return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -55,7 +56,9 @@ public func _bjs_ClassA_linkedB_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_ClassA_linkedB_set") public func _bjs_ClassA_linkedB_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ClassA.bridgeJSLiftParameter(_self).linkedB = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = ClassA.bridgeJSLiftParameter(_self) + _self.linkedB = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index e2e74e532..5ed3dc80d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -137,7 +137,8 @@ fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { @_cdecl("bjs_MathOperations_init") public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { #if arch(wasm32) - let ret = MathOperations(baseValue: Double.bridgeJSLiftParameter(baseValue)) + let baseValue = Double.bridgeJSLiftParameter(baseValue) + let ret = MathOperations(baseValue: baseValue) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -148,7 +149,10 @@ public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let _self = MathOperations.bridgeJSLiftParameter() + let ret = _self.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -159,7 +163,10 @@ public func _bjs_MathOperations_add(_ a: Float64, _ b: Float64) -> Float64 { @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let _self = MathOperations.bridgeJSLiftParameter() + let ret = _self.multiply(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -170,7 +177,9 @@ public func _bjs_MathOperations_multiply(_ a: Float64, _ b: Float64) -> Float64 @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let ret = MathOperations.subtract(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -181,7 +190,8 @@ public func _bjs_MathOperations_static_subtract(_ a: Float64, _ b: Float64) -> F @_cdecl("bjs_testStringDefault") public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let ret = testStringDefault(message: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -192,7 +202,8 @@ public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32 @_cdecl("bjs_testNegativeIntDefault") public func _bjs_testNegativeIntDefault(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = testNegativeIntDefault(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = testNegativeIntDefault(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -203,7 +214,8 @@ public func _bjs_testNegativeIntDefault(_ value: Int32) -> Int32 { @_cdecl("bjs_testBoolDefault") public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { #if arch(wasm32) - let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) + let flag = Bool.bridgeJSLiftParameter(flag) + let ret = testBoolDefault(flag: flag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -214,7 +226,8 @@ public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { @_cdecl("bjs_testNegativeFloatDefault") public func _bjs_testNegativeFloatDefault(_ temp: Float32) -> Float32 { #if arch(wasm32) - let ret = testNegativeFloatDefault(temp: Float.bridgeJSLiftParameter(temp)) + let temp = Float.bridgeJSLiftParameter(temp) + let ret = testNegativeFloatDefault(temp: temp) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -225,7 +238,8 @@ public func _bjs_testNegativeFloatDefault(_ temp: Float32) -> Float32 { @_cdecl("bjs_testDoubleDefault") public func _bjs_testDoubleDefault(_ precision: Float64) -> Float64 { #if arch(wasm32) - let ret = testDoubleDefault(precision: Double.bridgeJSLiftParameter(precision)) + let precision = Double.bridgeJSLiftParameter(precision) + let ret = testDoubleDefault(precision: precision) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -236,7 +250,8 @@ public func _bjs_testDoubleDefault(_ precision: Float64) -> Float64 { @_cdecl("bjs_testOptionalDefault") public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = testOptionalDefault(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -247,7 +262,8 @@ public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ @_cdecl("bjs_testOptionalStringDefault") public func _bjs_testOptionalStringDefault(_ greetingIsSome: Int32, _ greetingBytes: Int32, _ greetingLength: Int32) -> Void { #if arch(wasm32) - let ret = testOptionalStringDefault(greeting: Optional.bridgeJSLiftParameter(greetingIsSome, greetingBytes, greetingLength)) + let greeting = Optional.bridgeJSLiftParameter(greetingIsSome, greetingBytes, greetingLength) + let ret = testOptionalStringDefault(greeting: greeting) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -258,7 +274,10 @@ public func _bjs_testOptionalStringDefault(_ greetingIsSome: Int32, _ greetingBy @_cdecl("bjs_testMultipleDefaults") public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let count = Int.bridgeJSLiftParameter(count) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let ret = testMultipleDefaults(title: title, count: count, enabled: enabled) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -269,7 +288,8 @@ public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, @_cdecl("bjs_testEnumDefault") public func _bjs_testEnumDefault(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = testEnumDefault(status: Status.bridgeJSLiftParameter(status)) + let status = Status.bridgeJSLiftParameter(status) + let ret = testEnumDefault(status: status) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -280,7 +300,8 @@ public func _bjs_testEnumDefault(_ status: Int32) -> Int32 { @_cdecl("bjs_testComplexInit") public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testComplexInit(greeter: DefaultGreeter.bridgeJSLiftParameter(greeter)) + let greeter = DefaultGreeter.bridgeJSLiftParameter(greeter) + let ret = testComplexInit(greeter: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -291,7 +312,8 @@ public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> UnsafeMu @_cdecl("bjs_testEmptyInit") public func _bjs_testEmptyInit(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testEmptyInit(greeter: EmptyGreeter.bridgeJSLiftParameter(greeter)) + let greeter = EmptyGreeter.bridgeJSLiftParameter(greeter) + let ret = testEmptyInit(greeter: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -302,7 +324,8 @@ public func _bjs_testEmptyInit(_ greeter: UnsafeMutableRawPointer) -> UnsafeMuta @_cdecl("bjs_testOptionalStructDefault") public func _bjs_testOptionalStructDefault() -> Void { #if arch(wasm32) - let ret = testOptionalStructDefault(point: Optional.bridgeJSLiftParameter()) + let point = Optional.bridgeJSLiftParameter() + let ret = testOptionalStructDefault(point: point) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -313,7 +336,8 @@ public func _bjs_testOptionalStructDefault() -> Void { @_cdecl("bjs_testOptionalStructWithValueDefault") public func _bjs_testOptionalStructWithValueDefault() -> Void { #if arch(wasm32) - let ret = testOptionalStructWithValueDefault(point: Optional.bridgeJSLiftParameter()) + let point = Optional.bridgeJSLiftParameter() + let ret = testOptionalStructWithValueDefault(point: point) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -324,7 +348,8 @@ public func _bjs_testOptionalStructWithValueDefault() -> Void { @_cdecl("bjs_testIntArrayDefault") public func _bjs_testIntArrayDefault() -> Void { #if arch(wasm32) - let ret = testIntArrayDefault(values: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let ret = testIntArrayDefault(values: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -335,7 +360,8 @@ public func _bjs_testIntArrayDefault() -> Void { @_cdecl("bjs_testStringArrayDefault") public func _bjs_testStringArrayDefault() -> Void { #if arch(wasm32) - let ret = testStringArrayDefault(names: [String].bridgeJSStackPop()) + let names = [String].bridgeJSStackPop() + let ret = testStringArrayDefault(names: names) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -346,7 +372,8 @@ public func _bjs_testStringArrayDefault() -> Void { @_cdecl("bjs_testDoubleArrayDefault") public func _bjs_testDoubleArrayDefault() -> Void { #if arch(wasm32) - let ret = testDoubleArrayDefault(values: [Double].bridgeJSStackPop()) + let values = [Double].bridgeJSStackPop() + let ret = testDoubleArrayDefault(values: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -357,7 +384,8 @@ public func _bjs_testDoubleArrayDefault() -> Void { @_cdecl("bjs_testBoolArrayDefault") public func _bjs_testBoolArrayDefault() -> Void { #if arch(wasm32) - let ret = testBoolArrayDefault(flags: [Bool].bridgeJSStackPop()) + let flags = [Bool].bridgeJSStackPop() + let ret = testBoolArrayDefault(flags: flags) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -368,7 +396,8 @@ public func _bjs_testBoolArrayDefault() -> Void { @_cdecl("bjs_testEmptyArrayDefault") public func _bjs_testEmptyArrayDefault() -> Void { #if arch(wasm32) - let ret = testEmptyArrayDefault(items: [Int].bridgeJSStackPop()) + let items = [Int].bridgeJSStackPop() + let ret = testEmptyArrayDefault(items: items) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -379,7 +408,10 @@ public func _bjs_testEmptyArrayDefault() -> Void { @_cdecl("bjs_testMixedWithArrayDefault") public func _bjs_testMixedWithArrayDefault(_ nameBytes: Int32, _ nameLength: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = testMixedWithArrayDefault(name: String.bridgeJSLiftParameter(nameBytes, nameLength), values: [Int].bridgeJSStackPop(), enabled: Bool.bridgeJSLiftParameter(enabled)) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let values = [Int].bridgeJSStackPop() + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = testMixedWithArrayDefault(name: name, values: values, enabled: enabled) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -390,7 +422,8 @@ public func _bjs_testMixedWithArrayDefault(_ nameBytes: Int32, _ nameLength: Int @_cdecl("bjs_DefaultGreeter_init") public func _bjs_DefaultGreeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DefaultGreeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = DefaultGreeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -401,7 +434,8 @@ public func _bjs_DefaultGreeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> @_cdecl("bjs_DefaultGreeter_name_get") public func _bjs_DefaultGreeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultGreeter.bridgeJSLiftParameter(_self).name + let _self = DefaultGreeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -412,7 +446,9 @@ public func _bjs_DefaultGreeter_name_get(_ _self: UnsafeMutableRawPointer) -> Vo @_cdecl("bjs_DefaultGreeter_name_set") public func _bjs_DefaultGreeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - DefaultGreeter.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = DefaultGreeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -495,7 +531,12 @@ fileprivate func _bjs_EmptyGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointe @_cdecl("bjs_ConstructorDefaults_init") public func _bjs_ConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ConstructorDefaults(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled), status: Status.bridgeJSLiftParameter(status), tag: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + let tag = Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength) + let status = Status.bridgeJSLiftParameter(status) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let count = Int.bridgeJSLiftParameter(count) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = ConstructorDefaults(name: name, count: count, enabled: enabled, status: status, tag: tag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -506,7 +547,8 @@ public func _bjs_ConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int3 @_cdecl("bjs_ConstructorDefaults_name_get") public func _bjs_ConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).name + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -517,7 +559,9 @@ public func _bjs_ConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ConstructorDefaults_name_set") public func _bjs_ConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -527,7 +571,8 @@ public func _bjs_ConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_ConstructorDefaults_count_get") public func _bjs_ConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).count + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -538,7 +583,9 @@ public func _bjs_ConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ConstructorDefaults_count_set") public func _bjs_ConstructorDefaults_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif @@ -548,7 +595,8 @@ public func _bjs_ConstructorDefaults_count_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_ConstructorDefaults_enabled_get") public func _bjs_ConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).enabled + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.enabled return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -559,7 +607,9 @@ public func _bjs_ConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_ConstructorDefaults_enabled_set") public func _bjs_ConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + _self.enabled = value #else fatalError("Only available on WebAssembly") #endif @@ -569,7 +619,8 @@ public func _bjs_ConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_ConstructorDefaults_status_get") public func _bjs_ConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).status + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.status return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -580,7 +631,9 @@ public func _bjs_ConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ConstructorDefaults_status_set") public func _bjs_ConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) + let value = Status.bridgeJSLiftParameter(value) + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + _self.status = value #else fatalError("Only available on WebAssembly") #endif @@ -590,7 +643,8 @@ public func _bjs_ConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ConstructorDefaults_tag_get") public func _bjs_ConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ConstructorDefaults.bridgeJSLiftParameter(_self).tag + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -601,7 +655,9 @@ public func _bjs_ConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_ConstructorDefaults_tag_set") public func _bjs_ConstructorDefaults_tag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - ConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = ConstructorDefaults.bridgeJSLiftParameter(_self) + _self.tag = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index 2990eeabe..0f1dfe88a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -56,7 +56,8 @@ fileprivate func _bjs_struct_lift_Counters_extern() -> Int32 { @_cdecl("bjs_mirrorDictionary") public func _bjs_mirrorDictionary() -> Void { #if arch(wasm32) - let ret = mirrorDictionary(_: [String: Int].bridgeJSLiftParameter()) + let values = [String: Int].bridgeJSLiftParameter() + let ret = mirrorDictionary(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -67,7 +68,8 @@ public func _bjs_mirrorDictionary() -> Void { @_cdecl("bjs_optionalDictionary") public func _bjs_optionalDictionary() -> Void { #if arch(wasm32) - let ret = optionalDictionary(_: Optional<[String: String]>.bridgeJSLiftParameter()) + let values = Optional<[String: String]>.bridgeJSLiftParameter() + let ret = optionalDictionary(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -78,7 +80,8 @@ public func _bjs_optionalDictionary() -> Void { @_cdecl("bjs_nestedDictionary") public func _bjs_nestedDictionary() -> Void { #if arch(wasm32) - let ret = nestedDictionary(_: [String: [Int]].bridgeJSLiftParameter()) + let values = [String: [Int]].bridgeJSLiftParameter() + let ret = nestedDictionary(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -89,7 +92,8 @@ public func _bjs_nestedDictionary() -> Void { @_cdecl("bjs_boxDictionary") public func _bjs_boxDictionary() -> Void { #if arch(wasm32) - let ret = boxDictionary(_: [String: Box].bridgeJSLiftParameter()) + let boxes = [String: Box].bridgeJSLiftParameter() + let ret = boxDictionary(_: boxes) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -100,7 +104,8 @@ public func _bjs_boxDictionary() -> Void { @_cdecl("bjs_optionalBoxDictionary") public func _bjs_optionalBoxDictionary() -> Void { #if arch(wasm32) - let ret = optionalBoxDictionary(_: [String: Optional].bridgeJSLiftParameter()) + let boxes = [String: Optional].bridgeJSLiftParameter() + let ret = optionalBoxDictionary(_: boxes) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -111,7 +116,8 @@ public func _bjs_optionalBoxDictionary() -> Void { @_cdecl("bjs_roundtripCounters") public func _bjs_roundtripCounters() -> Void { #if arch(wasm32) - let ret = roundtripCounters(_: Counters.bridgeJSLiftParameter()) + let counters = Counters.bridgeJSLiftParameter() + let ret = roundtripCounters(_: counters) return ret.bridgeJSLowerReturn() #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 fab694b18..b9c65e28f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -87,7 +87,8 @@ extension Color: _BridgedSwiftCaseEnum { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Color.canonical(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -157,7 +158,9 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { @_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)) + let greeting = String.bridgeJSLiftParameter(greetingBytes, greetingLength) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = greet(name: name, greeting: greeting) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -168,7 +171,9 @@ public func _bjs_greet(_ nameBytes: Int32, _ nameLength: Int32, _ greetingBytes: @_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)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -199,8 +204,9 @@ public func _bjs_hello() -> Void { @_cdecl("bjs_parseInt") public func _bjs_parseInt(_ textBytes: Int32, _ textLength: Int32) -> Int32 { #if arch(wasm32) + let text = String.bridgeJSLiftParameter(textBytes, textLength) do { - let ret = try parseInt(text: String.bridgeJSLiftParameter(textBytes, textLength)) + let ret = try parseInt(text: text) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -224,7 +230,8 @@ public func _bjs_parseInt(_ textBytes: Int32, _ textLength: Int32) -> Int32 { @_cdecl("bjs_MathUtils_double") public func _bjs_MathUtils_double(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = double(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = double(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -246,7 +253,8 @@ public func _bjs_terminator() -> Void { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -257,7 +265,8 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -268,7 +277,8 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_name_get") public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -279,7 +289,9 @@ public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift index 5689b143f..8f003b1be 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_roundtripColor") public func _bjs_roundtripColor(_ color: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundtripColor(_: Color.bridgeJSLiftParameter(color)) + let color = Color.bridgeJSLiftParameter(color) + let ret = roundtripColor(_: color) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_roundtripColor(_ color: UnsafeMutableRawPointer) -> UnsafeMutab @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = ColorBox(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 4ca3236f8..b3ce78701 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -408,7 +408,8 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { @_cdecl("bjs_handle") public func _bjs_handle(_ result: Int32) -> Void { #if arch(wasm32) - handle(result: APIResult.bridgeJSLiftParameter(result)) + let result = APIResult.bridgeJSLiftParameter(result) + handle(result: result) #else fatalError("Only available on WebAssembly") #endif @@ -429,7 +430,8 @@ public func _bjs_getResult() -> Void { @_cdecl("bjs_roundtripAPIResult") public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) + let result = APIResult.bridgeJSLiftParameter(result) + let ret = roundtripAPIResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -440,7 +442,8 @@ public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripOptionalAPIResult") public func _bjs_roundTripOptionalAPIResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalAPIResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalAPIResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -451,7 +454,8 @@ public func _bjs_roundTripOptionalAPIResult(_ resultIsSome: Int32, _ resultCaseI @_cdecl("bjs_handleComplex") public func _bjs_handleComplex(_ result: Int32) -> Void { #if arch(wasm32) - handleComplex(result: ComplexResult.bridgeJSLiftParameter(result)) + let result = ComplexResult.bridgeJSLiftParameter(result) + handleComplex(result: result) #else fatalError("Only available on WebAssembly") #endif @@ -472,7 +476,8 @@ public func _bjs_getComplexResult() -> Void { @_cdecl("bjs_roundtripComplexResult") public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) + let result = ComplexResult.bridgeJSLiftParameter(result) + let ret = roundtripComplexResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -483,7 +488,8 @@ public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripOptionalComplexResult") public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalComplexResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalComplexResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -494,7 +500,8 @@ public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultC @_cdecl("bjs_roundTripOptionalUtilitiesResult") public func _bjs_roundTripOptionalUtilitiesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalUtilitiesResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalUtilitiesResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -505,7 +512,8 @@ public func _bjs_roundTripOptionalUtilitiesResult(_ resultIsSome: Int32, _ resul @_cdecl("bjs_roundTripOptionalNetworkingResult") public func _bjs_roundTripOptionalNetworkingResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalNetworkingResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalNetworkingResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -516,7 +524,8 @@ public func _bjs_roundTripOptionalNetworkingResult(_ resultIsSome: Int32, _ resu @_cdecl("bjs_roundTripOptionalAPIOptionalResult") public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalAPIOptionalResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -527,9 +536,9 @@ public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ res @_cdecl("bjs_compareAPIResults") public func _bjs_compareAPIResults(_ result1IsSome: Int32, _ result1CaseId: Int32, _ result2IsSome: Int32, _ result2CaseId: Int32) -> Void { #if arch(wasm32) - let _tmp_result2 = Optional.bridgeJSLiftParameter(result2IsSome, result2CaseId) - let _tmp_result1 = Optional.bridgeJSLiftParameter(result1IsSome, result1CaseId) - let ret = compareAPIResults(result1: _tmp_result1, result2: _tmp_result2) + let result2 = Optional.bridgeJSLiftParameter(result2IsSome, result2CaseId) + let result1 = Optional.bridgeJSLiftParameter(result1IsSome, result1CaseId) + let ret = compareAPIResults(result1: result1, result2: result2) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -540,7 +549,8 @@ public func _bjs_compareAPIResults(_ result1IsSome: Int32, _ result1CaseId: Int3 @_cdecl("bjs_roundTripTypedPayloadResult") public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + let result = TypedPayloadResult.bridgeJSLiftParameter(result) + let ret = roundTripTypedPayloadResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -551,7 +561,8 @@ public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripOptionalTypedPayloadResult") public func _bjs_roundTripOptionalTypedPayloadResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalTypedPayloadResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -562,7 +573,8 @@ public func _bjs_roundTripOptionalTypedPayloadResult(_ resultIsSome: Int32, _ re @_cdecl("bjs_roundTripAllTypesResult") public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + let result = AllTypesResult.bridgeJSLiftParameter(result) + let ret = roundTripAllTypesResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -573,7 +585,8 @@ public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripOptionalAllTypesResult") public func _bjs_roundTripOptionalAllTypesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalAllTypesResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -584,7 +597,8 @@ public func _bjs_roundTripOptionalAllTypesResult(_ resultIsSome: Int32, _ result @_cdecl("bjs_roundTripOptionalPayloadResult") public func _bjs_roundTripOptionalPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(result)) + let result = OptionalAllTypesResult.bridgeJSLiftParameter(result) + let ret = roundTripOptionalPayloadResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -595,7 +609,8 @@ public func _bjs_roundTripOptionalPayloadResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripOptionalPayloadResultOpt") public func _bjs_roundTripOptionalPayloadResultOpt(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let ret = roundTripOptionalPayloadResultOpt(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift index dab981312..4b312204d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift @@ -158,7 +158,8 @@ extension PublicStatus: _BridgedSwiftCaseEnum { @_cdecl("bjs_setDirection") public func _bjs_setDirection(_ direction: Int32) -> Void { #if arch(wasm32) - setDirection(_: Direction.bridgeJSLiftParameter(direction)) + let direction = Direction.bridgeJSLiftParameter(direction) + setDirection(_: direction) #else fatalError("Only available on WebAssembly") #endif @@ -179,7 +180,8 @@ public func _bjs_getDirection() -> Int32 { @_cdecl("bjs_processDirection") public func _bjs_processDirection(_ input: Int32) -> Int32 { #if arch(wasm32) - let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) + let input = Direction.bridgeJSLiftParameter(input) + let ret = processDirection(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -190,7 +192,8 @@ public func _bjs_processDirection(_ input: Int32) -> Int32 { @_cdecl("bjs_roundTripOptionalDirection") public func _bjs_roundTripOptionalDirection(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalDirection(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalDirection(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -201,7 +204,8 @@ public func _bjs_roundTripOptionalDirection(_ inputIsSome: Int32, _ inputValue: @_cdecl("bjs_setTSDirection") public func _bjs_setTSDirection(_ direction: Int32) -> Void { #if arch(wasm32) - setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) + let direction = TSDirection.bridgeJSLiftParameter(direction) + setTSDirection(_: direction) #else fatalError("Only available on WebAssembly") #endif @@ -222,7 +226,8 @@ public func _bjs_getTSDirection() -> Int32 { @_cdecl("bjs_roundTripOptionalTSDirection") public func _bjs_roundTripOptionalTSDirection(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTSDirection(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalTSDirection(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 9d6908bcc..659b5306a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -86,7 +86,8 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @_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)) + let rootId = Int.bridgeJSLiftParameter(rootId) + let ret = GraphOperations.createGraph(rootId: rootId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -97,7 +98,8 @@ public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int @_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)) + let graphId = Int.bridgeJSLiftParameter(graphId) + let ret = GraphOperations.nodeCount(graphId: graphId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -108,8 +110,9 @@ public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int3 @_cdecl("bjs_Services_Graph_GraphOperations_static_validate") public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32) -> Int32 { #if arch(wasm32) + let graphId = Int.bridgeJSLiftParameter(graphId) do { - let ret = try GraphOperations.validate(graphId: Int.bridgeJSLiftParameter(graphId)) + let ret = try GraphOperations.validate(graphId: graphId) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -144,7 +147,9 @@ public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Utils_Converter_toString") public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -155,7 +160,8 @@ public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ va @_cdecl("bjs_Utils_Converter_precision_get") public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.precision return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -166,7 +172,9 @@ public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_Utils_Converter_precision_set") public func _bjs_Utils_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + _self.precision = value #else fatalError("Only available on WebAssembly") #endif @@ -218,7 +226,9 @@ public func _bjs_Networking_API_HTTPServer_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Networking_API_HTTPServer_call") public func _bjs_Networking_API_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) + let method = Networking.API.Method.bridgeJSLiftParameter(method) + let _self = Networking.API.HTTPServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -270,7 +280,9 @@ public func _bjs_Networking_APIV2_Internal_TestServer_init() -> UnsafeMutableRaw @_cdecl("bjs_Networking_APIV2_Internal_TestServer_call") public func _bjs_Networking_APIV2_Internal_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) + let method = Internal.SupportedMethod.bridgeJSLiftParameter(method) + let _self = Internal.TestServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -322,7 +334,9 @@ public func _bjs_Formatting_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Formatting_Converter_format") public func _bjs_Formatting_Converter_format(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Formatting.Converter.bridgeJSLiftParameter(_self).format(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Formatting.Converter.bridgeJSLiftParameter(_self) + let ret = _self.format(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 9d6908bcc..659b5306a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -86,7 +86,8 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @_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)) + let rootId = Int.bridgeJSLiftParameter(rootId) + let ret = GraphOperations.createGraph(rootId: rootId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -97,7 +98,8 @@ public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int @_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)) + let graphId = Int.bridgeJSLiftParameter(graphId) + let ret = GraphOperations.nodeCount(graphId: graphId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -108,8 +110,9 @@ public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int3 @_cdecl("bjs_Services_Graph_GraphOperations_static_validate") public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32) -> Int32 { #if arch(wasm32) + let graphId = Int.bridgeJSLiftParameter(graphId) do { - let ret = try GraphOperations.validate(graphId: Int.bridgeJSLiftParameter(graphId)) + let ret = try GraphOperations.validate(graphId: graphId) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -144,7 +147,9 @@ public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Utils_Converter_toString") public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -155,7 +160,8 @@ public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ va @_cdecl("bjs_Utils_Converter_precision_get") public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.precision return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -166,7 +172,9 @@ public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_Utils_Converter_precision_set") public func _bjs_Utils_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + _self.precision = value #else fatalError("Only available on WebAssembly") #endif @@ -218,7 +226,9 @@ public func _bjs_Networking_API_HTTPServer_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Networking_API_HTTPServer_call") public func _bjs_Networking_API_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) + let method = Networking.API.Method.bridgeJSLiftParameter(method) + let _self = Networking.API.HTTPServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -270,7 +280,9 @@ public func _bjs_Networking_APIV2_Internal_TestServer_init() -> UnsafeMutableRaw @_cdecl("bjs_Networking_APIV2_Internal_TestServer_call") public func _bjs_Networking_APIV2_Internal_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) + let method = Internal.SupportedMethod.bridgeJSLiftParameter(method) + let _self = Internal.TestServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -322,7 +334,9 @@ public func _bjs_Formatting_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Formatting_Converter_format") public func _bjs_Formatting_Converter_format(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Formatting.Converter.bridgeJSLiftParameter(_self).format(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Formatting.Converter.bridgeJSLiftParameter(_self) + let ret = _self.format(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index 2dbb21422..2cee26721 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -38,7 +38,8 @@ extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { @_cdecl("bjs_setTheme") public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = Theme.bridgeJSLiftParameter(themeBytes, themeLength) + setTheme(_: theme) #else fatalError("Only available on WebAssembly") #endif @@ -59,7 +60,8 @@ public func _bjs_getTheme() -> Void { @_cdecl("bjs_roundTripOptionalTheme") public func _bjs_roundTripOptionalTheme(_ inputIsSome: Int32, _ inputBytes: Int32, _ inputLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTheme(_: Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength) + let ret = roundTripOptionalTheme(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -70,7 +72,8 @@ public func _bjs_roundTripOptionalTheme(_ inputIsSome: Int32, _ inputBytes: Int3 @_cdecl("bjs_setTSTheme") public func _bjs_setTSTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = TSTheme.bridgeJSLiftParameter(themeBytes, themeLength) + setTSTheme(_: theme) #else fatalError("Only available on WebAssembly") #endif @@ -91,7 +94,8 @@ public func _bjs_getTSTheme() -> Void { @_cdecl("bjs_roundTripOptionalTSTheme") public func _bjs_roundTripOptionalTSTheme(_ inputIsSome: Int32, _ inputBytes: Int32, _ inputLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTSTheme(_: Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength) + let ret = roundTripOptionalTSTheme(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -102,7 +106,8 @@ public func _bjs_roundTripOptionalTSTheme(_ inputIsSome: Int32, _ inputBytes: In @_cdecl("bjs_setFeatureFlag") public func _bjs_setFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Void { #if arch(wasm32) - setFeatureFlag(_: FeatureFlag.bridgeJSLiftParameter(flagBytes, flagLength)) + let flag = FeatureFlag.bridgeJSLiftParameter(flagBytes, flagLength) + setFeatureFlag(_: flag) #else fatalError("Only available on WebAssembly") #endif @@ -123,7 +128,8 @@ public func _bjs_getFeatureFlag() -> Void { @_cdecl("bjs_roundTripOptionalFeatureFlag") public func _bjs_roundTripOptionalFeatureFlag(_ inputIsSome: Int32, _ inputBytes: Int32, _ inputLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalFeatureFlag(_: Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength) + let ret = roundTripOptionalFeatureFlag(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -134,7 +140,8 @@ public func _bjs_roundTripOptionalFeatureFlag(_ inputIsSome: Int32, _ inputBytes @_cdecl("bjs_setHttpStatus") public func _bjs_setHttpStatus(_ status: Int32) -> Void { #if arch(wasm32) - setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) + let status = HttpStatus.bridgeJSLiftParameter(status) + setHttpStatus(_: status) #else fatalError("Only available on WebAssembly") #endif @@ -155,7 +162,8 @@ public func _bjs_getHttpStatus() -> Int32 { @_cdecl("bjs_roundTripOptionalHttpStatus") public func _bjs_roundTripOptionalHttpStatus(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalHttpStatus(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalHttpStatus(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -166,7 +174,8 @@ public func _bjs_roundTripOptionalHttpStatus(_ inputIsSome: Int32, _ inputValue: @_cdecl("bjs_setTSHttpStatus") public func _bjs_setTSHttpStatus(_ status: Int32) -> Void { #if arch(wasm32) - setTSHttpStatus(_: TSHttpStatus.bridgeJSLiftParameter(status)) + let status = TSHttpStatus.bridgeJSLiftParameter(status) + setTSHttpStatus(_: status) #else fatalError("Only available on WebAssembly") #endif @@ -187,7 +196,8 @@ public func _bjs_getTSHttpStatus() -> Int32 { @_cdecl("bjs_roundTripOptionalHttpStatus") public func _bjs_roundTripOptionalHttpStatus(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalHttpStatus(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalHttpStatus(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -198,7 +208,8 @@ public func _bjs_roundTripOptionalHttpStatus(_ inputIsSome: Int32, _ inputValue: @_cdecl("bjs_setPriority") public func _bjs_setPriority(_ priority: Int32) -> Void { #if arch(wasm32) - setPriority(_: Priority.bridgeJSLiftParameter(priority)) + let priority = Priority.bridgeJSLiftParameter(priority) + setPriority(_: priority) #else fatalError("Only available on WebAssembly") #endif @@ -219,7 +230,8 @@ public func _bjs_getPriority() -> Int32 { @_cdecl("bjs_roundTripOptionalPriority") public func _bjs_roundTripOptionalPriority(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalPriority(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalPriority(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -230,7 +242,8 @@ public func _bjs_roundTripOptionalPriority(_ inputIsSome: Int32, _ inputValue: I @_cdecl("bjs_setFileSize") public func _bjs_setFileSize(_ size: Int64) -> Void { #if arch(wasm32) - setFileSize(_: FileSize.bridgeJSLiftParameter(size)) + let size = FileSize.bridgeJSLiftParameter(size) + setFileSize(_: size) #else fatalError("Only available on WebAssembly") #endif @@ -251,7 +264,8 @@ public func _bjs_getFileSize() -> Int64 { @_cdecl("bjs_roundTripOptionalFileSize") public func _bjs_roundTripOptionalFileSize(_ inputIsSome: Int32, _ inputValue: Int64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalFileSize(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -262,7 +276,8 @@ public func _bjs_roundTripOptionalFileSize(_ inputIsSome: Int32, _ inputValue: I @_cdecl("bjs_setUserId") public func _bjs_setUserId(_ id: Int32) -> Void { #if arch(wasm32) - setUserId(_: UserId.bridgeJSLiftParameter(id)) + let id = UserId.bridgeJSLiftParameter(id) + setUserId(_: id) #else fatalError("Only available on WebAssembly") #endif @@ -283,7 +298,8 @@ public func _bjs_getUserId() -> Int32 { @_cdecl("bjs_roundTripOptionalUserId") public func _bjs_roundTripOptionalUserId(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalUserId(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalUserId(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -294,7 +310,8 @@ public func _bjs_roundTripOptionalUserId(_ inputIsSome: Int32, _ inputValue: Int @_cdecl("bjs_setTokenId") public func _bjs_setTokenId(_ token: Int32) -> Void { #if arch(wasm32) - setTokenId(_: TokenId.bridgeJSLiftParameter(token)) + let token = TokenId.bridgeJSLiftParameter(token) + setTokenId(_: token) #else fatalError("Only available on WebAssembly") #endif @@ -315,7 +332,8 @@ public func _bjs_getTokenId() -> Int32 { @_cdecl("bjs_roundTripOptionalTokenId") public func _bjs_roundTripOptionalTokenId(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTokenId(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalTokenId(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -326,7 +344,8 @@ public func _bjs_roundTripOptionalTokenId(_ inputIsSome: Int32, _ inputValue: In @_cdecl("bjs_setSessionId") public func _bjs_setSessionId(_ session: Int64) -> Void { #if arch(wasm32) - setSessionId(_: SessionId.bridgeJSLiftParameter(session)) + let session = SessionId.bridgeJSLiftParameter(session) + setSessionId(_: session) #else fatalError("Only available on WebAssembly") #endif @@ -347,7 +366,8 @@ public func _bjs_getSessionId() -> Int64 { @_cdecl("bjs_roundTripOptionalSessionId") public func _bjs_roundTripOptionalSessionId(_ inputIsSome: Int32, _ inputValue: Int64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalSessionId(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalSessionId(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -358,7 +378,8 @@ public func _bjs_roundTripOptionalSessionId(_ inputIsSome: Int32, _ inputValue: @_cdecl("bjs_setPrecision") public func _bjs_setPrecision(_ precision: Float32) -> Void { #if arch(wasm32) - setPrecision(_: Precision.bridgeJSLiftParameter(precision)) + let precision = Precision.bridgeJSLiftParameter(precision) + setPrecision(_: precision) #else fatalError("Only available on WebAssembly") #endif @@ -379,7 +400,8 @@ public func _bjs_getPrecision() -> Float32 { @_cdecl("bjs_roundTripOptionalPrecision") public func _bjs_roundTripOptionalPrecision(_ inputIsSome: Int32, _ inputValue: Float32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalPrecision(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalPrecision(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -390,7 +412,8 @@ public func _bjs_roundTripOptionalPrecision(_ inputIsSome: Int32, _ inputValue: @_cdecl("bjs_setRatio") public func _bjs_setRatio(_ ratio: Float64) -> Void { #if arch(wasm32) - setRatio(_: Ratio.bridgeJSLiftParameter(ratio)) + let ratio = Ratio.bridgeJSLiftParameter(ratio) + setRatio(_: ratio) #else fatalError("Only available on WebAssembly") #endif @@ -411,7 +434,8 @@ public func _bjs_getRatio() -> Float64 { @_cdecl("bjs_roundTripOptionalRatio") public func _bjs_roundTripOptionalRatio(_ inputIsSome: Int32, _ inputValue: Float64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalRatio(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let input = Optional.bridgeJSLiftParameter(inputIsSome, inputValue) + let ret = roundTripOptionalRatio(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -422,7 +446,8 @@ public func _bjs_roundTripOptionalRatio(_ inputIsSome: Int32, _ inputValue: Floa @_cdecl("bjs_processTheme") public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int32 { #if arch(wasm32) - let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = Theme.bridgeJSLiftParameter(themeBytes, themeLength) + let ret = processTheme(_: theme) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -433,7 +458,8 @@ public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int3 @_cdecl("bjs_convertPriority") public func _bjs_convertPriority(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = convertPriority(_: HttpStatus.bridgeJSLiftParameter(status)) + let status = HttpStatus.bridgeJSLiftParameter(status) + let ret = convertPriority(_: status) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -444,7 +470,8 @@ public func _bjs_convertPriority(_ status: Int32) -> Int32 { @_cdecl("bjs_validateSession") public func _bjs_validateSession(_ session: Int64) -> Void { #if arch(wasm32) - let ret = validateSession(_: SessionId.bridgeJSLiftParameter(session)) + let session = SessionId.bridgeJSLiftParameter(session) + let ret = validateSession(_: session) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift index d7efa630c..9e0075c54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift @@ -109,7 +109,8 @@ fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Library.Shelf(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -131,7 +132,8 @@ public func _bjs_Library_Shelf_static_capacity_get() -> Int32 { @_cdecl("bjs_Library_Shelf_describeShelf") public func _bjs_Library_Shelf_describeShelf() -> Void { #if arch(wasm32) - let ret = Library.Shelf.bridgeJSLiftParameter().describeShelf() + let _self = Library.Shelf.bridgeJSLiftParameter() + let ret = _self.describeShelf() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -188,7 +190,8 @@ fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { @_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)) + let slot = Int.bridgeJSLiftParameter(slot) + let ret = Library.Shelf.Divider(slot: slot) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -199,7 +202,8 @@ public func _bjs_Library_Shelf_Divider_init(_ slot: Int32) -> Void { @_cdecl("bjs_roundTripMessage") public func _bjs_roundTripMessage(_ message: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMessage(_: Message.bridgeJSLiftParameter(message)) + let message = Message.bridgeJSLiftParameter(message) + let ret = roundTripMessage(_: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -210,7 +214,8 @@ public func _bjs_roundTripMessage(_ message: Int32) -> Void { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Library(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -221,7 +226,8 @@ public func _bjs_Library_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Library_describe") public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Library.bridgeJSLiftParameter(_self).describe() + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -232,7 +238,9 @@ public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { @_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)) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.rename(_: title) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -243,7 +251,9 @@ public func _bjs_Library_rename(_ _self: UnsafeMutableRawPointer, _ titleBytes: @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.shelf(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -254,7 +264,8 @@ public func _bjs_Library_shelf(_ _self: UnsafeMutableRawPointer, _ labelBytes: I @_cdecl("bjs_Library_name_get") public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Library.bridgeJSLiftParameter(_self).name + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -265,7 +276,9 @@ public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Library.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift index cc8091bbe..15d4462d5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift @@ -48,7 +48,8 @@ fileprivate func _bjs_struct_lift_Depot_Crate_extern() -> Int32 { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Depot.Crate(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -59,7 +60,8 @@ public func _bjs_Depot_Crate_init(_ labelBytes: Int32, _ labelLength: Int32) -> @_cdecl("bjs_Depot_Crate_describeCrate") public func _bjs_Depot_Crate_describeCrate() -> Void { #if arch(wasm32) - let ret = Depot.Crate.bridgeJSLiftParameter().describeCrate() + let _self = Depot.Crate.bridgeJSLiftParameter() + let ret = _self.describeCrate() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift index 7fe6db4d2..c0dbec726 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift @@ -51,7 +51,8 @@ fileprivate func _bjs_struct_lift_Meta_extern() -> Int32 { @_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)) + let note = String.bridgeJSLiftParameter(noteBytes, noteLength) + let ret = Signal.Meta(note: note) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift index 544a15e7c..a648f92e0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_roundTripInt8") public func _bjs_roundTripInt8(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripInt8(_: Int8.bridgeJSLiftParameter(v)) + let v = Int8.bridgeJSLiftParameter(v) + let ret = roundTripInt8(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_roundTripInt8(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripUInt8") public func _bjs_roundTripUInt8(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUInt8(_: UInt8.bridgeJSLiftParameter(v)) + let v = UInt8.bridgeJSLiftParameter(v) + let ret = roundTripUInt8(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_roundTripUInt8(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripInt16") public func _bjs_roundTripInt16(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripInt16(_: Int16.bridgeJSLiftParameter(v)) + let v = Int16.bridgeJSLiftParameter(v) + let ret = roundTripInt16(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,8 @@ public func _bjs_roundTripInt16(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripUInt16") public func _bjs_roundTripUInt16(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) + let v = UInt16.bridgeJSLiftParameter(v) + let ret = roundTripUInt16(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -46,7 +50,8 @@ public func _bjs_roundTripUInt16(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripInt32") public func _bjs_roundTripInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) + let v = Int32.bridgeJSLiftParameter(v) + let ret = roundTripInt32(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -57,7 +62,8 @@ public func _bjs_roundTripInt32(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripUInt32") public func _bjs_roundTripUInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) + let v = UInt32.bridgeJSLiftParameter(v) + let ret = roundTripUInt32(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -68,7 +74,8 @@ public func _bjs_roundTripUInt32(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripInt64") public func _bjs_roundTripInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) + let v = Int64.bridgeJSLiftParameter(v) + let ret = roundTripInt64(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -79,7 +86,8 @@ public func _bjs_roundTripInt64(_ v: Int64) -> Int64 { @_cdecl("bjs_roundTripUInt64") public func _bjs_roundTripUInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = roundTripUInt64(_: UInt64.bridgeJSLiftParameter(v)) + let v = UInt64.bridgeJSLiftParameter(v) + let ret = roundTripUInt64(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift index 01ed6196e..cf07236fc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -112,7 +112,8 @@ fileprivate func _bjs_struct_lift_GenericPoint_extern() -> Int32 { @_cdecl("bjs_GenericImportBox_init") public func _bjs_GenericImportBox_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = GenericImportBox(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = GenericImportBox(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -123,7 +124,8 @@ public func _bjs_GenericImportBox_init(_ value: Int32) -> UnsafeMutableRawPointe @_cdecl("bjs_GenericImportBox_get") public func _bjs_GenericImportBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = GenericImportBox.bridgeJSLiftParameter(_self).get() + let _self = GenericImportBox.bridgeJSLiftParameter(_self) + let ret = _self.get() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -134,7 +136,8 @@ public func _bjs_GenericImportBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 @_cdecl("bjs_GenericImportBox_value_get") public func _bjs_GenericImportBox_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = GenericImportBox.bridgeJSLiftParameter(_self).value + let _self = GenericImportBox.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -145,7 +148,9 @@ public func _bjs_GenericImportBox_value_get(_ _self: UnsafeMutableRawPointer) -> @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = GenericImportBox.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift index a79b91d56..e79cd04cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_CachedModel_init") public func _bjs_CachedModel_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = CachedModel(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = CachedModel(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_CachedModel_init(_ nameBytes: Int32, _ nameLength: Int32) -> Un @_cdecl("bjs_CachedModel_name_get") public func _bjs_CachedModel_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = CachedModel.bridgeJSLiftParameter(_self).name + let _self = CachedModel.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,9 @@ public func _bjs_CachedModel_name_get(_ _self: UnsafeMutableRawPointer) -> Void @_cdecl("bjs_CachedModel_name_set") public func _bjs_CachedModel_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - CachedModel.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = CachedModel.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -65,7 +69,8 @@ fileprivate func _bjs_CachedModel_wrap_extern(_ pointer: UnsafeMutableRawPointer @_cdecl("bjs_UncachedModel_init") public func _bjs_UncachedModel_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = UncachedModel(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = UncachedModel(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -76,7 +81,8 @@ public func _bjs_UncachedModel_init(_ value: Int32) -> UnsafeMutableRawPointer { @_cdecl("bjs_UncachedModel_value_get") public func _bjs_UncachedModel_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = UncachedModel.bridgeJSLiftParameter(_self).value + let _self = UncachedModel.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -87,7 +93,9 @@ public func _bjs_UncachedModel_value_get(_ _self: UnsafeMutableRawPointer) -> In @_cdecl("bjs_UncachedModel_value_set") public func _bjs_UncachedModel_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - UncachedModel.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = UncachedModel.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -128,7 +136,8 @@ fileprivate func _bjs_UncachedModel_wrap_extern(_ pointer: UnsafeMutableRawPoint @_cdecl("bjs_ExplicitlyUncachedModel_init") public func _bjs_ExplicitlyUncachedModel_init(_ count: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ExplicitlyUncachedModel(count: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let ret = ExplicitlyUncachedModel(count: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -139,7 +148,8 @@ public func _bjs_ExplicitlyUncachedModel_init(_ count: Int32) -> UnsafeMutableRa @_cdecl("bjs_ExplicitlyUncachedModel_count_get") public func _bjs_ExplicitlyUncachedModel_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ExplicitlyUncachedModel.bridgeJSLiftParameter(_self).count + let _self = ExplicitlyUncachedModel.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -150,7 +160,9 @@ public func _bjs_ExplicitlyUncachedModel_count_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_ExplicitlyUncachedModel_count_set") public func _bjs_ExplicitlyUncachedModel_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ExplicitlyUncachedModel.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = ExplicitlyUncachedModel.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index b9fddf706..8c98946bc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -75,7 +75,8 @@ public func _bjs_makeFoo() -> Int32 { @_cdecl("bjs_processFooArray") public func _bjs_processFooArray() -> Void { #if arch(wasm32) - let ret = processFooArray(_: [Foo].bridgeJSStackPop()) + let foos = [Foo].bridgeJSStackPop() + let ret = processFooArray(_: foos) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -86,7 +87,8 @@ public func _bjs_processFooArray() -> Void { @_cdecl("bjs_processOptionalFooArray") public func _bjs_processOptionalFooArray() -> Void { #if arch(wasm32) - let ret = processOptionalFooArray(_: [Optional].bridgeJSStackPop()) + let foos = [Optional].bridgeJSStackPop() + let ret = processOptionalFooArray(_: foos) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -97,7 +99,8 @@ public func _bjs_processOptionalFooArray() -> Void { @_cdecl("bjs_roundtripFooContainer") public func _bjs_roundtripFooContainer() -> Void { #if arch(wasm32) - let ret = roundtripFooContainer(_: FooContainer.bridgeJSLiftParameter()) + let container = FooContainer.bridgeJSLiftParameter() + let ret = roundtripFooContainer(_: container) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift index 8e01bca22..535c081f4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift @@ -59,7 +59,8 @@ public func _bjs_RenamedEnumMembers_static_defaultValue_get() -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + RenamedEnumMembers.defaultValue = value #else fatalError("Only available on WebAssembly") #endif @@ -69,7 +70,9 @@ public func _bjs_RenamedEnumMembers_static_defaultValue_set(_ valueBytes: Int32, @_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)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = RenamedNamespaceMembers.add(_: a, _: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -91,7 +94,8 @@ public func _bjs_RenamedNamespaceMembers_static_answer_get() -> Int32 { @_cdecl("bjs_RenamedNamespaceMembers_static_answer_set") public func _bjs_RenamedNamespaceMembers_static_answer_set(_ value: Int32) -> Void { #if arch(wasm32) - RenamedNamespaceMembers.answer = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + RenamedNamespaceMembers.answer = value #else fatalError("Only available on WebAssembly") #endif @@ -160,7 +164,8 @@ public func _bjs_RenamedVector_static_origin_get() -> Void { @_cdecl("bjs_RenamedVector_magnitude") public func _bjs_RenamedVector_magnitude() -> Float64 { #if arch(wasm32) - let ret = RenamedVector.bridgeJSLiftParameter().length() + let _self = RenamedVector.bridgeJSLiftParameter() + let ret = _self.length() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -171,7 +176,9 @@ public func _bjs_RenamedVector_magnitude() -> Float64 { @_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)) + let angle = Double.bridgeJSLiftParameter(angle) + let radius = Double.bridgeJSLiftParameter(radius) + let ret = RenamedVector.polar(radius: radius, angle: angle) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -182,7 +189,8 @@ public func _bjs_RenamedVector_static_fromPolar(_ radius: Float64, _ angle: Floa @_cdecl("bjs_makeGreeting") public func _bjs_makeGreeting(_ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = renderGreeting(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = renderGreeting(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -193,7 +201,8 @@ public func _bjs_makeGreeting(_ nameBytes: Int32, _ nameLength: Int32) -> Void { @_cdecl("bjs_greetName") public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = greet(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = greet(_: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -204,7 +213,8 @@ public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { @_cdecl("bjs_greetCount") public func _bjs_greetCount(_ count: Int32) -> Void { #if arch(wasm32) - let ret = greet(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let ret = greet(_: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -226,7 +236,9 @@ public func _bjs_Utils_Text_namespacedRenamed() -> Int32 { @_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)) + let count = Int.bridgeJSLiftParameter(count) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let ret = RenamedMembers(title: title, count: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -237,7 +249,8 @@ public func _bjs_RenamedMembers_init(_ titleBytes: Int32, _ titleLength: Int32, @_cdecl("bjs_RenamedMembers_makeGreeting") public func _bjs_RenamedMembers_makeGreeting(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = RenamedMembers.bridgeJSLiftParameter(_self).greet() + let _self = RenamedMembers.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -259,7 +272,8 @@ public func _bjs_RenamedMembers_static_makeDefault() -> UnsafeMutableRawPointer @_cdecl("bjs_RenamedMembers_title_get") public func _bjs_RenamedMembers_title_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = RenamedMembers.bridgeJSLiftParameter(_self).title + let _self = RenamedMembers.bridgeJSLiftParameter(_self) + let ret = _self.title return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -270,7 +284,9 @@ public func _bjs_RenamedMembers_title_get(_ _self: UnsafeMutableRawPointer) -> V @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = RenamedMembers.bridgeJSLiftParameter(_self) + _self.title = value #else fatalError("Only available on WebAssembly") #endif @@ -280,7 +296,8 @@ public func _bjs_RenamedMembers_title_set(_ _self: UnsafeMutableRawPointer, _ va @_cdecl("bjs_RenamedMembers_count_get") public func _bjs_RenamedMembers_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = RenamedMembers.bridgeJSLiftParameter(_self).count + let _self = RenamedMembers.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -302,7 +319,8 @@ public func _bjs_RenamedMembers_static_sharedCount_get() -> Int32 { @_cdecl("bjs_RenamedMembers_static_sharedCount_set") public func _bjs_RenamedMembers_static_sharedCount_set(_ value: Int32) -> Void { #if arch(wasm32) - RenamedMembers.sharedCount = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + RenamedMembers.sharedCount = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift index 4777af058..1c619f690 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_processBytes") public func _bjs_processBytes(_ data: Int32) -> Int32 { #if arch(wasm32) - let ret = processBytes(_: JSUint8Array.bridgeJSLiftParameter(data)) + let data = JSUint8Array.bridgeJSLiftParameter(data) + let ret = processBytes(_: data) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_processBytes(_ data: Int32) -> Int32 { @_cdecl("bjs_processFloats") public func _bjs_processFloats(_ data: Int32) -> Int32 { #if arch(wasm32) - let ret = processFloats(_: JSFloat32Array.bridgeJSLiftParameter(data)) + let data = JSFloat32Array.bridgeJSLiftParameter(data) + let ret = processFloats(_: data) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_processFloats(_ data: Int32) -> Int32 { @_cdecl("bjs_processGenericDoubles") public func _bjs_processGenericDoubles(_ data: Int32) -> Int32 { #if arch(wasm32) - let ret = processGenericDoubles(_: JSFloat64Array.bridgeJSLiftParameter(data)) + let data = JSFloat64Array.bridgeJSLiftParameter(data) + let ret = processGenericDoubles(_: data) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,8 @@ public func _bjs_processGenericDoubles(_ data: Int32) -> Int32 { @_cdecl("bjs_processGenericInts") public func _bjs_processGenericInts(_ data: Int32) -> Int32 { #if arch(wasm32) - let ret = processGenericInts(_: JSInt32Array.bridgeJSLiftParameter(data)) + let data = JSInt32Array.bridgeJSLiftParameter(data) + let ret = processGenericInts(_: data) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift index 1ce288202..4d2f76b5b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_roundTripJSValue") public func _bjs_roundTripJSValue(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - let ret = roundTripJSValue(_: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2)) + let value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let ret = roundTripJSValue(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_roundTripJSValue(_ valueKind: Int32, _ valuePayload1: Int32, _ @_cdecl("bjs_roundTripOptionalJSValue") public func _bjs_roundTripOptionalJSValue(_ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSValue(_: Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2) + let ret = roundTripOptionalJSValue(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_roundTripOptionalJSValue(_ valueIsSome: Int32, _ valueKind: Int @_cdecl("bjs_roundTripJSValueArray") public func _bjs_roundTripJSValueArray() -> Void { #if arch(wasm32) - let ret = roundTripJSValueArray(_: [JSValue].bridgeJSStackPop()) + let values = [JSValue].bridgeJSStackPop() + let ret = roundTripJSValueArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,8 @@ public func _bjs_roundTripJSValueArray() -> Void { @_cdecl("bjs_roundTripOptionalJSValueArray") public func _bjs_roundTripOptionalJSValueArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSValueArray(_: Optional<[JSValue]>.bridgeJSLiftParameter()) + let values = Optional<[JSValue]>.bridgeJSLiftParameter() + let ret = roundTripOptionalJSValueArray(_: values) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -46,7 +50,9 @@ public func _bjs_roundTripOptionalJSValueArray() -> Void { @_cdecl("bjs_JSValueHolder_init") public func _bjs_JSValueHolder_init(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ optionalValueIsSome: Int32, _ optionalValueKind: Int32, _ optionalValuePayload1: Int32, _ optionalValuePayload2: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSValueHolder(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2), optionalValue: Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2)) + let optionalValue = Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2) + let value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let ret = JSValueHolder(value: value, optionalValue: optionalValue) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -57,7 +63,10 @@ public func _bjs_JSValueHolder_init(_ valueKind: Int32, _ valuePayload1: Int32, @_cdecl("bjs_JSValueHolder_update") public func _bjs_JSValueHolder_update(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ optionalValueIsSome: Int32, _ optionalValueKind: Int32, _ optionalValuePayload1: Int32, _ optionalValuePayload2: Float64) -> Void { #if arch(wasm32) - JSValueHolder.bridgeJSLiftParameter(_self).update(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2), optionalValue: Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2)) + let optionalValue = Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2) + let value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + _self.update(value: value, optionalValue: optionalValue) #else fatalError("Only available on WebAssembly") #endif @@ -67,7 +76,9 @@ public func _bjs_JSValueHolder_update(_ _self: UnsafeMutableRawPointer, _ valueK @_cdecl("bjs_JSValueHolder_echo") public func _bjs_JSValueHolder_echo(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - let ret = JSValueHolder.bridgeJSLiftParameter(_self).echo(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2)) + let value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + let ret = _self.echo(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -78,7 +89,9 @@ public func _bjs_JSValueHolder_echo(_ _self: UnsafeMutableRawPointer, _ valueKin @_cdecl("bjs_JSValueHolder_echoOptional") public func _bjs_JSValueHolder_echoOptional(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - let ret = JSValueHolder.bridgeJSLiftParameter(_self).echoOptional(_: Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2) + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + let ret = _self.echoOptional(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -89,7 +102,8 @@ public func _bjs_JSValueHolder_echoOptional(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_JSValueHolder_value_get") public func _bjs_JSValueHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = JSValueHolder.bridgeJSLiftParameter(_self).value + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -100,7 +114,9 @@ public func _bjs_JSValueHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Vo @_cdecl("bjs_JSValueHolder_value_set") public func _bjs_JSValueHolder_value_set(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - JSValueHolder.bridgeJSLiftParameter(_self).value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -110,7 +126,8 @@ public func _bjs_JSValueHolder_value_set(_ _self: UnsafeMutableRawPointer, _ val @_cdecl("bjs_JSValueHolder_optionalValue_get") public func _bjs_JSValueHolder_optionalValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = JSValueHolder.bridgeJSLiftParameter(_self).optionalValue + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -121,7 +138,9 @@ public func _bjs_JSValueHolder_optionalValue_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_JSValueHolder_optionalValue_set") public func _bjs_JSValueHolder_optionalValue_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { #if arch(wasm32) - JSValueHolder.bridgeJSLiftParameter(_self).optionalValue = Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2) + let _self = JSValueHolder.bridgeJSLiftParameter(_self) + _self.optionalValue = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift index feaa7012c..ee9640144 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift @@ -24,7 +24,8 @@ public func _bjs_GlobalAPI_GlobalClass_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_GlobalAPI_GlobalClass_greet") public func _bjs_GlobalAPI_GlobalClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = GlobalClass.bridgeJSLiftParameter(_self).greet() + let _self = GlobalClass.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift index 184096f29..98cd730a5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift @@ -24,7 +24,8 @@ public func _bjs_PrivateAPI_PrivateClass_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_PrivateAPI_PrivateClass_greet") public func _bjs_PrivateAPI_PrivateClass_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PrivateClass.bridgeJSLiftParameter(_self).greet() + let _self = PrivateClass.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift index bff3007b7..dc4387ca3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift @@ -53,9 +53,10 @@ extension JSTypedClosure where Signature == (Workshop.Bench) -> Workshop.Bench { @_cdecl("invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC") public func _invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) + let param0 = Workshop.Bench.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Workshop.Bench) -> Workshop.Bench>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Workshop.Bench.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -76,7 +77,9 @@ 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_10TestModule8Workshop5BenchC_8Workshop5BenchC.bridgeJSLift(transform)) + let transform = _BJS_Closure_10TestModule8Workshop5BenchC_8Workshop5BenchC.bridgeJSLift(transform) + let bench = Workshop.Bench.bridgeJSLiftParameter(bench) + let ret = refitBench(_: bench, _: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index baa867eed..525a4e96d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -24,7 +24,8 @@ public func _bjs_MyModule_Utils_namespacedFunction() -> Void { @_cdecl("bjs___Swift_Foundation_Greeter_init") public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +36,8 @@ public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLengt @_cdecl("bjs___Swift_Foundation_Greeter_greet") public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -110,7 +112,9 @@ public func _bjs_Utils_Converters_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Utils_Converters_Converter_toString") public func _bjs_Utils_Converters_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Converter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -152,7 +156,8 @@ fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMu @_cdecl("bjs___Swift_Foundation_UUID_uuidString") public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = UUID.bridgeJSLiftParameter(_self).uuidString() + let _self = UUID.bridgeJSLiftParameter(_self) + let ret = _self.uuidString() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -205,7 +210,8 @@ public func _bjs_Collections_Container_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Collections_Container_getItems") public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).getItems() + let _self = Container.bridgeJSLiftParameter(_self) + let ret = _self.getItems() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -216,7 +222,9 @@ public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_Collections_Container_addItem") public func _bjs_Collections_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).addItem(_: Greeter.bridgeJSLiftParameter(item)) + let item = Greeter.bridgeJSLiftParameter(item) + let _self = Container.bridgeJSLiftParameter(_self) + _self.addItem(_: item) #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index baa867eed..525a4e96d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -24,7 +24,8 @@ public func _bjs_MyModule_Utils_namespacedFunction() -> Void { @_cdecl("bjs___Swift_Foundation_Greeter_init") public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +36,8 @@ public func _bjs___Swift_Foundation_Greeter_init(_ nameBytes: Int32, _ nameLengt @_cdecl("bjs___Swift_Foundation_Greeter_greet") public func _bjs___Swift_Foundation_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -110,7 +112,9 @@ public func _bjs_Utils_Converters_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Utils_Converters_Converter_toString") public func _bjs_Utils_Converters_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Converter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -152,7 +156,8 @@ fileprivate func _bjs_Utils_Converters_Converter_wrap_extern(_ pointer: UnsafeMu @_cdecl("bjs___Swift_Foundation_UUID_uuidString") public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = UUID.bridgeJSLiftParameter(_self).uuidString() + let _self = UUID.bridgeJSLiftParameter(_self) + let ret = _self.uuidString() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -205,7 +210,8 @@ public func _bjs_Collections_Container_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Collections_Container_getItems") public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).getItems() + let _self = Container.bridgeJSLiftParameter(_self) + let ret = _self.getItems() ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -216,7 +222,9 @@ public func _bjs_Collections_Container_getItems(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_Collections_Container_addItem") public func _bjs_Collections_Container_addItem(_ _self: UnsafeMutableRawPointer, _ item: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).addItem(_: Greeter.bridgeJSLiftParameter(item)) + let item = Greeter.bridgeJSLiftParameter(item) + let _self = Container.bridgeJSLiftParameter(_self) + _self.addItem(_: item) #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift index 9e1b0e0f6..e7310b1dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -98,7 +98,8 @@ fileprivate func _bjs_struct_lift_Player_Stats_extern() -> Int32 { @_cdecl("bjs_User_getName") public func _bjs_User_getName(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = User.bridgeJSLiftParameter(_self).getName() + let _self = User.bridgeJSLiftParameter(_self) + let ret = _self.getName() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -140,7 +141,8 @@ fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> In @_cdecl("bjs_Player_getTag") public func _bjs_Player_getTag(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Player.bridgeJSLiftParameter(_self).getTag() + let _self = Player.bridgeJSLiftParameter(_self) + let ret = _self.getTag() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift index 266f37f09..6da67b137 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift @@ -48,7 +48,8 @@ fileprivate func _bjs_struct_lift_Catalog_Entry_extern() -> Int32 { @_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)) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let ret = Catalog.Entry(title: title) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -105,7 +106,8 @@ fileprivate func _bjs_struct_lift_Entry_extern() -> Int32 { @_cdecl("bjs_Entry_init") public func _bjs_Entry_init(_ identifier: Int32) -> Void { #if arch(wasm32) - let ret = Entry(identifier: Int.bridgeJSLiftParameter(identifier)) + let identifier = Int.bridgeJSLiftParameter(identifier) + let ret = Entry(identifier: identifier) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -116,7 +118,8 @@ public func _bjs_Entry_init(_ identifier: Int32) -> Void { @_cdecl("bjs_takeEntry") public func _bjs_takeEntry() -> Void { #if arch(wasm32) - let ret = takeEntry(_: Entry.bridgeJSLiftParameter()) + let entry = Entry.bridgeJSLiftParameter() + let ret = takeEntry(_: entry) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -127,7 +130,8 @@ public func _bjs_takeEntry() -> Void { @_cdecl("bjs_takeCatalogEntry") public func _bjs_takeCatalogEntry() -> Void { #if arch(wasm32) - let ret = takeCatalogEntry(_: Catalog.Entry.bridgeJSLiftParameter()) + let entry = Catalog.Entry.bridgeJSLiftParameter() + let ret = takeCatalogEntry(_: entry) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index f96fe39ff..f45a0bb1e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_roundTripOptionalClass") public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripOptionalClass(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +14,8 @@ public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: Unsa @_cdecl("bjs_testOptionalPropertyRoundtrip") public func _bjs_testOptionalPropertyRoundtrip(_ holderIsSome: Int32, _ holderValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = testOptionalPropertyRoundtrip(_: Optional.bridgeJSLiftParameter(holderIsSome, holderValue)) + let holder = Optional.bridgeJSLiftParameter(holderIsSome, holderValue) + let ret = testOptionalPropertyRoundtrip(_: holder) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +26,8 @@ public func _bjs_testOptionalPropertyRoundtrip(_ holderIsSome: Int32, _ holderVa @_cdecl("bjs_roundTripExportedOptionalJSObject") public func _bjs_roundTripExportedOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripExportedOptionalJSObject(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripExportedOptionalJSObject(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +38,8 @@ public func _bjs_roundTripExportedOptionalJSObject(_ valueIsSome: Int32, _ value @_cdecl("bjs_roundTripExportedOptionalJSClass") public func _bjs_roundTripExportedOptionalJSClass(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripExportedOptionalJSClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripExportedOptionalJSClass(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -46,7 +50,8 @@ public func _bjs_roundTripExportedOptionalJSClass(_ valueIsSome: Int32, _ valueV @_cdecl("bjs_roundTripString") public func _bjs_roundTripString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripString(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -57,7 +62,8 @@ public func _bjs_roundTripString(_ nameIsSome: Int32, _ nameBytes: Int32, _ name @_cdecl("bjs_roundTripInt") public func _bjs_roundTripInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripInt(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -68,7 +74,8 @@ public func _bjs_roundTripInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void @_cdecl("bjs_roundTripInt8") public func _bjs_roundTripInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripInt8(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripInt8(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -79,7 +86,8 @@ public func _bjs_roundTripInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Voi @_cdecl("bjs_roundTripUInt8") public func _bjs_roundTripUInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUInt8(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripUInt8(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -90,7 +98,8 @@ public func _bjs_roundTripUInt8(_ valueIsSome: Int32, _ valueValue: Int32) -> Vo @_cdecl("bjs_roundTripInt16") public func _bjs_roundTripInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripInt16(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripInt16(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -101,7 +110,8 @@ public func _bjs_roundTripInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> Vo @_cdecl("bjs_roundTripUInt16") public func _bjs_roundTripUInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUInt16(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripUInt16(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -112,7 +122,8 @@ public func _bjs_roundTripUInt16(_ valueIsSome: Int32, _ valueValue: Int32) -> V @_cdecl("bjs_roundTripInt32") public func _bjs_roundTripInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripInt32(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripInt32(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -123,7 +134,8 @@ public func _bjs_roundTripInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> Vo @_cdecl("bjs_roundTripUInt32") public func _bjs_roundTripUInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUInt32(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripUInt32(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -134,7 +146,8 @@ public func _bjs_roundTripUInt32(_ valueIsSome: Int32, _ valueValue: Int32) -> V @_cdecl("bjs_roundTripBool") public func _bjs_roundTripBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) + let flag = Optional.bridgeJSLiftParameter(flagIsSome, flagValue) + let ret = roundTripBool(flag: flag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -145,7 +158,8 @@ public func _bjs_roundTripBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void @_cdecl("bjs_roundTripFloat") public func _bjs_roundTripFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { #if arch(wasm32) - let ret = roundTripFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) + let number = Optional.bridgeJSLiftParameter(numberIsSome, numberValue) + let ret = roundTripFloat(number: number) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -156,7 +170,8 @@ public func _bjs_roundTripFloat(_ numberIsSome: Int32, _ numberValue: Float32) - @_cdecl("bjs_roundTripDouble") public func _bjs_roundTripDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { #if arch(wasm32) - let ret = roundTripDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) + let precision = Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue) + let ret = roundTripDouble(precision: precision) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -167,7 +182,8 @@ public func _bjs_roundTripDouble(_ precisionIsSome: Int32, _ precisionValue: Flo @_cdecl("bjs_roundTripSyntax") public func _bjs_roundTripSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripSyntax(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -178,7 +194,8 @@ public func _bjs_roundTripSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ name @_cdecl("bjs_roundTripMixSyntax") public func _bjs_roundTripMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripMixSyntax(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -189,7 +206,8 @@ public func _bjs_roundTripMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ n @_cdecl("bjs_roundTripSwiftSyntax") public func _bjs_roundTripSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripSwiftSyntax(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -200,7 +218,8 @@ public func _bjs_roundTripSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ @_cdecl("bjs_roundTripMixedSwiftSyntax") public func _bjs_roundTripMixedSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMixedSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripMixedSwiftSyntax(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -211,7 +230,8 @@ public func _bjs_roundTripMixedSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int @_cdecl("bjs_roundTripWithSpaces") public func _bjs_roundTripWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { #if arch(wasm32) - let ret = roundTripWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = roundTripWithSpaces(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -222,7 +242,8 @@ public func _bjs_roundTripWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64 @_cdecl("bjs_roundTripAlias") public func _bjs_roundTripAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) + let age = Optional.bridgeJSLiftParameter(ageIsSome, ageValue) + let ret = roundTripAlias(age: age) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -233,7 +254,8 @@ public func _bjs_roundTripAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { @_cdecl("bjs_roundTripOptionalAlias") public func _bjs_roundTripOptionalAlias(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalAlias(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = roundTripOptionalAlias(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -244,7 +266,11 @@ public func _bjs_roundTripOptionalAlias(_ nameIsSome: Int32, _ nameBytes: Int32, @_cdecl("bjs_testMixedOptionals") public func _bjs_testMixedOptionals(_ firstNameIsSome: Int32, _ firstNameBytes: Int32, _ firstNameLength: Int32, _ lastNameIsSome: Int32, _ lastNameBytes: Int32, _ lastNameLength: Int32, _ ageIsSome: Int32, _ ageValue: Int32, _ active: Int32) -> Void { #if arch(wasm32) - let ret = testMixedOptionals(firstName: Optional.bridgeJSLiftParameter(firstNameIsSome, firstNameBytes, firstNameLength), lastName: Optional.bridgeJSLiftParameter(lastNameIsSome, lastNameBytes, lastNameLength), age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue), active: Bool.bridgeJSLiftParameter(active)) + let active = Bool.bridgeJSLiftParameter(active) + let age = Optional.bridgeJSLiftParameter(ageIsSome, ageValue) + let lastName = Optional.bridgeJSLiftParameter(lastNameIsSome, lastNameBytes, lastNameLength) + let firstName = Optional.bridgeJSLiftParameter(firstNameIsSome, firstNameBytes, firstNameLength) + let ret = testMixedOptionals(firstName: firstName, lastName: lastName, age: age, active: active) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -255,7 +281,8 @@ public func _bjs_testMixedOptionals(_ firstNameIsSome: Int32, _ firstNameBytes: @_cdecl("bjs_Greeter_init") public func _bjs_Greeter_init(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -266,7 +293,8 @@ public func _bjs_Greeter_init(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLen @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -277,7 +305,9 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_changeName") public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.changeName(name: name) #else fatalError("Only available on WebAssembly") #endif @@ -287,7 +317,8 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameIsSo @_cdecl("bjs_Greeter_name_get") public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -298,7 +329,9 @@ public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_name_set") public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).name = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -350,7 +383,8 @@ public func _bjs_OptionalPropertyHolder_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_OptionalPropertyHolder_optionalName_get") public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalName return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -361,7 +395,9 @@ public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableR @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalName = value #else fatalError("Only available on WebAssembly") #endif @@ -371,7 +407,8 @@ public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableR @_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalAge return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -382,7 +419,9 @@ public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRa @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalAge = value #else fatalError("Only available on WebAssembly") #endif @@ -392,7 +431,8 @@ public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRa @_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalGreeter return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -403,7 +443,9 @@ public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutab @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalGreeter = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift index e818f2877..f6c47ef5c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift @@ -2,7 +2,12 @@ @_cdecl("bjs_check") public func _bjs_check(_ a: Int32, _ b: Int32, _ c: Float32, _ d: Float64, _ e: Int32) -> Void { #if arch(wasm32) - check(a: Int.bridgeJSLiftParameter(a), b: UInt.bridgeJSLiftParameter(b), c: Float.bridgeJSLiftParameter(c), d: Double.bridgeJSLiftParameter(d), e: Bool.bridgeJSLiftParameter(e)) + let e = Bool.bridgeJSLiftParameter(e) + let d = Double.bridgeJSLiftParameter(d) + let c = Float.bridgeJSLiftParameter(c) + let b = UInt.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + check(a: a, b: b, c: c, d: d, e: e) #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift index 1c7c8350f..d5afd2def 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift @@ -2,7 +2,13 @@ @_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)) + let jsObject = JSObject.bridgeJSLiftParameter(jsObject) + let stringValue = String.bridgeJSLiftParameter(stringValueBytes, stringValueLength) + let boolValue = Bool.bridgeJSLiftParameter(boolValue) + let doubleValue = Double.bridgeJSLiftParameter(doubleValue) + let floatValue = Float.bridgeJSLiftParameter(floatValue) + let intValue = Int.bridgeJSLiftParameter(intValue) + let ret = createPropertyHolder(intValue: intValue, floatValue: floatValue, doubleValue: doubleValue, boolValue: boolValue, stringValue: stringValue, jsObject: jsObject) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13,7 +19,8 @@ public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, @_cdecl("bjs_testPropertyHolder") public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + let holder = PropertyHolder.bridgeJSLiftParameter(holder) + let ret = testPropertyHolder(holder: holder) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -24,7 +31,13 @@ public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_PropertyHolder_init") public func _bjs_PropertyHolder_init(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> 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)) + let jsObject = JSObject.bridgeJSLiftParameter(jsObject) + let stringValue = String.bridgeJSLiftParameter(stringValueBytes, stringValueLength) + let boolValue = Bool.bridgeJSLiftParameter(boolValue) + let doubleValue = Double.bridgeJSLiftParameter(doubleValue) + let floatValue = Float.bridgeJSLiftParameter(floatValue) + let intValue = Int.bridgeJSLiftParameter(intValue) + let ret = PropertyHolder(intValue: intValue, floatValue: floatValue, doubleValue: doubleValue, boolValue: boolValue, stringValue: stringValue, jsObject: jsObject) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -35,7 +48,8 @@ public func _bjs_PropertyHolder_init(_ intValue: Int32, _ floatValue: Float32, _ @_cdecl("bjs_PropertyHolder_getAllValues") public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).getAllValues() + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.getAllValues() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -46,7 +60,8 @@ public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_intValue_get") public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).intValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.intValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -57,7 +72,9 @@ public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_intValue_set") public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).intValue = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.intValue = value #else fatalError("Only available on WebAssembly") #endif @@ -67,7 +84,8 @@ public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_floatValue_get") public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).floatValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.floatValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -78,7 +96,9 @@ public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Float.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.floatValue = value #else fatalError("Only available on WebAssembly") #endif @@ -88,7 +108,8 @@ public func _bjs_PropertyHolder_floatValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_doubleValue_get") public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).doubleValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.doubleValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -99,7 +120,9 @@ public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer @_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) + let value = Double.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.doubleValue = value #else fatalError("Only available on WebAssembly") #endif @@ -109,7 +132,8 @@ public func _bjs_PropertyHolder_doubleValue_set(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_boolValue_get") public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).boolValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.boolValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -120,7 +144,9 @@ public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Bool.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.boolValue = value #else fatalError("Only available on WebAssembly") #endif @@ -130,7 +156,8 @@ public func _bjs_PropertyHolder_boolValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_stringValue_get") public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).stringValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.stringValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -141,7 +168,9 @@ public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_stringValue_set") public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).stringValue = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.stringValue = value #else fatalError("Only available on WebAssembly") #endif @@ -151,7 +180,8 @@ public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_readonlyInt_get") public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyInt + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyInt return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -162,7 +192,8 @@ public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_readonlyFloat_get") public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyFloat + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyFloat return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -173,7 +204,8 @@ public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_PropertyHolder_readonlyDouble_get") public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyDouble + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyDouble return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -184,7 +216,8 @@ public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_PropertyHolder_readonlyBool_get") public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyBool + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyBool return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -195,7 +228,8 @@ public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_PropertyHolder_readonlyString_get") public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyString + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyString return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -206,7 +240,8 @@ public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_PropertyHolder_jsObject_get") public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).jsObject + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -217,7 +252,9 @@ public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_jsObject_set") public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).jsObject = JSObject.bridgeJSLiftParameter(value) + let value = JSObject.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.jsObject = value #else fatalError("Only available on WebAssembly") #endif @@ -227,7 +264,8 @@ public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_sibling_get") public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).sibling + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.sibling return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -238,7 +276,9 @@ public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_PropertyHolder_sibling_set") public func _bjs_PropertyHolder_sibling_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).sibling = PropertyHolder.bridgeJSLiftParameter(value) + let value = PropertyHolder.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.sibling = value #else fatalError("Only available on WebAssembly") #endif @@ -248,7 +288,8 @@ public func _bjs_PropertyHolder_sibling_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_lazyValue_get") public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).lazyValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.lazyValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -259,7 +300,9 @@ public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.lazyValue = value #else fatalError("Only available on WebAssembly") #endif @@ -269,7 +312,8 @@ public func _bjs_PropertyHolder_lazyValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_computedReadonly_get") public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadonly + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.computedReadonly return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -280,7 +324,8 @@ public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_PropertyHolder_computedReadWrite_get") public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.computedReadWrite return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -291,7 +336,9 @@ public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawP @_cdecl("bjs_PropertyHolder_computedReadWrite_set") public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.computedReadWrite = value #else fatalError("Only available on WebAssembly") #endif @@ -301,7 +348,8 @@ public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawP @_cdecl("bjs_PropertyHolder_observedProperty_get") public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).observedProperty + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.observedProperty return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -312,7 +360,9 @@ public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_PropertyHolder_observedProperty_set") public func _bjs_PropertyHolder_observedProperty_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).observedProperty = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.observedProperty = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 6afb7e6b8..ef9beefac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -696,7 +696,8 @@ extension Priority: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { @_cdecl("bjs_processDelegates") public func _bjs_processDelegates() -> Void { #if arch(wasm32) - let ret = processDelegates(_: [AnyMyViewControllerDelegate].bridgeJSStackPop()) + let delegates = [AnyMyViewControllerDelegate].bridgeJSStackPop() + let ret = processDelegates(_: delegates) for __bjs_elem_ret in ret { _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } @@ -710,7 +711,8 @@ public func _bjs_processDelegates() -> Void { @_cdecl("bjs_processDelegatesByName") public func _bjs_processDelegatesByName() -> Void { #if arch(wasm32) - let ret = processDelegatesByName(_: [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter()) + let delegates = [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter() + let ret = processDelegatesByName(_: delegates) for __bjs_kv_ret in ret { __bjs_kv_ret.key.bridgeJSStackPush() _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_kv_ret.value, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) @@ -725,7 +727,8 @@ public func _bjs_processDelegatesByName() -> Void { @_cdecl("bjs_Helper_init") public func _bjs_Helper_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Helper(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = Helper(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -736,7 +739,8 @@ public func _bjs_Helper_init(_ value: Int32) -> UnsafeMutableRawPointer { @_cdecl("bjs_Helper_increment") public func _bjs_Helper_increment(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Helper.bridgeJSLiftParameter(_self).increment() + let _self = Helper.bridgeJSLiftParameter(_self) + _self.increment() #else fatalError("Only available on WebAssembly") #endif @@ -746,7 +750,8 @@ public func _bjs_Helper_increment(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Helper_value_get") public func _bjs_Helper_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Helper.bridgeJSLiftParameter(_self).value + let _self = Helper.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -757,7 +762,9 @@ public func _bjs_Helper_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { @_cdecl("bjs_Helper_value_set") public func _bjs_Helper_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Helper.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = Helper.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -798,7 +805,8 @@ fileprivate func _bjs_Helper_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> @_cdecl("bjs_MyViewController_init") public func _bjs_MyViewController_init(_ delegate: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = MyViewController(delegate: AnyMyViewControllerDelegate.bridgeJSLiftParameter(delegate)) + let delegate = AnyMyViewControllerDelegate.bridgeJSLiftParameter(delegate) + let ret = MyViewController(delegate: delegate) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -809,7 +817,8 @@ public func _bjs_MyViewController_init(_ delegate: Int32) -> UnsafeMutableRawPoi @_cdecl("bjs_MyViewController_triggerEvent") public func _bjs_MyViewController_triggerEvent(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).triggerEvent() + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.triggerEvent() #else fatalError("Only available on WebAssembly") #endif @@ -819,7 +828,9 @@ public func _bjs_MyViewController_triggerEvent(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_MyViewController_updateValue") public func _bjs_MyViewController_updateValue(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).updateValue(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.updateValue(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -829,7 +840,9 @@ public func _bjs_MyViewController_updateValue(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_updateCount") public func _bjs_MyViewController_updateCount(_ _self: UnsafeMutableRawPointer, _ count: Int32) -> Int32 { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).updateCount(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let _self = MyViewController.bridgeJSLiftParameter(_self) + let ret = _self.updateCount(_: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -840,7 +853,10 @@ public func _bjs_MyViewController_updateCount(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_updateLabel") public func _bjs_MyViewController_updateLabel(_ _self: UnsafeMutableRawPointer, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).updateLabel(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength), _: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + let suffix = String.bridgeJSLiftParameter(suffixBytes, suffixLength) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.updateLabel(_: prefix, _: suffix) #else fatalError("Only available on WebAssembly") #endif @@ -850,7 +866,8 @@ public func _bjs_MyViewController_updateLabel(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_checkEvenCount") public func _bjs_MyViewController_checkEvenCount(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).checkEvenCount() + let _self = MyViewController.bridgeJSLiftParameter(_self) + let ret = _self.checkEvenCount() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -861,7 +878,9 @@ public func _bjs_MyViewController_checkEvenCount(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_MyViewController_sendHelper") public func _bjs_MyViewController_sendHelper(_ _self: UnsafeMutableRawPointer, _ helper: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).sendHelper(_: Helper.bridgeJSLiftParameter(helper)) + let helper = Helper.bridgeJSLiftParameter(helper) + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.sendHelper(_: helper) #else fatalError("Only available on WebAssembly") #endif @@ -871,7 +890,8 @@ public func _bjs_MyViewController_sendHelper(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_MyViewController_delegate_get") public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = _bridgeJSUnwrapProtocolExportable(MyViewController.bridgeJSLiftParameter(_self).delegate, "MyViewControllerDelegate") + let _self = MyViewController.bridgeJSLiftParameter(_self) + let ret = _bridgeJSUnwrapProtocolExportable(_self.delegate, "MyViewControllerDelegate") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -882,7 +902,9 @@ public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_MyViewController_delegate_set") public func _bjs_MyViewController_delegate_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).delegate = AnyMyViewControllerDelegate.bridgeJSLiftParameter(value) + let value = AnyMyViewControllerDelegate.bridgeJSLiftParameter(value) + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.delegate = value #else fatalError("Only available on WebAssembly") #endif @@ -892,7 +914,8 @@ public func _bjs_MyViewController_delegate_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_secondDelegate_get") public func _bjs_MyViewController_secondDelegate_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).secondDelegate + let _self = MyViewController.bridgeJSLiftParameter(_self) + let ret = _self.secondDelegate if let ret { _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } else { @@ -907,7 +930,9 @@ public func _bjs_MyViewController_secondDelegate_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_MyViewController_secondDelegate_set") public func _bjs_MyViewController_secondDelegate_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - MyViewController.bridgeJSLiftParameter(_self).secondDelegate = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = MyViewController.bridgeJSLiftParameter(_self) + _self.secondDelegate = value #else fatalError("Only available on WebAssembly") #endif @@ -948,7 +973,8 @@ fileprivate func _bjs_MyViewController_wrap_extern(_ pointer: UnsafeMutableRawPo @_cdecl("bjs_DelegateManager_init") public func _bjs_DelegateManager_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DelegateManager(delegates: [AnyMyViewControllerDelegate].bridgeJSStackPop()) + let delegates = [AnyMyViewControllerDelegate].bridgeJSStackPop() + let ret = DelegateManager(delegates: delegates) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -959,7 +985,8 @@ public func _bjs_DelegateManager_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_DelegateManager_notifyAll") public func _bjs_DelegateManager_notifyAll(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DelegateManager.bridgeJSLiftParameter(_self).notifyAll() + let _self = DelegateManager.bridgeJSLiftParameter(_self) + _self.notifyAll() #else fatalError("Only available on WebAssembly") #endif @@ -969,7 +996,8 @@ public func _bjs_DelegateManager_notifyAll(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_DelegateManager_delegates_get") public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DelegateManager.bridgeJSLiftParameter(_self).delegates + let _self = DelegateManager.bridgeJSLiftParameter(_self) + let ret = _self.delegates for __bjs_elem_ret in ret { _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) } @@ -983,7 +1011,9 @@ public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_DelegateManager_delegates_set") public func _bjs_DelegateManager_delegates_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DelegateManager.bridgeJSLiftParameter(_self).delegates = [AnyMyViewControllerDelegate].bridgeJSStackPop() + let value = [AnyMyViewControllerDelegate].bridgeJSStackPop() + let _self = DelegateManager.bridgeJSLiftParameter(_self) + _self.delegates = value #else fatalError("Only available on WebAssembly") #endif @@ -993,7 +1023,8 @@ public func _bjs_DelegateManager_delegates_set(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_DelegateManager_delegatesByName_get") public func _bjs_DelegateManager_delegatesByName_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DelegateManager.bridgeJSLiftParameter(_self).delegatesByName + let _self = DelegateManager.bridgeJSLiftParameter(_self) + let ret = _self.delegatesByName for __bjs_kv_ret in ret { __bjs_kv_ret.key.bridgeJSStackPush() _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_kv_ret.value, "MyViewControllerDelegate").bridgeJSLowerAsProtocolReturn()) @@ -1008,7 +1039,9 @@ public func _bjs_DelegateManager_delegatesByName_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_DelegateManager_delegatesByName_set") public func _bjs_DelegateManager_delegatesByName_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DelegateManager.bridgeJSLiftParameter(_self).delegatesByName = [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter() + let value = [String: AnyMyViewControllerDelegate].bridgeJSLiftParameter() + let _self = DelegateManager.bridgeJSLiftParameter(_self) + _self.delegatesByName = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift index 78765e3f5..f02cd4019 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift @@ -53,9 +53,10 @@ extension JSTypedClosure where Signature == (any Renderable) -> any Renderable { @_cdecl("invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP") public func _invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = AnyRenderable.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any Renderable) -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(AnyRenderable.bridgeJSLiftParameter(param0)) - return _bridgeJSUnwrapProtocolExportable(result, "Renderable").bridgeJSLowerAsProtocolReturn() + let ret = _bridgeJSUnwrapProtocolExportable(closure(param0), "Renderable") + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -116,9 +117,10 @@ extension JSTypedClosure where Signature == (any Renderable) -> String { @_cdecl("invoke_swift_closure_TestModule_10TestModule10RenderableP_SS") public func _invoke_swift_closure_TestModule_10TestModule10RenderableP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = AnyRenderable.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any Renderable) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(AnyRenderable.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -184,9 +186,10 @@ extension JSTypedClosure where Signature == (Optional) -> String @_cdecl("invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS") public func _invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -247,8 +250,8 @@ extension JSTypedClosure where Signature == () -> any Renderable { public func _invoke_swift_closure_TestModule_10TestModuley_10RenderableP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any Renderable>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return _bridgeJSUnwrapProtocolExportable(result, "Renderable").bridgeJSLowerAsProtocolReturn() + let ret = _bridgeJSUnwrapProtocolExportable(closure(), "Renderable") + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -284,7 +287,9 @@ fileprivate func _extern_render_extern(_ jsObject: Int32) -> Int32 { @_cdecl("bjs_processRenderable") public func _bjs_processRenderable(_ item: Int32, _ transform: Int32) -> Void { #if arch(wasm32) - let ret = processRenderable(_: AnyRenderable.bridgeJSLiftParameter(item), transform: _BJS_Closure_10TestModule10RenderableP_SS.bridgeJSLift(transform)) + let transform = _BJS_Closure_10TestModule10RenderableP_SS.bridgeJSLift(transform) + let item = AnyRenderable.bridgeJSLiftParameter(item) + let ret = processRenderable(_: item, transform: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -295,7 +300,8 @@ public func _bjs_processRenderable(_ item: Int32, _ transform: Int32) -> Void { @_cdecl("bjs_makeRenderableFactory") public func _bjs_makeRenderableFactory(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> Int32 { #if arch(wasm32) - let ret = makeRenderableFactory(defaultName: String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength)) + let defaultName = String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength) + let ret = makeRenderableFactory(defaultName: defaultName) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -306,7 +312,8 @@ public func _bjs_makeRenderableFactory(_ defaultNameBytes: Int32, _ defaultNameL @_cdecl("bjs_roundtripRenderable") public func _bjs_roundtripRenderable(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripRenderable(_: _BJS_Closure_10TestModule10RenderableP_10RenderableP.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModule10RenderableP_10RenderableP.bridgeJSLift(callback) + let ret = roundtripRenderable(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -317,7 +324,8 @@ public func _bjs_roundtripRenderable(_ callback: Int32) -> Int32 { @_cdecl("bjs_processOptionalRenderable") public func _bjs_processOptionalRenderable(_ callback: Int32) -> Void { #if arch(wasm32) - let ret = processOptionalRenderable(_: _BJS_Closure_10TestModuleSq10RenderableP_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq10RenderableP_SS.bridgeJSLift(callback) + let ret = processOptionalRenderable(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -328,7 +336,8 @@ public func _bjs_processOptionalRenderable(_ callback: Int32) -> Void { @_cdecl("bjs_Widget_init") public func _bjs_Widget_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Widget(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Widget(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -339,7 +348,8 @@ public func _bjs_Widget_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeM @_cdecl("bjs_Widget_name_get") public func _bjs_Widget_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Widget.bridgeJSLiftParameter(_self).name + let _self = Widget.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -350,7 +360,9 @@ public func _bjs_Widget_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Widget_name_set") public func _bjs_Widget_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - Widget.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Widget.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift index 0a6b272e9..52fa7a95d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift @@ -92,7 +92,8 @@ fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { @_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)) + let slot = Int.bridgeJSLiftParameter(slot) + let ret = Library.Shelf.Divider(slot: slot) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -158,7 +159,8 @@ public func _bjs_Outer_Inner_init() -> Void { @_cdecl("bjs_Outer_Inner_marker") public func _bjs_Outer_Inner_marker() -> Int32 { #if arch(wasm32) - let ret = Outer.Inner.bridgeJSLiftParameter().marker() + let _self = Outer.Inner.bridgeJSLiftParameter() + let ret = _self.marker() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -279,7 +281,9 @@ public func _bjs_Library_init() -> UnsafeMutableRawPointer { @_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()) + let value = Library.Shelf.Divider.bridgeJSLiftParameter() + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.divider(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 2d5a93c54..9bfff8ebb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -37,7 +37,8 @@ extension Calculator: _BridgedSwiftCaseEnum { @_cdecl("bjs_Calculator_static_square") public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.square(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = Calculator.square(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -48,7 +49,8 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { @_cdecl("bjs_Calculator_static_cube") public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = Calculator.cube(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -94,7 +96,8 @@ extension APIResult: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_APIResult_static_roundtrip") public func _bjs_APIResult_static_roundtrip(_ value: Int32) -> Void { #if arch(wasm32) - let ret = APIResult.roundtrip(value: APIResult.bridgeJSLiftParameter(value)) + let value = APIResult.bridgeJSLiftParameter(value) + let ret = APIResult.roundtrip(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -105,7 +108,8 @@ public func _bjs_APIResult_static_roundtrip(_ value: Int32) -> Void { @_cdecl("bjs_Utils_String_static_uppercase") public func _bjs_Utils_String_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = Utils.String.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let ret = Utils.String.uppercase(_: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -127,7 +131,9 @@ public func _bjs_MathUtils_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_MathUtils_static_subtract") public func _bjs_MathUtils_static_subtract(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.subtract(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.subtract(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -138,7 +144,9 @@ public func _bjs_MathUtils_static_subtract(_ a: Int32, _ b: Int32) -> Int32 { @_cdecl("bjs_MathUtils_static_add") public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -149,7 +157,10 @@ public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { @_cdecl("bjs_MathUtils_multiply") public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.bridgeJSLiftParameter(_self).multiply(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let y = Int.bridgeJSLiftParameter(y) + let x = Int.bridgeJSLiftParameter(x) + let _self = MathUtils.bridgeJSLiftParameter(_self) + let ret = _self.multiply(x: x, y: y) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -160,7 +171,9 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 @_cdecl("bjs_MathUtils_static_divide") public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.divide(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 2d5a93c54..9bfff8ebb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -37,7 +37,8 @@ extension Calculator: _BridgedSwiftCaseEnum { @_cdecl("bjs_Calculator_static_square") public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.square(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = Calculator.square(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -48,7 +49,8 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { @_cdecl("bjs_Calculator_static_cube") public func _bjs_Calculator_static_cube(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.cube(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = Calculator.cube(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -94,7 +96,8 @@ extension APIResult: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_APIResult_static_roundtrip") public func _bjs_APIResult_static_roundtrip(_ value: Int32) -> Void { #if arch(wasm32) - let ret = APIResult.roundtrip(value: APIResult.bridgeJSLiftParameter(value)) + let value = APIResult.bridgeJSLiftParameter(value) + let ret = APIResult.roundtrip(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -105,7 +108,8 @@ public func _bjs_APIResult_static_roundtrip(_ value: Int32) -> Void { @_cdecl("bjs_Utils_String_static_uppercase") public func _bjs_Utils_String_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = Utils.String.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let ret = Utils.String.uppercase(_: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -127,7 +131,9 @@ public func _bjs_MathUtils_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_MathUtils_static_subtract") public func _bjs_MathUtils_static_subtract(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.subtract(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.subtract(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -138,7 +144,9 @@ public func _bjs_MathUtils_static_subtract(_ a: Int32, _ b: Int32) -> Int32 { @_cdecl("bjs_MathUtils_static_add") public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -149,7 +157,10 @@ public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { @_cdecl("bjs_MathUtils_multiply") public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.bridgeJSLiftParameter(_self).multiply(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let y = Int.bridgeJSLiftParameter(y) + let x = Int.bridgeJSLiftParameter(x) + let _self = MathUtils.bridgeJSLiftParameter(_self) + let ret = _self.multiply(x: x, y: y) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -160,7 +171,9 @@ public func _bjs_MathUtils_multiply(_ _self: UnsafeMutableRawPointer, _ x: Int32 @_cdecl("bjs_MathUtils_static_divide") public func _bjs_MathUtils_static_divide(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.divide(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.divide(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index 721c5335a..00e6999c5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -48,7 +48,8 @@ public func _bjs_PropertyEnum_static_enumProperty_get() -> Void { @_cdecl("bjs_PropertyEnum_static_enumProperty_set") public func _bjs_PropertyEnum_static_enumProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyEnum.enumProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyEnum.enumProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -80,7 +81,8 @@ public func _bjs_PropertyEnum_static_computedEnum_get() -> Void { @_cdecl("bjs_PropertyEnum_static_computedEnum_set") public func _bjs_PropertyEnum_static_computedEnum_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyEnum.computedEnum = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyEnum.computedEnum = value #else fatalError("Only available on WebAssembly") #endif @@ -101,7 +103,8 @@ public func _bjs_PropertyNamespace_static_namespaceProperty_get() -> Void { @_cdecl("bjs_PropertyNamespace_static_namespaceProperty_set") public func _bjs_PropertyNamespace_static_namespaceProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyNamespace.namespaceProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyNamespace.namespaceProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -133,7 +136,8 @@ public func _bjs_PropertyNamespace_Nested_static_nestedProperty_get() -> Int32 { @_cdecl("bjs_PropertyNamespace_Nested_static_nestedProperty_set") public func _bjs_PropertyNamespace_Nested_static_nestedProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyNamespace.Nested.nestedProperty = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + PropertyNamespace.Nested.nestedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -165,7 +169,8 @@ public func _bjs_PropertyNamespace_Nested_static_nestedDouble_get() -> Float64 { @_cdecl("bjs_PropertyNamespace_Nested_static_nestedDouble_set") public func _bjs_PropertyNamespace_Nested_static_nestedDouble_set(_ value: Float64) -> Void { #if arch(wasm32) - PropertyNamespace.Nested.nestedDouble = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + PropertyNamespace.Nested.nestedDouble = value #else fatalError("Only available on WebAssembly") #endif @@ -208,7 +213,8 @@ public func _bjs_PropertyClass_static_staticVariable_get() -> Int32 { @_cdecl("bjs_PropertyClass_static_staticVariable_set") public func _bjs_PropertyClass_static_staticVariable_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyClass.staticVariable = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + PropertyClass.staticVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -229,7 +235,8 @@ public func _bjs_PropertyClass_static_jsObjectProperty_get() -> Int32 { @_cdecl("bjs_PropertyClass_static_jsObjectProperty_set") public func _bjs_PropertyClass_static_jsObjectProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyClass.jsObjectProperty = JSObject.bridgeJSLiftParameter(value) + let value = JSObject.bridgeJSLiftParameter(value) + PropertyClass.jsObjectProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -250,7 +257,8 @@ public func _bjs_PropertyClass_static_classVariable_get() -> Void { @_cdecl("bjs_PropertyClass_static_classVariable_set") public func _bjs_PropertyClass_static_classVariable_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.classVariable = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyClass.classVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -271,7 +279,8 @@ public func _bjs_PropertyClass_static_computedProperty_get() -> Void { @_cdecl("bjs_PropertyClass_static_computedProperty_set") public func _bjs_PropertyClass_static_computedProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.computedProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyClass.computedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -303,7 +312,8 @@ public func _bjs_PropertyClass_static_optionalProperty_get() -> Void { @_cdecl("bjs_PropertyClass_static_optionalProperty_set") public func _bjs_PropertyClass_static_optionalProperty_set(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.optionalProperty = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + PropertyClass.optionalProperty = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index 721c5335a..00e6999c5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -48,7 +48,8 @@ public func _bjs_PropertyEnum_static_enumProperty_get() -> Void { @_cdecl("bjs_PropertyEnum_static_enumProperty_set") public func _bjs_PropertyEnum_static_enumProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyEnum.enumProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyEnum.enumProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -80,7 +81,8 @@ public func _bjs_PropertyEnum_static_computedEnum_get() -> Void { @_cdecl("bjs_PropertyEnum_static_computedEnum_set") public func _bjs_PropertyEnum_static_computedEnum_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyEnum.computedEnum = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyEnum.computedEnum = value #else fatalError("Only available on WebAssembly") #endif @@ -101,7 +103,8 @@ public func _bjs_PropertyNamespace_static_namespaceProperty_get() -> Void { @_cdecl("bjs_PropertyNamespace_static_namespaceProperty_set") public func _bjs_PropertyNamespace_static_namespaceProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyNamespace.namespaceProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyNamespace.namespaceProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -133,7 +136,8 @@ public func _bjs_PropertyNamespace_Nested_static_nestedProperty_get() -> Int32 { @_cdecl("bjs_PropertyNamespace_Nested_static_nestedProperty_set") public func _bjs_PropertyNamespace_Nested_static_nestedProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyNamespace.Nested.nestedProperty = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + PropertyNamespace.Nested.nestedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -165,7 +169,8 @@ public func _bjs_PropertyNamespace_Nested_static_nestedDouble_get() -> Float64 { @_cdecl("bjs_PropertyNamespace_Nested_static_nestedDouble_set") public func _bjs_PropertyNamespace_Nested_static_nestedDouble_set(_ value: Float64) -> Void { #if arch(wasm32) - PropertyNamespace.Nested.nestedDouble = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + PropertyNamespace.Nested.nestedDouble = value #else fatalError("Only available on WebAssembly") #endif @@ -208,7 +213,8 @@ public func _bjs_PropertyClass_static_staticVariable_get() -> Int32 { @_cdecl("bjs_PropertyClass_static_staticVariable_set") public func _bjs_PropertyClass_static_staticVariable_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyClass.staticVariable = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + PropertyClass.staticVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -229,7 +235,8 @@ public func _bjs_PropertyClass_static_jsObjectProperty_get() -> Int32 { @_cdecl("bjs_PropertyClass_static_jsObjectProperty_set") public func _bjs_PropertyClass_static_jsObjectProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyClass.jsObjectProperty = JSObject.bridgeJSLiftParameter(value) + let value = JSObject.bridgeJSLiftParameter(value) + PropertyClass.jsObjectProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -250,7 +257,8 @@ public func _bjs_PropertyClass_static_classVariable_get() -> Void { @_cdecl("bjs_PropertyClass_static_classVariable_set") public func _bjs_PropertyClass_static_classVariable_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.classVariable = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyClass.classVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -271,7 +279,8 @@ public func _bjs_PropertyClass_static_computedProperty_get() -> Void { @_cdecl("bjs_PropertyClass_static_computedProperty_set") public func _bjs_PropertyClass_static_computedProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.computedProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + PropertyClass.computedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -303,7 +312,8 @@ public func _bjs_PropertyClass_static_optionalProperty_get() -> Void { @_cdecl("bjs_PropertyClass_static_optionalProperty_set") public func _bjs_PropertyClass_static_optionalProperty_set(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyClass.optionalProperty = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + PropertyClass.optionalProperty = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift index 0760df764..f519c3306 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_checkString") public func _bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { #if arch(wasm32) - checkString(a: String.bridgeJSLiftParameter(aBytes, aLength)) + let a = String.bridgeJSLiftParameter(aBytes, aLength) + checkString(a: a) #else fatalError("Only available on WebAssembly") #endif @@ -12,7 +13,8 @@ public func _bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { @_cdecl("bjs_roundtripString") public func _bjs_roundtripString(_ aBytes: Int32, _ aLength: Int32) -> Void { #if arch(wasm32) - let ret = roundtripString(a: String.bridgeJSLiftParameter(aBytes, aLength)) + let a = String.bridgeJSLiftParameter(aBytes, aLength) + let ret = roundtripString(a: a) 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 8fc6db1a7..1db3c9e5e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -57,7 +57,8 @@ fileprivate func _bjs_struct_lift_Shape_extern() -> Int32 { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Shape(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -114,7 +115,8 @@ fileprivate func _bjs_struct_lift_Widget_extern() -> Int32 { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Widget(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -219,7 +221,9 @@ fileprivate func _bjs_struct_lift_Widget_Bounds_extern() -> Int32 { @_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)) + let height = Int.bridgeJSLiftParameter(height) + let width = Int.bridgeJSLiftParameter(width) + let ret = Widget.Bounds(width: width, height: height) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index abf33ec5e..634333863 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -2,7 +2,8 @@ @_cdecl("bjs_takeGreeter") public func _bjs_takeGreeter(_ greeter: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeGreeter(greeter: Greeter.bridgeJSLiftParameter(greeter)) + let greeter = Greeter.bridgeJSLiftParameter(greeter) + takeGreeter(greeter: greeter) #else fatalError("Only available on WebAssembly") #endif @@ -12,7 +13,8 @@ public func _bjs_takeGreeter(_ greeter: UnsafeMutableRawPointer) -> Void { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -23,7 +25,8 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -34,7 +37,9 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_changeName") public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.changeName(name: name) #else fatalError("Only available on WebAssembly") #endif @@ -44,7 +49,8 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameByte @_cdecl("bjs_Greeter_greetEnthusiastically") public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greetEnthusiastically() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -66,7 +72,8 @@ public func _bjs_Greeter_static_greetAnonymously() -> Void { @_cdecl("bjs_Greeter_name_get") public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -77,7 +84,9 @@ public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -87,7 +96,8 @@ public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes @_cdecl("bjs_Greeter_nameCount_get") public func _bjs_Greeter_nameCount_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).nameCount + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.nameCount return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index c2844aa9c..af740495c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -53,9 +53,10 @@ extension JSTypedClosure where Signature == (HttpStatus) -> HttpStatus { @_cdecl("invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO") public func _invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = HttpStatus.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(HttpStatus) -> HttpStatus>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(HttpStatus.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -119,9 +120,10 @@ extension JSTypedClosure where Signature == (Theme) -> Theme { @_cdecl("invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO") public func _invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = Theme.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> Theme>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -182,9 +184,10 @@ extension JSTypedClosure where Signature == (Animal) -> Animal { @_cdecl("invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV") public func _invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Animal.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(Animal) -> Animal>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Animal.bridgeJSLiftParameter()) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -245,9 +248,10 @@ extension JSTypedClosure where Signature == (Person) -> Person { @_cdecl("invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC") public func _invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) + let param0 = Person.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Person) -> Person>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Person.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -308,9 +312,10 @@ extension JSTypedClosure where Signature == (APIResult) -> APIResult { @_cdecl("invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO") public func _invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = APIResult.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(APIResult) -> APIResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(APIResult.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -371,9 +376,10 @@ extension JSTypedClosure where Signature == (Direction) -> Direction { @_cdecl("invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO") public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Direction.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> Direction>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Direction.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -440,10 +446,11 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = try closure(param0) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -523,10 +530,11 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Int @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = try closure(param0) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -603,9 +611,10 @@ extension JSTypedClosure where Signature == (String) -> String { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSS_SS") public func _invoke_swift_closure_TestModule_10TestModuleSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -666,9 +675,10 @@ extension JSTypedClosure where Signature == (Bool) -> Bool { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSb_Sb") public func _invoke_swift_closure_TestModule_10TestModuleSb_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Bool.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Bool.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -729,9 +739,10 @@ extension JSTypedClosure where Signature == (Double) -> Double { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSd_Sd") public func _invoke_swift_closure_TestModule_10TestModuleSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Float64 { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Double>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Double.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -792,9 +803,10 @@ extension JSTypedClosure where Signature == (Float) -> Float { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSf_Sf") public func _invoke_swift_closure_TestModule_10TestModuleSf_Sf(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float32) -> Float32 { #if arch(wasm32) + let param0 = Float.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Float) -> Float>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Float.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -855,9 +867,10 @@ extension JSTypedClosure where Signature == (Int) -> Int { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSi_Si") public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -918,9 +931,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -982,9 +996,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional @_cdecl("invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") public func _invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1045,9 +1060,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter()) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1108,9 +1124,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1171,9 +1188,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1234,9 +1252,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1298,9 +1317,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1361,9 +1381,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb") public func _invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1424,9 +1445,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1487,9 +1509,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional @_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf") public func _invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1550,9 +1573,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi") public func _invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1588,9 +1612,9 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { return { [callback] (param0: String) async throws(JSException) -> String in #if arch(wasm32) let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -1620,9 +1644,10 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - @_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 param0 = String.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)) + return try await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -1659,9 +1684,9 @@ private enum _BJS_Closure_10TestModuleYaKSb_9APIResultO { return { [callback] (param0: Bool) async throws(JSException) -> APIResult in #if arch(wasm32) let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending APIResult) -> Void>($0) + JSTypedClosure<(sending APIResult) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let param0Value = param0.bridgeJSLowerParameter() let callbackValue = callback.bridgeJSLowerParameter() @@ -1690,9 +1715,10 @@ extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> @_cdecl("invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO") public func _invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Bool.bridgeJSLiftParameter(param0) 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)) + return try await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -1729,9 +1755,9 @@ private enum _BJS_Closure_10TestModuleYaSS_6AnimalV { return { [callback] (param0: String) async -> Animal in #if arch(wasm32) let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Animal) -> Void>($0) + JSTypedClosure<(sending Animal) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -1761,9 +1787,10 @@ extension JSTypedClosure where Signature == (String) async -> Animal { @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) 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)) + return await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -1800,9 +1827,9 @@ private enum _BJS_Closure_10TestModuleYaSS_SS { return { [callback] (param0: String) async -> String in #if arch(wasm32) let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -1832,9 +1859,10 @@ extension JSTypedClosure where Signature == (String) async -> String { @_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 param0 = 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)) + return await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -1881,8 +1909,8 @@ private enum _BJS_Closure_10TestModules6AnimalV_y { } extension JSTypedClosure where Signature == (sending Animal) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Animal) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Animal) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules6AnimalV_y, body: body, fileID: fileID, @@ -1895,8 +1923,9 @@ extension JSTypedClosure where Signature == (sending Animal) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModules6AnimalV_y") public func _invoke_swift_closure_TestModule_10TestModules6AnimalV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Animal.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Animal) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Animal.bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -1942,8 +1971,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { } extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, body: body, fileID: fileID, @@ -1956,8 +1985,9 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { @_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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2003,8 +2033,8 @@ private enum _BJS_Closure_10TestModules9APIResultO_y { } extension JSTypedClosure where Signature == (sending APIResult) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending APIResult) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending APIResult) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules9APIResultO_y, body: body, fileID: fileID, @@ -2017,8 +2047,9 @@ extension JSTypedClosure where Signature == (sending APIResult) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModules9APIResultO_y") public func _invoke_swift_closure_TestModule_10TestModules9APIResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = APIResult.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending APIResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(APIResult.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2065,8 +2096,8 @@ private enum _BJS_Closure_10TestModulesSS_y { } extension JSTypedClosure where Signature == (sending String) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSS_y, body: body, fileID: fileID, @@ -2079,8 +2110,9 @@ extension JSTypedClosure where Signature == (sending String) -> Void { @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2228,7 +2260,8 @@ fileprivate func _bjs_struct_lift_Animal_extern() -> Int32 { @_cdecl("bjs_Animal_init") public func _bjs_Animal_init(_ typeBytes: Int32, _ typeLength: Int32) -> Void { #if arch(wasm32) - let ret = Animal(type: String.bridgeJSLiftParameter(typeBytes, typeLength)) + let type = String.bridgeJSLiftParameter(typeBytes, typeLength) + let ret = Animal(type: type) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2239,7 +2272,8 @@ public func _bjs_Animal_init(_ typeBytes: Int32, _ typeLength: Int32) -> Void { @_cdecl("bjs_roundtripAnimal") public func _bjs_roundtripAnimal(_ animalClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripAnimal(_: _BJS_Closure_10TestModule6AnimalV_6AnimalV.bridgeJSLift(animalClosure)) + let animalClosure = _BJS_Closure_10TestModule6AnimalV_6AnimalV.bridgeJSLift(animalClosure) + let ret = roundtripAnimal(_: animalClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2250,7 +2284,8 @@ public func _bjs_roundtripAnimal(_ animalClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalAnimal") public func _bjs_roundtripOptionalAnimal(_ animalClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalAnimal(_: _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV.bridgeJSLift(animalClosure)) + let animalClosure = _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV.bridgeJSLift(animalClosure) + let ret = roundtripOptionalAnimal(_: animalClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2261,7 +2296,8 @@ public func _bjs_roundtripOptionalAnimal(_ animalClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripString") public func _bjs_roundtripString(_ stringClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripString(_: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(stringClosure)) + let stringClosure = _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(stringClosure) + let ret = roundtripString(_: stringClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2272,7 +2308,8 @@ public func _bjs_roundtripString(_ stringClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripInt") public func _bjs_roundtripInt(_ intClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripInt(_: _BJS_Closure_10TestModuleSi_Si.bridgeJSLift(intClosure)) + let intClosure = _BJS_Closure_10TestModuleSi_Si.bridgeJSLift(intClosure) + let ret = roundtripInt(_: intClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2283,7 +2320,8 @@ public func _bjs_roundtripInt(_ intClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripBool") public func _bjs_roundtripBool(_ boolClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripBool(_: _BJS_Closure_10TestModuleSb_Sb.bridgeJSLift(boolClosure)) + let boolClosure = _BJS_Closure_10TestModuleSb_Sb.bridgeJSLift(boolClosure) + let ret = roundtripBool(_: boolClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2294,7 +2332,8 @@ public func _bjs_roundtripBool(_ boolClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripFloat") public func _bjs_roundtripFloat(_ floatClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripFloat(_: _BJS_Closure_10TestModuleSf_Sf.bridgeJSLift(floatClosure)) + let floatClosure = _BJS_Closure_10TestModuleSf_Sf.bridgeJSLift(floatClosure) + let ret = roundtripFloat(_: floatClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2305,7 +2344,8 @@ public func _bjs_roundtripFloat(_ floatClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripDouble") public func _bjs_roundtripDouble(_ doubleClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripDouble(_: _BJS_Closure_10TestModuleSd_Sd.bridgeJSLift(doubleClosure)) + let doubleClosure = _BJS_Closure_10TestModuleSd_Sd.bridgeJSLift(doubleClosure) + let ret = roundtripDouble(_: doubleClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2316,7 +2356,8 @@ public func _bjs_roundtripDouble(_ doubleClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalString") public func _bjs_roundtripOptionalString(_ stringClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalString(_: _BJS_Closure_10TestModuleSqSS_SqSS.bridgeJSLift(stringClosure)) + let stringClosure = _BJS_Closure_10TestModuleSqSS_SqSS.bridgeJSLift(stringClosure) + let ret = roundtripOptionalString(_: stringClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2327,7 +2368,8 @@ public func _bjs_roundtripOptionalString(_ stringClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalInt") public func _bjs_roundtripOptionalInt(_ intClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalInt(_: _BJS_Closure_10TestModuleSqSi_SqSi.bridgeJSLift(intClosure)) + let intClosure = _BJS_Closure_10TestModuleSqSi_SqSi.bridgeJSLift(intClosure) + let ret = roundtripOptionalInt(_: intClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2338,7 +2380,8 @@ public func _bjs_roundtripOptionalInt(_ intClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalBool") public func _bjs_roundtripOptionalBool(_ boolClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalBool(_: _BJS_Closure_10TestModuleSqSb_SqSb.bridgeJSLift(boolClosure)) + let boolClosure = _BJS_Closure_10TestModuleSqSb_SqSb.bridgeJSLift(boolClosure) + let ret = roundtripOptionalBool(_: boolClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2349,7 +2392,8 @@ public func _bjs_roundtripOptionalBool(_ boolClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalFloat") public func _bjs_roundtripOptionalFloat(_ floatClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalFloat(_: _BJS_Closure_10TestModuleSqSf_SqSf.bridgeJSLift(floatClosure)) + let floatClosure = _BJS_Closure_10TestModuleSqSf_SqSf.bridgeJSLift(floatClosure) + let ret = roundtripOptionalFloat(_: floatClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2360,7 +2404,8 @@ public func _bjs_roundtripOptionalFloat(_ floatClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalDouble") public func _bjs_roundtripOptionalDouble(_ doubleClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalDouble(_: _BJS_Closure_10TestModuleSqSd_SqSd.bridgeJSLift(doubleClosure)) + let doubleClosure = _BJS_Closure_10TestModuleSqSd_SqSd.bridgeJSLift(doubleClosure) + let ret = roundtripOptionalDouble(_: doubleClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2371,7 +2416,8 @@ public func _bjs_roundtripOptionalDouble(_ doubleClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripPerson") public func _bjs_roundtripPerson(_ personClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripPerson(_: _BJS_Closure_10TestModule6PersonC_6PersonC.bridgeJSLift(personClosure)) + let personClosure = _BJS_Closure_10TestModule6PersonC_6PersonC.bridgeJSLift(personClosure) + let ret = roundtripPerson(_: personClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2382,7 +2428,8 @@ public func _bjs_roundtripPerson(_ personClosure: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalPerson") public func _bjs_roundtripOptionalPerson(_ personClosure: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalPerson(_: _BJS_Closure_10TestModuleSq6PersonC_Sq6PersonC.bridgeJSLift(personClosure)) + let personClosure = _BJS_Closure_10TestModuleSq6PersonC_Sq6PersonC.bridgeJSLift(personClosure) + let ret = roundtripOptionalPerson(_: personClosure) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2404,7 +2451,8 @@ public func _bjs_makeThrowingParser() -> Int32 { @_cdecl("bjs_validateWith") public func _bjs_validateWith(_ validate: Int32) -> Void { #if arch(wasm32) - validateWith(_: _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(validate)) + let validate = _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(validate) + validateWith(_: validate) #else fatalError("Only available on WebAssembly") #endif @@ -2458,7 +2506,8 @@ public func _bjs_makeResultLoader() -> Int32 { @_cdecl("bjs_roundtripDirection") public func _bjs_roundtripDirection(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripDirection(_: _BJS_Closure_10TestModule9DirectionO_9DirectionO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModule9DirectionO_9DirectionO.bridgeJSLift(callback) + let ret = roundtripDirection(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2469,7 +2518,8 @@ public func _bjs_roundtripDirection(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripTheme") public func _bjs_roundtripTheme(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripTheme(_: _BJS_Closure_10TestModule5ThemeO_5ThemeO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModule5ThemeO_5ThemeO.bridgeJSLift(callback) + let ret = roundtripTheme(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2480,7 +2530,8 @@ public func _bjs_roundtripTheme(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripHttpStatus") public func _bjs_roundtripHttpStatus(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripHttpStatus(_: _BJS_Closure_10TestModule10HttpStatusO_10HttpStatusO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModule10HttpStatusO_10HttpStatusO.bridgeJSLift(callback) + let ret = roundtripHttpStatus(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2491,7 +2542,8 @@ public func _bjs_roundtripHttpStatus(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripAPIResult") public func _bjs_roundtripAPIResult(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripAPIResult(_: _BJS_Closure_10TestModule9APIResultO_9APIResultO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModule9APIResultO_9APIResultO.bridgeJSLift(callback) + let ret = roundtripAPIResult(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2502,7 +2554,8 @@ public func _bjs_roundtripAPIResult(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalDirection") public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalDirection(_: _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback) + let ret = roundtripOptionalDirection(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2513,7 +2566,8 @@ public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalTheme") public func _bjs_roundtripOptionalTheme(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalTheme(_: _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO.bridgeJSLift(callback) + let ret = roundtripOptionalTheme(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2524,7 +2578,8 @@ public func _bjs_roundtripOptionalTheme(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalHttpStatus") public func _bjs_roundtripOptionalHttpStatus(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalHttpStatus(_: _BJS_Closure_10TestModuleSq10HttpStatusO_Sq10HttpStatusO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq10HttpStatusO_Sq10HttpStatusO.bridgeJSLift(callback) + let ret = roundtripOptionalHttpStatus(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2535,7 +2590,8 @@ public func _bjs_roundtripOptionalHttpStatus(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalAPIResult") public func _bjs_roundtripOptionalAPIResult(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalAPIResult(_: _BJS_Closure_10TestModuleSq9APIResultO_Sq9APIResultO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq9APIResultO_Sq9APIResultO.bridgeJSLift(callback) + let ret = roundtripOptionalAPIResult(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2546,7 +2602,8 @@ public func _bjs_roundtripOptionalAPIResult(_ callback: Int32) -> Int32 { @_cdecl("bjs_roundtripOptionalDirection") public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripOptionalDirection(_: _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback)) + let callback = _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback) + let ret = roundtripOptionalDirection(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2557,7 +2614,8 @@ public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { @_cdecl("bjs_Person_init") public func _bjs_Person_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Person(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Person(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -2599,7 +2657,8 @@ fileprivate func _bjs_Person_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> @_cdecl("bjs_TestProcessor_init") public func _bjs_TestProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TestProcessor(transform: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(transform)) + let transform = _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(transform) + let ret = TestProcessor(transform: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift index 6f133d748..3634ad491 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift @@ -59,10 +59,11 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = try closure(param0) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -136,9 +137,10 @@ extension JSTypedClosure where Signature == (Int) -> Int { @_cdecl("invoke_swift_closure_TestModule_10TestModuleSi_Si") public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -174,9 +176,9 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { return { [callback] (param0: String) async throws(JSException) -> String in #if arch(wasm32) let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -206,9 +208,10 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - @_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 param0 = String.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)) + return try await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -255,8 +258,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { } extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, body: body, fileID: fileID, @@ -269,8 +272,9 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { @_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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -317,8 +321,8 @@ private enum _BJS_Closure_10TestModulesSS_y { } extension JSTypedClosure where Signature == (sending String) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) -> Self { + Self( makeClosure: make_swift_closure_TestModule_10TestModulesSS_y, body: body, fileID: fileID, @@ -331,8 +335,9 @@ extension JSTypedClosure where Signature == (sending String) -> Void { @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -342,7 +347,8 @@ public func _invoke_swift_closure_TestModule_10TestModulesSS_y(_ boxPtr: UnsafeM @_cdecl("bjs_runValidator") public func _bjs_runValidator(_ cb: Int32) -> Void { #if arch(wasm32) - runValidator(_: _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(cb)) + let cb = _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(cb) + runValidator(_: cb) #else fatalError("Only available on WebAssembly") #endif @@ -352,7 +358,8 @@ public func _bjs_runValidator(_ cb: Int32) -> Void { @_cdecl("bjs_loadEach") public func _bjs_loadEach(_ fetch: Int32) -> Void { #if arch(wasm32) - loadEach(_: _BJS_Closure_10TestModuleYaKSS_SS.bridgeJSLift(fetch)) + let fetch = _BJS_Closure_10TestModuleYaKSS_SS.bridgeJSLift(fetch) + loadEach(_: fetch) #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index 2fcab7cb0..cdb672a18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -701,6 +701,35 @@ "returnType" : { "string" : { + } + } + }, + { + "abiName" : "bjs_Vector2D_dot", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "dot", + "parameters" : [ + { + "label" : "_", + "name" : "components", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "double" : { + } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index b4e54961c..8797a79b2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -59,7 +59,12 @@ fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { @_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)) + let optFlag = Optional.bridgeJSLiftParameter(optFlagIsSome, optFlagValue) + let optCount = Optional.bridgeJSLiftParameter(optCountIsSome, optCountValue) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let y = Double.bridgeJSLiftParameter(y) + let x = Double.bridgeJSLiftParameter(x) + let ret = DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -358,7 +363,8 @@ public func _bjs_ConfigStruct_static_defaultConfig_get() -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + ConfigStruct.defaultConfig = value #else fatalError("Only available on WebAssembly") #endif @@ -379,7 +385,8 @@ public func _bjs_ConfigStruct_static_timeout_get() -> Float64 { @_cdecl("bjs_ConfigStruct_static_timeout_set") public func _bjs_ConfigStruct_static_timeout_set(_ value: Float64) -> Void { #if arch(wasm32) - ConfigStruct.timeout = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + ConfigStruct.timeout = value #else fatalError("Only available on WebAssembly") #endif @@ -400,7 +407,8 @@ public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { @_cdecl("bjs_ConfigStruct_static_update") public func _bjs_ConfigStruct_static_update(_ timeout: Float64) -> Float64 { #if arch(wasm32) - let ret = ConfigStruct.update(_: Double.bridgeJSLiftParameter(timeout)) + let timeout = Double.bridgeJSLiftParameter(timeout) + let ret = ConfigStruct.update(_: timeout) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -507,7 +515,8 @@ fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 { @_cdecl("bjs_Vector2D_magnitude") public func _bjs_Vector2D_magnitude() -> Float64 { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().magnitude() + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.magnitude() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -518,7 +527,9 @@ public func _bjs_Vector2D_magnitude() -> Float64 { @_cdecl("bjs_Vector2D_scaled") public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + let factor = Double.bridgeJSLiftParameter(factor) + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.scaled(by: factor) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -529,7 +540,21 @@ public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { @_cdecl("bjs_Vector2D_describe") public func _bjs_Vector2D_describe() -> Void { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().describe() + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Vector2D_dot") +@_cdecl("bjs_Vector2D_dot") +public func _bjs_Vector2D_dot() -> Float64 { + #if arch(wasm32) + let components = [Double].bridgeJSStackPop() + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.dot(_: components) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -540,7 +565,8 @@ public func _bjs_Vector2D_describe() -> Void { @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { #if arch(wasm32) - let ret = roundtrip(_: Person.bridgeJSLiftParameter()) + let session = Person.bridgeJSLiftParameter() + let ret = roundtrip(_: session) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -551,7 +577,8 @@ public func _bjs_roundtrip() -> Void { @_cdecl("bjs_roundtripContainer") public func _bjs_roundtripContainer() -> Void { #if arch(wasm32) - let ret = roundtripContainer(_: Container.bridgeJSLiftParameter()) + let container = Container.bridgeJSLiftParameter() + let ret = roundtripContainer(_: container) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -562,7 +589,8 @@ public func _bjs_roundtripContainer() -> Void { @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -573,7 +601,8 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -584,7 +613,8 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_name_get") public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -595,7 +625,9 @@ public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift index c86b122a1..076e25b7d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift @@ -52,8 +52,9 @@ extension JSTypedClosure where Signature == (JSPublicEvent) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y") public func _invoke_swift_closure_TestModule_10TestModule13JSPublicEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = JSPublicEvent.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSPublicEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSPublicEvent.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -113,8 +114,9 @@ extension JSTypedClosure where Signature == (JSPackageEvent) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y") public func _invoke_swift_closure_TestModule_10TestModule14JSPackageEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = JSPackageEvent.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSPackageEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSPackageEvent.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -174,8 +176,9 @@ extension JSTypedClosure where Signature == (JSInternalEvent) -> Void { @_cdecl("invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y") public func _invoke_swift_closure_TestModule_10TestModule15JSInternalEventC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = JSInternalEvent.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSInternalEvent) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSInternalEvent.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift index 69011da18..4179da090 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift @@ -56,7 +56,12 @@ fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { @_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 = PointerFields(raw: UnsafeRawPointer.bridgeJSLiftParameter(raw), mutRaw: UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw), opaque: OpaquePointer.bridgeJSLiftParameter(opaque), ptr: UnsafePointer.bridgeJSLiftParameter(ptr), mutPtr: UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr)) + let mutPtr = UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr) + let ptr = UnsafePointer.bridgeJSLiftParameter(ptr) + let opaque = OpaquePointer.bridgeJSLiftParameter(opaque) + let mutRaw = UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw) + let raw = UnsafeRawPointer.bridgeJSLiftParameter(raw) + let ret = PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -67,7 +72,8 @@ public func _bjs_PointerFields_init(_ raw: UnsafeMutableRawPointer, _ mutRaw: Un @_cdecl("bjs_takeUnsafeRawPointer") public func _bjs_takeUnsafeRawPointer(_ p: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeUnsafeRawPointer(_: UnsafeRawPointer.bridgeJSLiftParameter(p)) + let p = UnsafeRawPointer.bridgeJSLiftParameter(p) + takeUnsafeRawPointer(_: p) #else fatalError("Only available on WebAssembly") #endif @@ -77,7 +83,8 @@ public func _bjs_takeUnsafeRawPointer(_ p: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_takeUnsafeMutableRawPointer") public func _bjs_takeUnsafeMutableRawPointer(_ p: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeUnsafeMutableRawPointer(_: UnsafeMutableRawPointer.bridgeJSLiftParameter(p)) + let p = UnsafeMutableRawPointer.bridgeJSLiftParameter(p) + takeUnsafeMutableRawPointer(_: p) #else fatalError("Only available on WebAssembly") #endif @@ -87,7 +94,8 @@ public func _bjs_takeUnsafeMutableRawPointer(_ p: UnsafeMutableRawPointer) -> Vo @_cdecl("bjs_takeOpaquePointer") public func _bjs_takeOpaquePointer(_ p: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeOpaquePointer(_: OpaquePointer.bridgeJSLiftParameter(p)) + let p = OpaquePointer.bridgeJSLiftParameter(p) + takeOpaquePointer(_: p) #else fatalError("Only available on WebAssembly") #endif @@ -97,7 +105,8 @@ public func _bjs_takeOpaquePointer(_ p: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_takeUnsafePointer") public func _bjs_takeUnsafePointer(_ p: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeUnsafePointer(_: UnsafePointer.bridgeJSLiftParameter(p)) + let p = UnsafePointer.bridgeJSLiftParameter(p) + takeUnsafePointer(_: p) #else fatalError("Only available on WebAssembly") #endif @@ -107,7 +116,8 @@ public func _bjs_takeUnsafePointer(_ p: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_takeUnsafeMutablePointer") public func _bjs_takeUnsafeMutablePointer(_ p: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - takeUnsafeMutablePointer(_: UnsafeMutablePointer.bridgeJSLiftParameter(p)) + let p = UnsafeMutablePointer.bridgeJSLiftParameter(p) + takeUnsafeMutablePointer(_: p) #else fatalError("Only available on WebAssembly") #endif @@ -172,7 +182,8 @@ public func _bjs_returnUnsafeMutablePointer() -> UnsafeMutableRawPointer { @_cdecl("bjs_roundTripPointerFields") public func _bjs_roundTripPointerFields() -> Void { #if arch(wasm32) - let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) + let value = PointerFields.bridgeJSLiftParameter() + let ret = roundTripPointerFields(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index fe1fa7b54..9fda637df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -405,8 +405,8 @@ export async function createInstantiator(options, swift) { }.bind(instance1); instance1.multiply = function(a, b) { structHelpers.M10TestModuleT14MathOperations.lower(this); - const ret1 = instance.exports.bjs_MathOperations_multiply(a, b); - return ret1; + const ret = instance.exports.bjs_MathOperations_multiply(a, b); + return ret; }.bind(instance1); return instance1; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js index d031ff64b..85cdb44d4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js @@ -59,10 +59,10 @@ export async function createInstantiator(options, swift) { const instance1 = { label: string }; instance1.describeShelf = function() { structHelpers.M10TestModuleT7LibraryT5Shelf.lower(this); - const ret = instance.exports.bjs_Library_Shelf_describeShelf(); - const ret1 = tmpRetString; + instance.exports.bjs_Library_Shelf_describeShelf(); + const ret = tmpRetString; tmpRetString = undefined; - return ret1; + return ret; }.bind(instance1); return instance1; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js index 6cc339d24..a9091e925 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js @@ -43,10 +43,10 @@ export async function createInstantiator(options, swift) { const instance1 = { label: string }; instance1.describeCrate = function() { structHelpers.M10TestModuleT5DepotT5Crate.lower(this); - const ret = instance.exports.bjs_Depot_Crate_describeCrate(); - const ret1 = tmpRetString; + instance.exports.bjs_Depot_Crate_describeCrate(); + const ret = tmpRetString; tmpRetString = undefined; - return ret1; + return ret; }.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 3b394fb06..48590c063 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -49,6 +49,7 @@ export interface Vector2D { magnitude(): number; scaled(factor: number): Vector2D; describe(): string; + dot(components: number[]): number; } 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 fc3d9ddbb..0bfd7c2e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -385,6 +385,7 @@ export async function createInstantiator(options, swift) { }, }; const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); + const __bjs_codec_Array_Double = __bjs_arrayCodec(__bjs_primitiveCodecs.Double); const __bjs_createStructHelpers_M10TestModuleT9DataPoint = () => ({ lower: (value) => { @@ -515,16 +516,22 @@ export async function createInstantiator(options, swift) { }.bind(instance1); instance1.scaled = function(factor) { structHelpers.M10TestModuleT8Vector2D.lower(this); - const ret1 = instance.exports.bjs_Vector2D_scaled(factor); + instance.exports.bjs_Vector2D_scaled(factor); const structValue = structHelpers.M10TestModuleT8Vector2D.lift(); return structValue; }.bind(instance1); instance1.describe = function() { structHelpers.M10TestModuleT8Vector2D.lower(this); - const ret2 = instance.exports.bjs_Vector2D_describe(); - const ret3 = tmpRetString; + instance.exports.bjs_Vector2D_describe(); + const ret = tmpRetString; tmpRetString = undefined; - return ret3; + return ret; + }.bind(instance1); + instance1.dot = function(components) { + structHelpers.M10TestModuleT8Vector2D.lower(this); + __bjs_codec_Array_Double.lower(components); + const ret = instance.exports.bjs_Vector2D_dot(); + return ret; }.bind(instance1); return instance1; } diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index 91638a428..dd2230ae2 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -107,7 +107,8 @@ public func _bjs_GlobalStaticPropertyNamespace_static_namespaceProperty_get() -> @_cdecl("bjs_GlobalStaticPropertyNamespace_static_namespaceProperty_set") public func _bjs_GlobalStaticPropertyNamespace_static_namespaceProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - GlobalStaticPropertyNamespace.namespaceProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + GlobalStaticPropertyNamespace.namespaceProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -139,7 +140,8 @@ public func _bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedPro @_cdecl("bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedProperty_set") public func _bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - GlobalStaticPropertyNamespace.NestedProperties.nestedProperty = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + GlobalStaticPropertyNamespace.NestedProperties.nestedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -171,7 +173,8 @@ public func _bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedDou @_cdecl("bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedDouble_set") public func _bjs_GlobalStaticPropertyNamespace_NestedProperties_static_nestedDouble_set(_ value: Float64) -> Void { #if arch(wasm32) - GlobalStaticPropertyNamespace.NestedProperties.nestedDouble = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + GlobalStaticPropertyNamespace.NestedProperties.nestedDouble = value #else fatalError("Only available on WebAssembly") #endif @@ -192,7 +195,9 @@ public func _bjs_GlobalNetworking_API_TestHTTPServer_init() -> UnsafeMutableRawP @_cdecl("bjs_GlobalNetworking_API_TestHTTPServer_call") public func _bjs_GlobalNetworking_API_TestHTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - GlobalNetworking.API.TestHTTPServer.bridgeJSLiftParameter(_self).call(_: GlobalNetworking.API.CallMethod.bridgeJSLiftParameter(method)) + let method = GlobalNetworking.API.CallMethod.bridgeJSLiftParameter(method) + let _self = GlobalNetworking.API.TestHTTPServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -244,7 +249,9 @@ public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_init() -> Un @_cdecl("bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call") public func _bjs_GlobalNetworking_APIV2_Internal_TestInternalServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Internal.TestInternalServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedServerMethod.bridgeJSLiftParameter(method)) + let method = Internal.SupportedServerMethod.bridgeJSLiftParameter(method) + let _self = Internal.TestInternalServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -296,7 +303,9 @@ public func _bjs_GlobalUtils_PublicConverter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_GlobalUtils_PublicConverter_toString") public func _bjs_GlobalUtils_PublicConverter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -307,7 +316,8 @@ public func _bjs_GlobalUtils_PublicConverter_toString(_ _self: UnsafeMutableRawP @_cdecl("bjs_GlobalUtils_PublicConverter_precision_get") public func _bjs_GlobalUtils_PublicConverter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).precision + let _self = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self) + let ret = _self.precision return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -318,7 +328,9 @@ public func _bjs_GlobalUtils_PublicConverter_precision_get(_ _self: UnsafeMutabl @_cdecl("bjs_GlobalUtils_PublicConverter_precision_set") public func _bjs_GlobalUtils_PublicConverter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = GlobalUtils.PublicConverter.bridgeJSLiftParameter(_self) + _self.precision = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift index 72a8dfdd4..6aa082880 100644 --- a/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSIdentityTests/Generated/BridgeJS.swift @@ -75,7 +75,8 @@ public func _bjs_resetRetainLeakDeinits() -> Void { @_cdecl("bjs_setupArrayPool") public func _bjs_setupArrayPool(_ count: Int32) -> Void { #if arch(wasm32) - setupArrayPool(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + setupArrayPool(_: count) #else fatalError("Only available on WebAssembly") #endif @@ -96,7 +97,8 @@ public func _bjs_getArrayPool() -> Void { @_cdecl("bjs_getArrayPoolElement") public func _bjs_getArrayPoolElement(_ index: Int32) -> Void { #if arch(wasm32) - let ret = getArrayPoolElement(_: Int.bridgeJSLiftParameter(index)) + let index = Int.bridgeJSLiftParameter(index) + let ret = getArrayPoolElement(_: index) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -138,7 +140,8 @@ public func _bjs_clearArrayPool() -> Void { @_cdecl("bjs_IdentityTestSubject_init") public func _bjs_IdentityTestSubject_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = IdentityTestSubject(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = IdentityTestSubject(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -149,7 +152,8 @@ public func _bjs_IdentityTestSubject_init(_ value: Int32) -> UnsafeMutableRawPoi @_cdecl("bjs_IdentityTestSubject_value_get") public func _bjs_IdentityTestSubject_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = IdentityTestSubject.bridgeJSLiftParameter(_self).value + let _self = IdentityTestSubject.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -160,7 +164,9 @@ public func _bjs_IdentityTestSubject_value_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_IdentityTestSubject_value_set") public func _bjs_IdentityTestSubject_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - IdentityTestSubject.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = IdentityTestSubject.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -170,7 +176,8 @@ public func _bjs_IdentityTestSubject_value_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_IdentityTestSubject_currentValue_get") public func _bjs_IdentityTestSubject_currentValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = IdentityTestSubject.bridgeJSLiftParameter(_self).currentValue + let _self = IdentityTestSubject.bridgeJSLiftParameter(_self) + let ret = _self.currentValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -212,7 +219,8 @@ fileprivate func _bjs_IdentityTestSubject_wrap_extern(_ pointer: UnsafeMutableRa @_cdecl("bjs_RetainLeakSubject_init") public func _bjs_RetainLeakSubject_init(_ tag: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = RetainLeakSubject(tag: Int.bridgeJSLiftParameter(tag)) + let tag = Int.bridgeJSLiftParameter(tag) + let ret = RetainLeakSubject(tag: tag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -223,7 +231,8 @@ public func _bjs_RetainLeakSubject_init(_ tag: Int32) -> UnsafeMutableRawPointer @_cdecl("bjs_RetainLeakSubject_tag_get") public func _bjs_RetainLeakSubject_tag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = RetainLeakSubject.bridgeJSLiftParameter(_self).tag + let _self = RetainLeakSubject.bridgeJSLiftParameter(_self) + let ret = _self.tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -234,7 +243,9 @@ public func _bjs_RetainLeakSubject_tag_get(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_RetainLeakSubject_tag_set") public func _bjs_RetainLeakSubject_tag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - RetainLeakSubject.bridgeJSLiftParameter(_self).tag = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = RetainLeakSubject.bridgeJSLiftParameter(_self) + _self.tag = value #else fatalError("Only available on WebAssembly") #endif @@ -275,7 +286,8 @@ fileprivate func _bjs_RetainLeakSubject_wrap_extern(_ pointer: UnsafeMutableRawP @_cdecl("bjs_ArrayIdentityElement_init") public func _bjs_ArrayIdentityElement_init(_ tag: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ArrayIdentityElement(tag: Int.bridgeJSLiftParameter(tag)) + let tag = Int.bridgeJSLiftParameter(tag) + let ret = ArrayIdentityElement(tag: tag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -286,7 +298,8 @@ public func _bjs_ArrayIdentityElement_init(_ tag: Int32) -> UnsafeMutableRawPoin @_cdecl("bjs_ArrayIdentityElement_tag_get") public func _bjs_ArrayIdentityElement_tag_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ArrayIdentityElement.bridgeJSLiftParameter(_self).tag + let _self = ArrayIdentityElement.bridgeJSLiftParameter(_self) + let ret = _self.tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -297,7 +310,9 @@ public func _bjs_ArrayIdentityElement_tag_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ArrayIdentityElement_tag_set") public func _bjs_ArrayIdentityElement_tag_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - ArrayIdentityElement.bridgeJSLiftParameter(_self).tag = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = ArrayIdentityElement.bridgeJSLiftParameter(_self) + _self.tag = value #else fatalError("Only available on WebAssembly") #endif diff --git a/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift b/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift index 678981ede..12a5acca0 100644 --- a/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift @@ -76,6 +76,14 @@ enum AsyncRecorderState { nonisolated(unsafe) static var lastRecorded: String = "" } +@JS func makeAsyncArraySum() -> JSTypedClosure<([Int]) async -> Int> { + JSTypedClosure { values in values.reduce(0, +) } +} + +@JS func awaitArraySum(_ sum: ([Int]) async -> Int) async -> Int { + await sum([1, 2, 3]) +} + // MARK: - XCTest entry point final class ClosureAsyncTests: XCTestCase { diff --git a/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift b/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift index 8078ed777..d6bb9c839 100644 --- a/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift @@ -25,26 +25,26 @@ import JavaScriptKit _ value: JSObject, _ transform: JSTypedClosure<(JSObject) -> JSObject> ) throws(JSException) -> JSObject - // @JSFunction static func jsApplyArrayInt( - // _ value: [Int], - // _ transform: JSTypedClosure<([Int]) -> [Int]> - // ) throws(JSException) -> [Int] - // @JSFunction static func jsApplyArrayDouble( - // _ value: [Double], - // _ transform: JSTypedClosure<([Double]) -> [Double]> - // ) throws(JSException) -> [Double] - // @JSFunction static func jsApplyArrayString( - // _ value: [String], - // _ transform: JSTypedClosure<([String]) -> [String]> - // ) throws(JSException) -> [String] - // @JSFunction static func jsApplyArrayJSValue( - // _ value: [JSValue], - // _ transform: JSTypedClosure<([JSValue]) -> [JSValue]> - // ) throws(JSException) -> [JSValue] - // @JSFunction static func jsApplyArrayJSObject( - // _ value: [JSObject], - // _ transform: JSTypedClosure<([JSObject]) -> [JSObject]> - // ) throws(JSException) -> [JSObject] + @JSFunction static func jsApplyArrayInt( + _ value: [Int], + _ transform: JSTypedClosure<([Int]) -> [Int]> + ) throws(JSException) -> [Int] + @JSFunction static func jsApplyArrayDouble( + _ value: [Double], + _ transform: JSTypedClosure<([Double]) -> [Double]> + ) throws(JSException) -> [Double] + @JSFunction static func jsApplyArrayString( + _ value: [String], + _ transform: JSTypedClosure<([String]) -> [String]> + ) throws(JSException) -> [String] + @JSFunction static func jsApplyArrayJSValue( + _ value: [JSValue], + _ transform: JSTypedClosure<([JSValue]) -> [JSValue]> + ) throws(JSException) -> [JSValue] + @JSFunction static func jsApplyArrayJSObject( + _ value: [JSObject], + _ transform: JSTypedClosure<([JSObject]) -> [JSObject]> + ) throws(JSException) -> [JSObject] @JSFunction static func jsMakeIntToInt(_ base: Int) throws(JSException) -> (Int) -> Int @JSFunction static func jsMakeDoubleToDouble(_ base: Double) throws(JSException) -> (Double) -> Double @@ -85,6 +85,10 @@ import JavaScriptKit @JS static func makeJSStringToString(_ prefix: String) -> JSTypedClosure<(String) -> String> { return JSTypedClosure { prefix + $0 } } + + @JS static func makeArrayDifference() -> ([Int], [Int]) -> Int { + { first, second in first.reduce(0, +) - second.reduce(0, +) } + } } final class ClosureSupportTests: XCTestCase { @@ -148,43 +152,43 @@ final class ClosureSupportTests: XCTestCase { XCTAssertEqual(result, obj) } - // func testClosureParameterArrayIntToArrayInt() throws { - // let transform = JSTypedClosure<([Int]) -> [Int]> { $0 } - // defer { transform.release() } - // let result = try ClosureSupportImports.jsApplyArrayInt([1, 2, 3], transform) - // XCTAssertEqual(result, [1, 2, 3]) - // } + func testClosureParameterArrayIntToArrayInt() throws { + let transform = JSTypedClosure<([Int]) -> [Int]> { $0 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyArrayInt([1, 2, 3], transform) + XCTAssertEqual(result, [1, 2, 3]) + } - // func testClosureParameterArrayDoubleToArrayDouble() throws { - // let transform = JSTypedClosure<([Double]) -> [Double]> { $0 } - // defer { transform.release() } - // let result = try ClosureSupportImports.jsApplyArrayDouble([1.0, 2.0, 3.0], transform) - // XCTAssertEqual(result, [1.0, 2.0, 3.0]) - // } + func testClosureParameterArrayDoubleToArrayDouble() throws { + let transform = JSTypedClosure<([Double]) -> [Double]> { $0 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyArrayDouble([1.0, 2.0, 3.0], transform) + XCTAssertEqual(result, [1.0, 2.0, 3.0]) + } - // func testClosureParameterArrayStringToArrayString() throws { - // let transform = JSTypedClosure<([String]) -> [String]> { $0 } - // defer { transform.release() } - // let result = try ClosureSupportImports.jsApplyArrayString(["a", "b", "c"], transform) - // XCTAssertEqual(result, ["a", "b", "c"]) - // } + func testClosureParameterArrayStringToArrayString() throws { + let transform = JSTypedClosure<([String]) -> [String]> { $0 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyArrayString(["a", "b", "c"], transform) + XCTAssertEqual(result, ["a", "b", "c"]) + } - // func testClosureParameterArrayJSValueToArrayJSValue() throws { - // let transform = JSTypedClosure<([JSValue]) -> [JSValue]> { $0 } - // defer { transform.release() } - // let result = try ClosureSupportImports.jsApplyArrayJSValue([.number(1), .number(2), .number(3)], transform) - // XCTAssertEqual(result, [.number(1), .number(2), .number(3)]) - // } + func testClosureParameterArrayJSValueToArrayJSValue() throws { + let transform = JSTypedClosure<([JSValue]) -> [JSValue]> { $0 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyArrayJSValue([.number(1), .number(2), .number(3)], transform) + XCTAssertEqual(result, [.number(1), .number(2), .number(3)]) + } - // func testClosureParameterArrayJSObjectToArrayJSObject() throws { - // let transform = JSTypedClosure<([JSObject]) -> [JSObject]> { $0 } - // defer { transform.release() } - // let obj1 = JSObject() - // let obj2 = JSObject() - // let obj3 = JSObject() - // let result = try ClosureSupportImports.jsApplyArrayJSObject([obj1, obj2, obj3], transform) - // XCTAssertEqual(result, [obj1, obj2, obj3]) - // } + func testClosureParameterArrayJSObjectToArrayJSObject() throws { + let transform = JSTypedClosure<([JSObject]) -> [JSObject]> { $0 } + defer { transform.release() } + let obj1 = JSObject() + let obj2 = JSObject() + let obj3 = JSObject() + let result = try ClosureSupportImports.jsApplyArrayJSObject([obj1, obj2, obj3], transform) + XCTAssertEqual(result, [obj1, obj2, obj3]) + } func testClosureReturnIntToInt() throws { let c = try ClosureSupportImports.jsMakeIntToInt(10) diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 748a95129..6ad1711a3 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -63,9 +63,10 @@ extension JSTypedClosure where Signature == (HttpStatus) -> Int { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = HttpStatus.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(HttpStatus) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(HttpStatus.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -126,9 +127,10 @@ extension JSTypedClosure where Signature == (any DataProcessor) -> any DataProce @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = AnyDataProcessor.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any DataProcessor) -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(AnyDataProcessor.bridgeJSLiftParameter(param0)) - return _bridgeJSUnwrapProtocolExportable(result, "DataProcessor").bridgeJSLowerAsProtocolReturn() + let ret = _bridgeJSUnwrapProtocolExportable(closure(param0), "DataProcessor") + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -189,9 +191,10 @@ extension JSTypedClosure where Signature == (any DataProcessor) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = AnyDataProcessor.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(any DataProcessor) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(AnyDataProcessor.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -255,9 +258,10 @@ extension JSTypedClosure where Signature == (Theme) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = Theme.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -321,9 +325,10 @@ extension JSTypedClosure where Signature == (Theme) -> Bool { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) + let param0 = Theme.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -384,9 +389,10 @@ extension JSTypedClosure where Signature == (Greeter) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Greeter.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Greeter) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Greeter.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -447,9 +453,10 @@ extension JSTypedClosure where Signature == (JSObject) -> JSObject { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = JSObject.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSObject) -> JSObject>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(JSObject.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -510,9 +517,10 @@ extension JSTypedClosure where Signature == (Vector2D) -> Vector2D { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Vector2D.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(Vector2D) -> Vector2D>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Vector2D.bridgeJSLiftParameter()) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -572,8 +580,9 @@ extension JSTypedClosure where Signature == (Vector2D) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Vector2D.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(Vector2D) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Vector2D.bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -634,9 +643,10 @@ extension JSTypedClosure where Signature == (APIResult) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = APIResult.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(APIResult) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(APIResult.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -697,9 +707,10 @@ extension JSTypedClosure where Signature == (Direction) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = Direction.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Direction.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -760,9 +771,10 @@ extension JSTypedClosure where Signature == (Direction) -> Bool { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Direction.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Direction.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -823,9 +835,10 @@ extension JSTypedClosure where Signature == (Polygon) -> Int { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) + let param0 = Polygon.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Polygon.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -892,10 +905,11 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = try closure(param0) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -975,10 +989,11 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Int @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = try closure(param0) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -1055,9 +1070,10 @@ extension JSTypedClosure where Signature == (String) -> Greeter { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) + let param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> Greeter>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1121,9 +1137,396 @@ extension JSTypedClosure where Signature == (String) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV { + static func bridgeJSLift(_ callbackId: Int32) -> ([JSValue]) -> [JSValue] { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV(callbackValue) + return [JSValue].bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([JSValue]) -> [JSValue] { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([JSValue]) -> [JSValue]) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let param0 = [JSValue].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([JSValue]) -> [JSValue]>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC { + static func bridgeJSLift(_ callbackId: Int32) -> ([JSObject]) -> [JSObject] { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC(callbackValue) + return [JSObject].bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([JSObject]) -> [JSObject] { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([JSObject]) -> [JSObject]) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let param0 = [JSObject].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([JSObject]) -> [JSObject]>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSaSS_SaSS { + static func bridgeJSLift(_ callbackId: Int32) -> ([String]) -> [String] { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS(callbackValue) + return [String].bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([String]) -> [String] { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([String]) -> [String]) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSS_SaSS(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let param0 = [String].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([String]) -> [String]>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSaSd_SaSd { + static func bridgeJSLift(_ callbackId: Int32) -> ([Double]) -> [Double] { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd(callbackValue) + return [Double].bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([Double]) -> [Double] { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([Double]) -> [Double]) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSd_SaSd(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let param0 = [Double].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([Double]) -> [Double]>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(_ callback: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSaSiSaSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> ([Int], [Int]) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0, param1) in + #if arch(wasm32) + let _ = param1.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si(callbackValue) + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([Int], [Int]) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([Int], [Int]) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSiSaSi_Si(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let param1 = [Int].bridgeJSStackPop() + let param0 = [Int].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([Int], [Int]) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0, param1) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSaSi_SaSi { + static func bridgeJSLift(_ callbackId: Int32) -> ([Int]) -> [Int] { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi(callbackValue) + return [Int].bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == ([Int]) -> [Int] { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([Int]) -> [Int]) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSaSi_SaSi(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let param0 = [Int].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([Int]) -> [Int]>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let ret = closure(param0) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1184,9 +1587,10 @@ extension JSTypedClosure where Signature == (Double) -> Vector2D { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Vector2D>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Double.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1247,9 +1651,10 @@ extension JSTypedClosure where Signature == (Double) -> Double { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Float64 { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Double>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Double.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1310,9 +1715,10 @@ extension JSTypedClosure where Signature == (Double) -> Optional { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Double.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1378,9 +1784,12 @@ extension JSTypedClosure where Signature == (Int, String, Double) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Void { #if arch(wasm32) + let param2 = Double.bridgeJSLiftParameter(param2) + let param1 = String.bridgeJSLiftParameter(param1Bytes, param1Length) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, String, Double) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0), String.bridgeJSLiftParameter(param1Bytes, param1Length), Double.bridgeJSLiftParameter(param2)) - return result.bridgeJSLowerReturn() + let ret = closure(param0, param1, param2) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1443,9 +1852,12 @@ extension JSTypedClosure where Signature == (Int, Int, Int) -> Int { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1: Int32, _ param2: Int32) -> Int32 { #if arch(wasm32) + let param2 = Int.bridgeJSLiftParameter(param2) + let param1 = Int.bridgeJSLiftParameter(param1) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, Int, Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0), Int.bridgeJSLiftParameter(param1), Int.bridgeJSLiftParameter(param2)) - return result.bridgeJSLowerReturn() + let ret = closure(param0, param1, param2) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1507,9 +1919,11 @@ extension JSTypedClosure where Signature == (Int, Int) -> Int { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1: Int32) -> Int32 { #if arch(wasm32) + let param1 = Int.bridgeJSLiftParameter(param1) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0), Int.bridgeJSLiftParameter(param1)) - return result.bridgeJSLowerReturn() + let ret = closure(param0, param1) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1570,9 +1984,10 @@ extension JSTypedClosure where Signature == (Int) -> Int { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Int.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1632,8 +2047,9 @@ extension JSTypedClosure where Signature == (Int) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Int.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -1699,9 +2115,10 @@ extension JSTypedClosure where Signature == (Optional) -> Str @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1765,9 +2182,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1828,9 +2246,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1891,9 +2310,10 @@ extension JSTypedClosure where Signature == (Optional) -> Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1954,9 +2374,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -2017,9 +2438,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -2083,9 +2505,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_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 param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -2146,9 +2569,10 @@ extension JSTypedClosure where Signature == (Optional) -> String { @_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 param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let ret = closure(param0) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -2184,9 +2608,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { return { [callback] (param0: String) async throws(JSException) -> String in #if arch(wasm32) let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -2216,9 +2640,10 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - @_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 param0 = String.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)) + return try await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -2257,7 +2682,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in let callbackValue = callback.bridgeJSLowerParameter() @@ -2286,9 +2711,10 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) 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)) + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) -> Void in + try await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -2325,9 +2751,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { return { [callback] (param0: Bool) async throws(JSException) -> AsyncPayloadResult in #if arch(wasm32) let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending AsyncPayloadResult) -> Void>($0) + JSTypedClosure<(sending AsyncPayloadResult) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let param0Value = param0.bridgeJSLowerParameter() let callbackValue = callback.bridgeJSLowerParameter() @@ -2356,9 +2782,82 @@ extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> @_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)) + let param0 = Bool.bridgeJSLiftParameter(param0) + 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(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_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_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>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_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_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_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 param0 = 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(param0) } #else fatalError("Only available on WebAssembly") @@ -2366,43 +2865,42 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK } #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_20BridgeJSRuntimeTestsYaSaSi_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: 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_20BridgeJSRuntimeTestsYaSaSi_Si_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: 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_20BridgeJSRuntimeTestsYaSaSi_Si(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si_extern(resolveRef, rejectRef, callback) } #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_20BridgeJSRuntimeTestsYaSaSi_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si_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_20BridgeJSRuntimeTestsYaSaSi_Si_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_20BridgeJSRuntimeTestsYaSaSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { - static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSaSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> ([Int]) async -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) async -> String in + return { [callback] (param0: [Int]) async -> Int in #if arch(wasm32) let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending Int) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) - } + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si(resolveRef, rejectRef, callbackValue) } return resolved #else @@ -2412,10 +2910,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 == ([Int]) async -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping ([Int]) async -> Int) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si, body: body, fileID: fileID, line: line @@ -2423,13 +2921,14 @@ 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_20BridgeJSRuntimeTestsYaSaSi_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSaSi_Si(_ boxPtr: UnsafeMutableRawPointer) -> 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)) + let param0 = [Int].bridgeJSStackPop() + let closure = Unmanaged<_BridgeJSTypedClosureBox<([Int]) async -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -2466,9 +2965,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { return { [callback] (param0: Double) async -> DataPoint in #if arch(wasm32) let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending DataPoint) -> Void>($0) + JSTypedClosure<(sending DataPoint) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let param0Value = param0.bridgeJSLowerParameter() let callbackValue = callback.bridgeJSLowerParameter() @@ -2497,9 +2996,10 @@ extension JSTypedClosure where Signature == (Double) async -> DataPoint { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Int32 { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) 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)) + return await closure(param0) } #else fatalError("Only available on WebAssembly") @@ -2547,8 +3047,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending FeatureFlag) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y, body: body, fileID: fileID, @@ -2561,8 +3061,9 @@ extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { @_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 param0 = FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending FeatureFlag) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2608,8 +3109,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending WeatherData) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y, body: body, fileID: fileID, @@ -2622,8 +3123,9 @@ extension JSTypedClosure where Signature == (sending WeatherData) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = WeatherData.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending WeatherData) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(WeatherData.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2669,8 +3171,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncPayloadResult) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y, body: body, fileID: fileID, @@ -2683,8 +3185,9 @@ extension JSTypedClosure where Signature == (sending AsyncPayloadResult) -> Void @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = AsyncPayloadResult.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(AsyncPayloadResult.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2730,8 +3233,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncImportedPayloadResult) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y, body: body, fileID: fileID, @@ -2744,8 +3247,9 @@ extension JSTypedClosure where Signature == (sending AsyncImportedPayloadResult) @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = AsyncImportedPayloadResult.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncImportedPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(AsyncImportedPayloadResult.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2791,8 +3295,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, body: body, fileID: fileID, @@ -2805,8 +3309,9 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { @_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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2852,8 +3357,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending DataPoint) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y, body: body, fileID: fileID, @@ -2866,8 +3371,9 @@ extension JSTypedClosure where Signature == (sending DataPoint) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = DataPoint.bridgeJSLiftParameter() let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending DataPoint) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(DataPoint.bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2914,8 +3420,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, body: body, fileID: fileID, @@ -2928,8 +3434,9 @@ extension JSTypedClosure where Signature == (sending String) -> Void { @_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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -2975,8 +3482,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [String]) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, body: body, fileID: fileID, @@ -2989,8 +3496,9 @@ extension JSTypedClosure where Signature == (sending [String]) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = [String].bridgeJSStackPop() let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [String]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([String].bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3036,8 +3544,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Bool]) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y, body: body, fileID: fileID, @@ -3050,8 +3558,9 @@ extension JSTypedClosure where Signature == (sending [Bool]) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = [Bool].bridgeJSStackPop() let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Bool]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Bool].bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3097,8 +3606,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Double]) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y, body: body, fileID: fileID, @@ -3111,8 +3620,9 @@ extension JSTypedClosure where Signature == (sending [Double]) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) + let param0 = [Double].bridgeJSStackPop() let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Double]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Double].bridgeJSLiftParameter()) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3158,8 +3668,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y, body: body, fileID: fileID, @@ -3172,8 +3682,9 @@ extension JSTypedClosure where Signature == (sending Bool) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) + let param0 = Bool.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Bool.bridgeJSLiftParameter(param0)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3219,8 +3730,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y, body: body, fileID: fileID, @@ -3233,8 +3744,71 @@ extension JSTypedClosure where Signature == (sending Double) -> Void { @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) + let param0 = Double.bridgeJSLiftParameter(param0) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Double.bridgeJSLiftParameter(param0)) + closure(param0) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestssSi_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Int) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending Int) -> Void { + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Int) -> Void) -> Self { + Self( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3280,8 +3854,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO } extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y, body: body, fileID: fileID, @@ -3294,8 +3868,9 @@ extension JSTypedClosure where Signature == (sending Optional Void { #if arch(wasm32) + let param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3342,8 +3917,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y, body: body, fileID: fileID, @@ -3356,8 +3931,9 @@ extension JSTypedClosure where Signature == (sending Optional) -> Void { @_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 param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3403,8 +3979,8 @@ 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) { - self.init( + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) -> Self { + Self( makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y, body: body, fileID: fileID, @@ -3417,8 +3993,9 @@ extension JSTypedClosure where Signature == (sending Optional) -> Void { @_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 param0 = Optional.bridgeJSLiftParameter(param0IsSome, param0Value) let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + closure(param0) #else fatalError("Only available on WebAssembly") #endif @@ -3479,8 +4056,8 @@ extension JSTypedClosure where Signature == () -> any DataProcessor { 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 _bridgeJSUnwrapProtocolExportable(result, "DataProcessor").bridgeJSLowerAsProtocolReturn() + let ret = _bridgeJSUnwrapProtocolExportable(closure(), "DataProcessor") + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif @@ -3541,8 +4118,8 @@ extension JSTypedClosure where Signature == () -> Bool { 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() + let ret = closure() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -3603,8 +4180,8 @@ extension JSTypedClosure where Signature == () -> Optional { 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() + let ret = closure() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -4370,7 +4947,8 @@ extension InnerTag: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_ArraySupportExports_static_roundTripIntArray") public func _bjs_ArraySupportExports_static_roundTripIntArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripIntArray(_: [Int].bridgeJSStackPop()) + let v = [Int].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripIntArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4381,7 +4959,8 @@ public func _bjs_ArraySupportExports_static_roundTripIntArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripStringArray") public func _bjs_ArraySupportExports_static_roundTripStringArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripStringArray(_: [String].bridgeJSStackPop()) + let v = [String].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripStringArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4392,7 +4971,8 @@ public func _bjs_ArraySupportExports_static_roundTripStringArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripDoubleArray") public func _bjs_ArraySupportExports_static_roundTripDoubleArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripDoubleArray(_: [Double].bridgeJSStackPop()) + let v = [Double].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripDoubleArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4403,7 +4983,8 @@ public func _bjs_ArraySupportExports_static_roundTripDoubleArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripBoolArray") public func _bjs_ArraySupportExports_static_roundTripBoolArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripBoolArray(_: [Bool].bridgeJSStackPop()) + let v = [Bool].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripBoolArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4414,7 +4995,8 @@ public func _bjs_ArraySupportExports_static_roundTripBoolArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray") public func _bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) + let v = [UnsafeRawPointer].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripUnsafeRawPointerArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4425,7 +5007,8 @@ public func _bjs_ArraySupportExports_static_roundTripUnsafeRawPointerArray() -> @_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray") public func _bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) + let v = [UnsafeMutableRawPointer].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripUnsafeMutableRawPointerArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4436,7 +5019,8 @@ public func _bjs_ArraySupportExports_static_roundTripUnsafeMutableRawPointerArra @_cdecl("bjs_ArraySupportExports_static_roundTripOpaquePointerArray") public func _bjs_ArraySupportExports_static_roundTripOpaquePointerArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) + let v = [OpaquePointer].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOpaquePointerArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4447,7 +5031,8 @@ public func _bjs_ArraySupportExports_static_roundTripOpaquePointerArray() -> Voi @_cdecl("bjs_ArraySupportExports_static_roundTripUnsafePointerArray") public func _bjs_ArraySupportExports_static_roundTripUnsafePointerArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripUnsafePointerArray(_: [UnsafePointer].bridgeJSStackPop()) + let v = [UnsafePointer].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripUnsafePointerArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4458,7 +5043,8 @@ public func _bjs_ArraySupportExports_static_roundTripUnsafePointerArray() -> Voi @_cdecl("bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray") public func _bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripUnsafeMutablePointerArray(_: [UnsafeMutablePointer].bridgeJSStackPop()) + let v = [UnsafeMutablePointer].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripUnsafeMutablePointerArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4469,7 +5055,8 @@ public func _bjs_ArraySupportExports_static_roundTripUnsafeMutablePointerArray() @_cdecl("bjs_ArraySupportExports_static_roundTripJSValueArray") public func _bjs_ArraySupportExports_static_roundTripJSValueArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripJSValueArray(_: [JSValue].bridgeJSStackPop()) + let v = [JSValue].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripJSValueArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4480,7 +5067,8 @@ public func _bjs_ArraySupportExports_static_roundTripJSValueArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripJSObjectArray") public func _bjs_ArraySupportExports_static_roundTripJSObjectArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripJSObjectArray(_: [JSObject].bridgeJSStackPop()) + let v = [JSObject].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripJSObjectArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4491,7 +5079,8 @@ public func _bjs_ArraySupportExports_static_roundTripJSObjectArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripCaseEnumArray") public func _bjs_ArraySupportExports_static_roundTripCaseEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripCaseEnumArray(_: [Direction].bridgeJSStackPop()) + let v = [Direction].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripCaseEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4502,7 +5091,8 @@ public func _bjs_ArraySupportExports_static_roundTripCaseEnumArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripStringRawValueEnumArray(_: [Theme].bridgeJSStackPop()) + let v = [Theme].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripStringRawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4513,7 +5103,8 @@ public func _bjs_ArraySupportExports_static_roundTripStringRawValueEnumArray() - @_cdecl("bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripIntRawValueEnumArray(_: [HttpStatus].bridgeJSStackPop()) + let v = [HttpStatus].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripIntRawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4524,7 +5115,8 @@ public func _bjs_ArraySupportExports_static_roundTripIntRawValueEnumArray() -> V @_cdecl("bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripInt64RawValueEnumArray(_: [FileSize].bridgeJSStackPop()) + let v = [FileSize].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripInt64RawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4535,7 +5127,8 @@ public func _bjs_ArraySupportExports_static_roundTripInt64RawValueEnumArray() -> @_cdecl("bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripUInt64RawValueEnumArray(_: [SessionId].bridgeJSStackPop()) + let v = [SessionId].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripUInt64RawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4546,7 +5139,8 @@ public func _bjs_ArraySupportExports_static_roundTripUInt64RawValueEnumArray() - @_cdecl("bjs_ArraySupportExports_static_roundTripStructArray") public func _bjs_ArraySupportExports_static_roundTripStructArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripStructArray(_: [DataPoint].bridgeJSStackPop()) + let v = [DataPoint].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripStructArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4557,7 +5151,8 @@ public func _bjs_ArraySupportExports_static_roundTripStructArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripSwiftClassArray") public func _bjs_ArraySupportExports_static_roundTripSwiftClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripSwiftClassArray(_: [Greeter].bridgeJSStackPop()) + let v = [Greeter].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripSwiftClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4568,7 +5163,8 @@ public func _bjs_ArraySupportExports_static_roundTripSwiftClassArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray") public func _bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNamespacedSwiftClassArray(_: [Utils.Converter].bridgeJSStackPop()) + let v = [Utils.Converter].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNamespacedSwiftClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4579,7 +5175,8 @@ public func _bjs_ArraySupportExports_static_roundTripNamespacedSwiftClassArray() @_cdecl("bjs_ArraySupportExports_static_roundTripProtocolArray") public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripProtocolArray(_: [AnyArrayElementProtocol].bridgeJSStackPop()) + let v = [AnyArrayElementProtocol].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripProtocolArray(_: v) for __bjs_elem_ret in ret { _swift_js_push_i32(_bridgeJSUnwrapProtocolExportable(__bjs_elem_ret, "ArrayElementProtocol").bridgeJSLowerAsProtocolReturn()) } @@ -4593,7 +5190,8 @@ public func _bjs_ArraySupportExports_static_roundTripProtocolArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripJSClassArray") public func _bjs_ArraySupportExports_static_roundTripJSClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripJSClassArray(_: [ArrayElementObject].bridgeJSStackPop()) + let v = [ArrayElementObject].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripJSClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4604,7 +5202,8 @@ public func _bjs_ArraySupportExports_static_roundTripJSClassArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalIntArray") public func _bjs_ArraySupportExports_static_roundTripOptionalIntArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalIntArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalIntArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4615,7 +5214,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalIntArray() -> Void @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStringArray") public func _bjs_ArraySupportExports_static_roundTripOptionalStringArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalStringArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalStringArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4626,7 +5226,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalStringArray() -> Vo @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray") public func _bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalJSObjectArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalJSObjectArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4637,7 +5238,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalJSObjectArray() -> @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray") public func _bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalCaseEnumArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalCaseEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4648,7 +5250,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalCaseEnumArray() -> @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalStringRawValueEnumArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalStringRawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4659,7 +5262,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalStringRawValueEnumA @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalIntRawValueEnumArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalIntRawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4670,7 +5274,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalIntRawValueEnumArra @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalInt64RawValueEnumArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalInt64RawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4681,7 +5286,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalInt64RawValueEnumAr @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray") public func _bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalUInt64RawValueEnumArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalUInt64RawValueEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4692,7 +5298,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalUInt64RawValueEnumA @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalStructArray") public func _bjs_ArraySupportExports_static_roundTripOptionalStructArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalStructArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalStructArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4703,7 +5310,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalStructArray() -> Vo @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray") public func _bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalSwiftClassArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalSwiftClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4714,7 +5322,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalSwiftClassArray() - @_cdecl("bjs_ArraySupportExports_static_roundTripOptionalJSClassArray") public func _bjs_ArraySupportExports_static_roundTripOptionalJSClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripOptionalJSClassArray(_: [Optional].bridgeJSStackPop()) + let v = [Optional].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripOptionalJSClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4725,7 +5334,8 @@ public func _bjs_ArraySupportExports_static_roundTripOptionalJSClassArray() -> V @_cdecl("bjs_ArraySupportExports_static_roundTripNestedIntArray") public func _bjs_ArraySupportExports_static_roundTripNestedIntArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedIntArray(_: [[Int]].bridgeJSStackPop()) + let v = [[Int]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedIntArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4736,7 +5346,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedIntArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripNestedStringArray") public func _bjs_ArraySupportExports_static_roundTripNestedStringArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedStringArray(_: [[String]].bridgeJSStackPop()) + let v = [[String]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedStringArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4747,7 +5358,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedStringArray() -> Void @_cdecl("bjs_ArraySupportExports_static_roundTripNestedDoubleArray") public func _bjs_ArraySupportExports_static_roundTripNestedDoubleArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedDoubleArray(_: [[Double]].bridgeJSStackPop()) + let v = [[Double]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedDoubleArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4758,7 +5370,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedDoubleArray() -> Void @_cdecl("bjs_ArraySupportExports_static_roundTripNestedBoolArray") public func _bjs_ArraySupportExports_static_roundTripNestedBoolArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedBoolArray(_: [[Bool]].bridgeJSStackPop()) + let v = [[Bool]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedBoolArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4769,7 +5382,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedBoolArray() -> Void { @_cdecl("bjs_ArraySupportExports_static_roundTripNestedStructArray") public func _bjs_ArraySupportExports_static_roundTripNestedStructArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedStructArray(_: [[DataPoint]].bridgeJSStackPop()) + let v = [[DataPoint]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedStructArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4780,7 +5394,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedStructArray() -> Void @_cdecl("bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray") public func _bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedCaseEnumArray(_: [[Direction]].bridgeJSStackPop()) + let v = [[Direction]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedCaseEnumArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4791,7 +5406,8 @@ public func _bjs_ArraySupportExports_static_roundTripNestedCaseEnumArray() -> Vo @_cdecl("bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray") public func _bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray() -> Void { #if arch(wasm32) - let ret = ArraySupportExports.roundTripNestedSwiftClassArray(_: [[Greeter]].bridgeJSStackPop()) + let v = [[Greeter]].bridgeJSStackPop() + let ret = ArraySupportExports.roundTripNestedSwiftClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4802,9 +5418,9 @@ public func _bjs_ArraySupportExports_static_roundTripNestedSwiftClassArray() -> @_cdecl("bjs_ArraySupportExports_static_multiArrayFirst") public func _bjs_ArraySupportExports_static_multiArrayFirst() -> Void { #if arch(wasm32) - let _tmp_b = [String].bridgeJSStackPop() - let _tmp_a = [Int].bridgeJSStackPop() - let ret = ArraySupportExports.multiArrayFirst(_: _tmp_a, _: _tmp_b) + let b = [String].bridgeJSStackPop() + let a = [Int].bridgeJSStackPop() + let ret = ArraySupportExports.multiArrayFirst(_: a, _: b) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4815,9 +5431,9 @@ public func _bjs_ArraySupportExports_static_multiArrayFirst() -> Void { @_cdecl("bjs_ArraySupportExports_static_multiArraySecond") public func _bjs_ArraySupportExports_static_multiArraySecond() -> Void { #if arch(wasm32) - let _tmp_b = [String].bridgeJSStackPop() - let _tmp_a = [Int].bridgeJSStackPop() - let ret = ArraySupportExports.multiArraySecond(_: _tmp_a, _: _tmp_b) + let b = [String].bridgeJSStackPop() + let a = [Int].bridgeJSStackPop() + let ret = ArraySupportExports.multiArraySecond(_: a, _: b) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4828,9 +5444,9 @@ public func _bjs_ArraySupportExports_static_multiArraySecond() -> Void { @_cdecl("bjs_ArraySupportExports_static_multiOptionalArrayFirst") public func _bjs_ArraySupportExports_static_multiOptionalArrayFirst() -> Void { #if arch(wasm32) - let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() - let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() - let ret = ArraySupportExports.multiOptionalArrayFirst(_: _tmp_a, _: _tmp_b) + let b = Optional<[String]>.bridgeJSLiftParameter() + let a = Optional<[Int]>.bridgeJSLiftParameter() + let ret = ArraySupportExports.multiOptionalArrayFirst(_: a, _: b) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4841,9 +5457,9 @@ public func _bjs_ArraySupportExports_static_multiOptionalArrayFirst() -> Void { @_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) + let b = Optional<[String]>.bridgeJSLiftParameter() + let a = Optional<[Int]>.bridgeJSLiftParameter() + let ret = ArraySupportExports.multiOptionalArraySecond(_: a, _: b) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -4885,7 +5501,8 @@ extension Workspace.Kind: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum @_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let ret = DefaultArgumentExports.testStringDefault(message: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4896,7 +5513,8 @@ public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: @_cdecl("bjs_DefaultArgumentExports_static_testIntDefault") public func _bjs_DefaultArgumentExports_static_testIntDefault(_ count: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.testIntDefault(count: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let ret = DefaultArgumentExports.testIntDefault(count: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4907,7 +5525,8 @@ public func _bjs_DefaultArgumentExports_static_testIntDefault(_ count: Int32) -> @_cdecl("bjs_DefaultArgumentExports_static_testBoolDefault") public func _bjs_DefaultArgumentExports_static_testBoolDefault(_ flag: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) + let flag = Bool.bridgeJSLiftParameter(flag) + let ret = DefaultArgumentExports.testBoolDefault(flag: flag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4918,7 +5537,8 @@ public func _bjs_DefaultArgumentExports_static_testBoolDefault(_ flag: Int32) -> @_cdecl("bjs_DefaultArgumentExports_static_testOptionalDefault") public func _bjs_DefaultArgumentExports_static_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let name = Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength) + let ret = DefaultArgumentExports.testOptionalDefault(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4929,7 +5549,10 @@ public func _bjs_DefaultArgumentExports_static_testOptionalDefault(_ nameIsSome: @_cdecl("bjs_DefaultArgumentExports_static_testMultipleDefaults") public func _bjs_DefaultArgumentExports_static_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let count = Int.bridgeJSLiftParameter(count) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let ret = DefaultArgumentExports.testMultipleDefaults(title: title, count: count, enabled: enabled) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4940,7 +5563,8 @@ public func _bjs_DefaultArgumentExports_static_testMultipleDefaults(_ titleBytes @_cdecl("bjs_DefaultArgumentExports_static_testSimpleEnumDefault") public func _bjs_DefaultArgumentExports_static_testSimpleEnumDefault(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) + let status = Status.bridgeJSLiftParameter(status) + let ret = DefaultArgumentExports.testSimpleEnumDefault(status: status) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4951,7 +5575,8 @@ public func _bjs_DefaultArgumentExports_static_testSimpleEnumDefault(_ status: I @_cdecl("bjs_DefaultArgumentExports_static_testDirectionDefault") public func _bjs_DefaultArgumentExports_static_testDirectionDefault(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) + let direction = Direction.bridgeJSLiftParameter(direction) + let ret = DefaultArgumentExports.testDirectionDefault(direction: direction) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4962,7 +5587,8 @@ public func _bjs_DefaultArgumentExports_static_testDirectionDefault(_ direction: @_cdecl("bjs_DefaultArgumentExports_static_testRawStringEnumDefault") public func _bjs_DefaultArgumentExports_static_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = Theme.bridgeJSLiftParameter(themeBytes, themeLength) + let ret = DefaultArgumentExports.testRawStringEnumDefault(theme: theme) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4973,7 +5599,8 @@ public func _bjs_DefaultArgumentExports_static_testRawStringEnumDefault(_ themeB @_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)) + let greeter = Greeter.bridgeJSLiftParameter(greeter) + let ret = DefaultArgumentExports.testComplexInit(greeter: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4984,7 +5611,8 @@ public func _bjs_DefaultArgumentExports_static_testComplexInit(_ greeter: Unsafe @_cdecl("bjs_DefaultArgumentExports_static_testEmptyInit") public func _bjs_DefaultArgumentExports_static_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DefaultArgumentExports.testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) + let object = StaticPropertyHolder.bridgeJSLiftParameter(object) + let ret = DefaultArgumentExports.testEmptyInit(_: object) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4995,7 +5623,12 @@ public func _bjs_DefaultArgumentExports_static_testEmptyInit(_ object: UnsafeMut @_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)) + let tag = Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength) + let status = Status.bridgeJSLiftParameter(status) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let count = Int.bridgeJSLiftParameter(count) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = DefaultArgumentExports.createConstructorDefaults(name: name, count: count, enabled: enabled, status: status, tag: tag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5006,7 +5639,8 @@ public func _bjs_DefaultArgumentExports_static_createConstructorDefaults(_ nameB @_cdecl("bjs_DefaultArgumentExports_static_describeConstructorDefaults") public func _bjs_DefaultArgumentExports_static_describeConstructorDefaults(_ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.describeConstructorDefaults(_: DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(value)) + let value = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(value) + let ret = DefaultArgumentExports.describeConstructorDefaults(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5017,7 +5651,8 @@ public func _bjs_DefaultArgumentExports_static_describeConstructorDefaults(_ val @_cdecl("bjs_DefaultArgumentExports_static_arrayWithDefault") public func _bjs_DefaultArgumentExports_static_arrayWithDefault() -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.arrayWithDefault(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let ret = DefaultArgumentExports.arrayWithDefault(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5028,7 +5663,8 @@ public func _bjs_DefaultArgumentExports_static_arrayWithDefault() -> Int32 { @_cdecl("bjs_DefaultArgumentExports_static_arrayWithOptionalDefault") public func _bjs_DefaultArgumentExports_static_arrayWithOptionalDefault() -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentExports.arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) + let values = Optional<[Int]>.bridgeJSLiftParameter() + let ret = DefaultArgumentExports.arrayWithOptionalDefault(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5039,7 +5675,10 @@ public func _bjs_DefaultArgumentExports_static_arrayWithOptionalDefault() -> Int @_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)) + let suffix = String.bridgeJSLiftParameter(suffixBytes, suffixLength) + let values = [Int].bridgeJSStackPop() + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let ret = DefaultArgumentExports.arrayMixedDefaults(prefix: prefix, values: values, suffix: suffix) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5224,7 +5863,8 @@ extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_Utils_StringUtils_static_uppercase") public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let ret = Utils.StringUtils.uppercase(_: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5235,7 +5875,8 @@ public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLe @_cdecl("bjs_Utils_StringUtils_static_lowercase") public func _bjs_Utils_StringUtils_static_lowercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let ret = Utils.StringUtils.lowercase(_: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5614,7 +6255,8 @@ extension StaticCalculator: _BridgedSwiftCaseEnum { @_cdecl("bjs_StaticCalculator_static_roundtrip") public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = StaticCalculator.roundtrip(_: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = StaticCalculator.roundtrip(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5625,7 +6267,8 @@ public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { @_cdecl("bjs_StaticCalculator_static_doubleValue") public func _bjs_StaticCalculator_static_doubleValue(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = StaticCalculator.doubleValue(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5647,7 +6290,8 @@ public func _bjs_StaticCalculator_static_version_get() -> Void { @_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)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = StaticUtils.Nested.roundtrip(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5658,7 +6302,8 @@ public func _bjs_StaticUtils_Nested_static_roundtrip(_ valueBytes: Int32, _ valu @_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)) + let rootId = Int.bridgeJSLiftParameter(rootId) + let ret = GraphOperations.createGraph(rootId: rootId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5669,7 +6314,8 @@ public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int @_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)) + let graphId = Int.bridgeJSLiftParameter(graphId) + let ret = GraphOperations.nodeCount(graphId: graphId) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5726,7 +6372,8 @@ public func _bjs_StaticPropertyEnum_static_enumProperty_get() -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyEnum.enumProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -5758,7 +6405,8 @@ public func _bjs_StaticPropertyEnum_static_enumBool_get() -> Int32 { @_cdecl("bjs_StaticPropertyEnum_static_enumBool_set") public func _bjs_StaticPropertyEnum_static_enumBool_set(_ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyEnum.enumBool = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + StaticPropertyEnum.enumBool = value #else fatalError("Only available on WebAssembly") #endif @@ -5779,7 +6427,8 @@ public func _bjs_StaticPropertyEnum_static_enumVariable_get() -> Int32 { @_cdecl("bjs_StaticPropertyEnum_static_enumVariable_set") public func _bjs_StaticPropertyEnum_static_enumVariable_set(_ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyEnum.enumVariable = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + StaticPropertyEnum.enumVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -5811,7 +6460,8 @@ public func _bjs_StaticPropertyEnum_static_computedReadWrite_get() -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyEnum.computedReadWrite = value #else fatalError("Only available on WebAssembly") #endif @@ -5832,7 +6482,8 @@ public func _bjs_StaticPropertyNamespace_static_namespaceProperty_get() -> Void @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyNamespace.namespaceProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -5864,7 +6515,8 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_ @_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) + let value = Int.bridgeJSLiftParameter(value) + StaticPropertyNamespace.NestedProperties.nestedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -5896,7 +6548,8 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_ge @_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) + let value = Double.bridgeJSLiftParameter(value) + StaticPropertyNamespace.NestedProperties.nestedDouble = value #else fatalError("Only available on WebAssembly") #endif @@ -5906,7 +6559,8 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_se @_cdecl("bjs_NestedStructGroupA_static_roundtripMetadata") public func _bjs_NestedStructGroupA_static_roundtripMetadata() -> Void { #if arch(wasm32) - let ret = NestedStructGroupA.roundtripMetadata(_: NestedStructGroupA.Metadata.bridgeJSLiftParameter()) + let m = NestedStructGroupA.Metadata.bridgeJSLiftParameter() + let ret = NestedStructGroupA.roundtripMetadata(_: m) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5917,7 +6571,8 @@ public func _bjs_NestedStructGroupA_static_roundtripMetadata() -> Void { @_cdecl("bjs_NestedStructGroupB_static_roundtripMetadata") public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { #if arch(wasm32) - let ret = NestedStructGroupB.roundtripMetadata(_: NestedStructGroupB.Metadata.bridgeJSLiftParameter()) + let m = NestedStructGroupB.Metadata.bridgeJSLiftParameter() + let ret = NestedStructGroupB.roundtripMetadata(_: m) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6128,7 +6783,8 @@ extension GenericRTOutcome: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt(_: Int.bridgeJSLiftParameter(v)) + let v = Int.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripInt(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6139,7 +6795,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> I @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt") public func _bjs_IntegerTypesSupportExports_static_roundTripUInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt(_: UInt.bridgeJSLiftParameter(v)) + let v = UInt.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripUInt(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6150,7 +6807,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt(_ v: Int32) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt8") public func _bjs_IntegerTypesSupportExports_static_roundTripInt8(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt8(_: Int8.bridgeJSLiftParameter(v)) + let v = Int8.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripInt8(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6161,7 +6819,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripInt8(_ v: Int32) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt8") public func _bjs_IntegerTypesSupportExports_static_roundTripUInt8(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt8(_: UInt8.bridgeJSLiftParameter(v)) + let v = UInt8.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripUInt8(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6172,7 +6831,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt8(_ v: Int32) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt16") public func _bjs_IntegerTypesSupportExports_static_roundTripInt16(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt16(_: Int16.bridgeJSLiftParameter(v)) + let v = Int16.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripInt16(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6183,7 +6843,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripInt16(_ v: Int32) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt16") public func _bjs_IntegerTypesSupportExports_static_roundTripUInt16(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) + let v = UInt16.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripUInt16(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6194,7 +6855,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt16(_ v: Int32) - @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt32") public func _bjs_IntegerTypesSupportExports_static_roundTripInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) + let v = Int32.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripInt32(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6205,7 +6867,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripInt32(_ v: Int32) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt32") public func _bjs_IntegerTypesSupportExports_static_roundTripUInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) + let v = UInt32.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripUInt32(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6216,7 +6879,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt32(_ v: Int32) - @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt64") public func _bjs_IntegerTypesSupportExports_static_roundTripInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) + let v = Int64.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripInt64(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6227,7 +6891,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripInt64(_ v: Int64) -> @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt64") public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt64(_: UInt64.bridgeJSLiftParameter(v)) + let v = UInt64.bridgeJSLiftParameter(v) + let ret = IntegerTypesSupportExports.roundTripUInt64(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6238,7 +6903,8 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) - @_cdecl("bjs_JSTypedArrayExports_static_roundTripUint8Array") public func _bjs_JSTypedArrayExports_static_roundTripUint8Array(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripUint8Array(_: JSUint8Array.bridgeJSLiftParameter(v)) + let v = JSUint8Array.bridgeJSLiftParameter(v) + let ret = JSTypedArrayExports.roundTripUint8Array(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6249,7 +6915,8 @@ public func _bjs_JSTypedArrayExports_static_roundTripUint8Array(_ v: Int32) -> I @_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat32Array") public func _bjs_JSTypedArrayExports_static_roundTripFloat32Array(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripFloat32Array(_: JSFloat32Array.bridgeJSLiftParameter(v)) + let v = JSFloat32Array.bridgeJSLiftParameter(v) + let ret = JSTypedArrayExports.roundTripFloat32Array(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6260,7 +6927,8 @@ public func _bjs_JSTypedArrayExports_static_roundTripFloat32Array(_ v: Int32) -> @_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat64Array") public func _bjs_JSTypedArrayExports_static_roundTripFloat64Array(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripFloat64Array(_: JSFloat64Array.bridgeJSLiftParameter(v)) + let v = JSFloat64Array.bridgeJSLiftParameter(v) + let ret = JSTypedArrayExports.roundTripFloat64Array(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6271,7 +6939,8 @@ public func _bjs_JSTypedArrayExports_static_roundTripFloat64Array(_ v: Int32) -> @_cdecl("bjs_JSTypedArrayExports_static_roundTripInt32Array") public func _bjs_JSTypedArrayExports_static_roundTripInt32Array(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripInt32Array(_: JSInt32Array.bridgeJSLiftParameter(v)) + let v = JSInt32Array.bridgeJSLiftParameter(v) + let ret = JSTypedArrayExports.roundTripInt32Array(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6282,7 +6951,8 @@ public func _bjs_JSTypedArrayExports_static_roundTripInt32Array(_ v: Int32) -> I @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) + let ret = OptionalSupportExports.roundTripOptionalString(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6293,7 +6963,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalString(_ vIsSome @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalInt(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6304,7 +6975,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalInt(_ vIsSome: I @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalBool(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6315,7 +6987,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalBool(_ vIsSome: @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalFloat(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6326,7 +6999,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalFloat(_ vIsSome: @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalDouble(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6337,7 +7011,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalDouble(_ vIsSome @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) + let ret = OptionalSupportExports.roundTripOptionalSyntax(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6348,7 +7023,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalSyntax(_ vIsSome @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalCaseEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6359,7 +7035,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum(_ vIsSo @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) + let ret = OptionalSupportExports.roundTripOptionalStringRawValueEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6370,7 +7047,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEn @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalIntRawValueEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6381,7 +7059,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum( @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum") public func _bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum(_ vIsSome: Int32, _ vValue: Int64) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalInt64RawValueEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6392,7 +7071,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnu @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalUInt64RawValueEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6403,7 +7083,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEn @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalTSEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6414,7 +7095,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalTSEnum(_ vIsSome @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) + let ret = OptionalSupportExports.roundTripOptionalTSStringEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6425,7 +7107,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum(_ v @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum") public func _bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalNamespacedEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalNamespacedEnum(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6436,7 +7119,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum(_ @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass") public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass(_ vIsSome: Int32, _ vValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalSwiftClass(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = OptionalSupportExports.roundTripOptionalSwiftClass(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6447,7 +7131,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass(_ vIs @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalIntArray") public func _bjs_OptionalSupportExports_static_roundTripOptionalIntArray() -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalIntArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + let v = Optional<[Int]>.bridgeJSLiftParameter() + let ret = OptionalSupportExports.roundTripOptionalIntArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -6458,7 +7143,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalIntArray() -> Vo @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalStringArray") public func _bjs_OptionalSupportExports_static_roundTripOptionalStringArray() -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalStringArray(_: Optional<[String]>.bridgeJSLiftParameter()) + let v = Optional<[String]>.bridgeJSLiftParameter() + let ret = OptionalSupportExports.roundTripOptionalStringArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -6469,7 +7155,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalStringArray() -> @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray") public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray() -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalSwiftClassArray(_: Optional<[Greeter]>.bridgeJSLiftParameter()) + let v = Optional<[Greeter]>.bridgeJSLiftParameter() + let ret = OptionalSupportExports.roundTripOptionalSwiftClassArray(_: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -6480,7 +7167,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray( @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalAPIResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6491,7 +7179,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIResult(_ vIsS @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalTypedPayloadResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6502,7 +7191,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResu @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalComplexResult") public func _bjs_OptionalSupportExports_static_roundTripOptionalComplexResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalComplexResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6513,7 +7203,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalComplexResult(_ @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalAllTypesResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6524,7 +7215,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult(_ @_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult") public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult(_ v: Int32) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(v)) + let v = OptionalAllTypesResult.bridgeJSLiftParameter(v) + let ret = OptionalSupportExports.roundTripOptionalPayloadResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6535,7 +7227,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult(_ @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalPayloadResultOpt(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6546,7 +7239,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt @_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)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let ret = OptionalSupportExports.roundTripOptionalAPIOptionalResult(_: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6557,7 +7251,8 @@ public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResul @_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)) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + OptionalSupportExports.takeOptionalJSObject(_: value) #else fatalError("Only available on WebAssembly") #endif @@ -6567,7 +7262,9 @@ public func _bjs_OptionalSupportExports_static_takeOptionalJSObject(_ valueIsSom @_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)) + let transform = _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC.bridgeJSLift(transform) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = OptionalSupportExports.applyOptionalGreeter(_: value, _: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6578,7 +7275,9 @@ public func _bjs_OptionalSupportExports_static_applyOptionalGreeter(_ valueIsSom @_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)) + let undefinedNumber = JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue) + let nullableGreeter = Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue) + let ret = OptionalSupportExports.makeOptionalHolder(nullableGreeter: nullableGreeter, undefinedNumber: undefinedNumber) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6589,9 +7288,9 @@ public func _bjs_OptionalSupportExports_static_makeOptionalHolder(_ nullableGree @_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) + let r2 = Optional.bridgeJSLiftParameter(r2IsSome, r2CaseId) + let r1 = Optional.bridgeJSLiftParameter(r1IsSome, r1CaseId) + let ret = OptionalSupportExports.compareAPIResults(_: r1, _: r2) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6730,7 +7429,9 @@ fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 { @_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)) + let longitude = Double.bridgeJSLiftParameter(longitude) + let latitude = Double.bridgeJSLiftParameter(latitude) + let ret = JSCoordinate(latitude: latitude, longitude: longitude) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6883,7 +7584,8 @@ fileprivate func _bjs_struct_lift_NestedTypeHost_Label_extern() -> Int32 { @_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)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let ret = NestedTypeHost.Label(text: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6962,7 +7664,8 @@ fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = Library.Shelf(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -6984,7 +7687,8 @@ public func _bjs_Library_Shelf_static_capacity_get() -> Int32 { @_cdecl("bjs_Library_Shelf_describeShelf") public func _bjs_Library_Shelf_describeShelf() -> Void { #if arch(wasm32) - let ret = Library.Shelf.bridgeJSLiftParameter().describeShelf() + let _self = Library.Shelf.bridgeJSLiftParameter() + let ret = _self.describeShelf() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7041,7 +7745,8 @@ fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { @_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)) + let slot = Int.bridgeJSLiftParameter(slot) + let ret = Library.Shelf.Divider(slot: slot) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7250,7 +7955,12 @@ fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { @_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 = PointerFields(raw: UnsafeRawPointer.bridgeJSLiftParameter(raw), mutRaw: UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw), opaque: OpaquePointer.bridgeJSLiftParameter(opaque), ptr: UnsafePointer.bridgeJSLiftParameter(ptr), mutPtr: UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr)) + let mutPtr = UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr) + let ptr = UnsafePointer.bridgeJSLiftParameter(ptr) + let opaque = OpaquePointer.bridgeJSLiftParameter(opaque) + let mutRaw = UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw) + let raw = UnsafeRawPointer.bridgeJSLiftParameter(raw) + let ret = PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7315,7 +8025,12 @@ fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { @_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)) + let optFlag = Optional.bridgeJSLiftParameter(optFlagIsSome, optFlagValue) + let optCount = Optional.bridgeJSLiftParameter(optCountIsSome, optCountValue) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let y = Double.bridgeJSLiftParameter(y) + let x = Double.bridgeJSLiftParameter(x) + let ret = DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7396,7 +8111,9 @@ fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 { @_cdecl("bjs_PublicPoint_init") public func _bjs_PublicPoint_init(_ x: Int32, _ y: Int32) -> Void { #if arch(wasm32) - let ret = PublicPoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let y = Int.bridgeJSLiftParameter(y) + let x = Int.bridgeJSLiftParameter(x) + let ret = PublicPoint(x: x, y: y) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7825,7 +8542,8 @@ fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { @_cdecl("bjs_MathOperations_init") public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { #if arch(wasm32) - let ret = MathOperations(baseValue: Double.bridgeJSLiftParameter(baseValue)) + let baseValue = Double.bridgeJSLiftParameter(baseValue) + let ret = MathOperations(baseValue: baseValue) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7836,7 +8554,10 @@ public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let _self = MathOperations.bridgeJSLiftParameter() + let ret = _self.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7847,7 +8568,10 @@ public func _bjs_MathOperations_add(_ a: Float64, _ b: Float64) -> Float64 { @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let _self = MathOperations.bridgeJSLiftParameter() + let ret = _self.multiply(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7858,7 +8582,9 @@ public func _bjs_MathOperations_multiply(_ a: Float64, _ b: Float64) -> Float64 @_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)) + let b = Double.bridgeJSLiftParameter(b) + let a = Double.bridgeJSLiftParameter(a) + let ret = MathOperations.subtract(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7917,7 +8643,8 @@ fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 { @_cdecl("bjs_CopyableCart_static_fromJSObject") public func _bjs_CopyableCart_static_fromJSObject(_ object: Int32) -> Void { #if arch(wasm32) - let ret = CopyableCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) + let object = JSObject.bridgeJSLiftParameter(object) + let ret = CopyableCart.fromJSObject(_: object) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8026,7 +8753,8 @@ fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 { @_cdecl("bjs_CopyableNestedCart_static_fromJSObject") public func _bjs_CopyableNestedCart_static_fromJSObject(_ object: Int32) -> Void { #if arch(wasm32) - let ret = CopyableNestedCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) + let object = JSObject.bridgeJSLiftParameter(object) + let ret = CopyableNestedCart.fromJSObject(_: object) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8096,7 +8824,8 @@ public func _bjs_ConfigStruct_static_defaultConfig_get() -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + ConfigStruct.defaultConfig = value #else fatalError("Only available on WebAssembly") #endif @@ -8128,7 +8857,8 @@ public func _bjs_ConfigStruct_static_timeout_get() -> Float64 { @_cdecl("bjs_ConfigStruct_static_timeout_set") public func _bjs_ConfigStruct_static_timeout_set(_ value: Float64) -> Void { #if arch(wasm32) - ConfigStruct.timeout = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + ConfigStruct.timeout = value #else fatalError("Only available on WebAssembly") #endif @@ -8197,7 +8927,9 @@ fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 { @_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)) + let dy = Double.bridgeJSLiftParameter(dy) + let dx = Double.bridgeJSLiftParameter(dx) + let ret = Vector2D(dx: dx, dy: dy) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8208,7 +8940,8 @@ public func _bjs_Vector2D_init(_ dx: Float64, _ dy: Float64) -> Void { @_cdecl("bjs_Vector2D_magnitude") public func _bjs_Vector2D_magnitude() -> Float64 { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().magnitude() + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.magnitude() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8219,7 +8952,9 @@ public func _bjs_Vector2D_magnitude() -> Float64 { @_cdecl("bjs_Vector2D_scaled") public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + let factor = Double.bridgeJSLiftParameter(factor) + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.scaled(by: factor) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8230,7 +8965,8 @@ public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { @_cdecl("bjs_Vector2D_describe") public func _bjs_Vector2D_describe() -> Void { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().describe() + let _self = Vector2D.bridgeJSLiftParameter() + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8385,7 +9121,9 @@ fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { @_cdecl("bjs_ArrayMembers_sumValues") public func _bjs_ArrayMembers_sumValues() -> Int32 { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + let values = [Int].bridgeJSStackPop() + let _self = ArrayMembers.bridgeJSLiftParameter() + let ret = _self.sumValues(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8396,18 +9134,75 @@ public func _bjs_ArrayMembers_sumValues() -> Int32 { @_cdecl("bjs_ArrayMembers_firstString") public func _bjs_ArrayMembers_firstString() -> Void { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) + let values = [String].bridgeJSStackPop() + let _self = ArrayMembers.bridgeJSLiftParameter() + let ret = _self.firstString(_: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } +@_expose(wasm, "bjs_ArrayMembers_ownSumAsync") +@_cdecl("bjs_ArrayMembers_ownSumAsync") +public func _bjs_ArrayMembers_ownSumAsync() -> Int32 { + #if arch(wasm32) + let _self = ArrayMembers.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await _self.ownSumAsync() + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayMembers_sumAsync") +@_cdecl("bjs_ArrayMembers_sumAsync") +public func _bjs_ArrayMembers_sumAsync() -> Int32 { + #if arch(wasm32) + let values = [Int].bridgeJSStackPop() + let _self = ArrayMembers.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await _self.sumAsync(_: values) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayMembers_requireValues") +@_cdecl("bjs_ArrayMembers_requireValues") +public func _bjs_ArrayMembers_requireValues() -> Void { + #if arch(wasm32) + let values = [Int].bridgeJSStackPop() + let _self = ArrayMembers.bridgeJSLiftParameter() + do { + let ret = try _self.requireValues(_: values) + ret.bridgeJSStackPush() + } 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_makeTag") @_cdecl("bjs_makeTag") public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = makeTag(_: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8418,7 +9213,8 @@ public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutab @_cdecl("bjs_roundTripPolygon") public func _bjs_roundTripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = roundTripPolygon(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8429,7 +9225,9 @@ public func _bjs_roundTripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeM @_cdecl("bjs_appendVertex") public func _bjs_appendVertex(_ polygon: UnsafeMutableRawPointer, _ value: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = appendVertex(_: Polygon.bridgeJSLiftParameter(polygon), _: Double.bridgeJSLiftParameter(value)) + let value = Double.bridgeJSLiftParameter(value) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = appendVertex(_: polygon, _: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8440,7 +9238,8 @@ public func _bjs_appendVertex(_ polygon: UnsafeMutableRawPointer, _ value: Float @_cdecl("bjs_optionalRoundTripPolygon") public func _bjs_optionalRoundTripPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = optionalRoundTripPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue)) + let polygon = Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue) + let ret = optionalRoundTripPolygon(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8451,7 +9250,8 @@ public func _bjs_optionalRoundTripPolygon(_ polygonIsSome: Int32, _ polygonValue @_cdecl("bjs_polygonVertexCount") public func _bjs_polygonVertexCount(_ polygon: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = polygonVertexCount(_: Polygon.bridgeJSLiftParameter(polygon)) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = polygonVertexCount(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8462,7 +9262,8 @@ public func _bjs_polygonVertexCount(_ polygon: UnsafeMutableRawPointer) -> Int32 @_cdecl("bjs_roundTripPolygonArray") public func _bjs_roundTripPolygonArray() -> Void { #if arch(wasm32) - let ret = roundTripPolygonArray(_: [Polygon].bridgeJSStackPop()) + let polygons = [Polygon].bridgeJSStackPop() + let ret = roundTripPolygonArray(_: polygons) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -8473,7 +9274,8 @@ public func _bjs_roundTripPolygonArray() -> Void { @_cdecl("bjs_concatPolygons") public func _bjs_concatPolygons() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = concatPolygons(_: [Polygon].bridgeJSStackPop()) + let polygons = [Polygon].bridgeJSStackPop() + let ret = concatPolygons(_: polygons) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8484,8 +9286,9 @@ public func _bjs_concatPolygons() -> UnsafeMutableRawPointer { @_cdecl("bjs_validatePolygon") public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) + let polygon = Polygon.bridgeJSLiftParameter(polygon) do { - let ret = try validatePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let ret = try validatePolygon(_: polygon) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -8509,7 +9312,8 @@ public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMu @_cdecl("bjs_splitPolygon") public func _bjs_splitPolygon(_ polygon: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = splitPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = splitPolygon(_: polygon) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -8531,7 +9335,8 @@ public func _bjs_makePolygonInspector() -> Int32 { @_cdecl("bjs_roundTripOptionalPolygonArray") public func _bjs_roundTripOptionalPolygonArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalPolygonArray(_: [Optional].bridgeJSStackPop()) + let polygons = [Optional].bridgeJSStackPop() + let ret = roundTripOptionalPolygonArray(_: polygons) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -8542,7 +9347,9 @@ public func _bjs_roundTripOptionalPolygonArray() -> Void { @_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)) + let version = Int.bridgeJSLiftParameter(version) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = makeTagHolder(_: name, _: version) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8553,7 +9360,8 @@ public func _bjs_makeTagHolder(_ nameBytes: Int32, _ nameLength: Int32, _ versio @_cdecl("bjs_roundTripCoordinate") public func _bjs_roundTripCoordinate() -> Void { #if arch(wasm32) - let ret = roundTripCoordinate(_: Coordinate.bridgeJSLiftParameter()) + let coordinate = Coordinate.bridgeJSLiftParameter() + let ret = roundTripCoordinate(_: coordinate) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8564,7 +9372,8 @@ public func _bjs_roundTripCoordinate() -> Void { @_cdecl("bjs_roundTripPriority") public func _bjs_roundTripPriority(_ priority: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripPriority(_: Priority.bridgeJSLiftParameter(priority)) + let priority = Priority.bridgeJSLiftParameter(priority) + let ret = roundTripPriority(_: priority) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8575,7 +9384,8 @@ public func _bjs_roundTripPriority(_ priority: UnsafeMutableRawPointer) -> Unsaf @_cdecl("bjs_roundTripAlert") public func _bjs_roundTripAlert(_ alert: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripAlert(_: Alert.bridgeJSLiftParameter(alert)) + let alert = Alert.bridgeJSLiftParameter(alert) + let ret = roundTripAlert(_: alert) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8586,7 +9396,8 @@ public func _bjs_roundTripAlert(_ alert: Int32) -> Int32 { @_cdecl("bjs_makeAlert") public func _bjs_makeAlert(_ level: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAlert(_: Severity.bridgeJSLiftParameter(level)) + let level = Severity.bridgeJSLiftParameter(level) + let ret = makeAlert(_: level) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8597,7 +9408,8 @@ public func _bjs_makeAlert(_ level: Int32) -> Int32 { @_cdecl("bjs_roundTripShape") public func _bjs_roundTripShape(_ s: Int32) -> Void { #if arch(wasm32) - let ret = roundTripShape(_: Shape.bridgeJSLiftParameter(s)) + let s = Shape.bridgeJSLiftParameter(s) + let ret = roundTripShape(_: s) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8608,7 +9420,8 @@ public func _bjs_roundTripShape(_ s: Int32) -> Void { @_cdecl("bjs_makeShapePolygon") public func _bjs_makeShapePolygon(_ polygon: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = makeShapePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + let polygon = Polygon.bridgeJSLiftParameter(polygon) + let ret = makeShapePolygon(_: polygon) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8630,7 +9443,8 @@ public func _bjs_makeShapeEmpty() -> Void { @_cdecl("bjs_roundTripUserId") public func _bjs_roundTripUserId(_ id: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUserId(_: UserId.bridgeJSLiftParameter(id)) + let id = UserId.bridgeJSLiftParameter(id) + let ret = roundTripUserId(_: id) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8641,7 +9455,8 @@ public func _bjs_roundTripUserId(_ id: Int32) -> Int32 { @_cdecl("bjs_roundTripOptionalUserId") public func _bjs_roundTripOptionalUserId(_ idIsSome: Int32, _ idValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalUserId(_: Optional.bridgeJSLiftParameter(idIsSome, idValue)) + let id = Optional.bridgeJSLiftParameter(idIsSome, idValue) + let ret = roundTripOptionalUserId(_: id) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8652,7 +9467,8 @@ public func _bjs_roundTripOptionalUserId(_ idIsSome: Int32, _ idValue: Int32) -> @_cdecl("bjs_roundTripUserIdArray") public func _bjs_roundTripUserIdArray() -> Void { #if arch(wasm32) - let ret = roundTripUserIdArray(_: [UserId].bridgeJSStackPop()) + let ids = [UserId].bridgeJSStackPop() + let ret = roundTripUserIdArray(_: ids) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -8663,7 +9479,8 @@ public func _bjs_roundTripUserIdArray() -> Void { @_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)) + let boxed = Boxed.bridgeJSLiftParameter(boxedKind, boxedPayload1, boxedPayload2) + let ret = roundTripBoxed(_: boxed) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8674,7 +9491,8 @@ public func _bjs_roundTripBoxed(_ boxedKind: Int32, _ boxedPayload1: Int32, _ bo @_cdecl("bjs_roundTripOptionalBoxed") public func _bjs_roundTripOptionalBoxed(_ boxedIsSome: Int32, _ boxedKind: Int32, _ boxedPayload1: Int32, _ boxedPayload2: Float64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalBoxed(_: Optional.bridgeJSLiftParameter(boxedIsSome, boxedKind, boxedPayload1, boxedPayload2)) + let boxed = Optional.bridgeJSLiftParameter(boxedIsSome, boxedKind, boxedPayload1, boxedPayload2) + let ret = roundTripOptionalBoxed(_: boxed) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8685,8 +9503,9 @@ public func _bjs_roundTripOptionalBoxed(_ boxedIsSome: Int32, _ boxedKind: Int32 @_cdecl("bjs_awaitAsyncCallback") public func _bjs_awaitAsyncCallback(_ fetch: Int32) -> Int32 { #if arch(wasm32) + let fetch = _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS.bridgeJSLift(fetch) 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)) + return try await awaitAsyncCallback(_: fetch) } #else fatalError("Only available on WebAssembly") @@ -8752,8 +9571,9 @@ public func _bjs_makeAsyncPayloadLoader() -> Int32 { @_cdecl("bjs_awaitPayloadCallback") public func _bjs_awaitPayloadCallback(_ load: Int32) -> Int32 { #if arch(wasm32) + let load = _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO.bridgeJSLift(load) 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)) + return try await awaitPayloadCallback(_: load) } #else fatalError("Only available on WebAssembly") @@ -8771,6 +9591,30 @@ public func _bjs_makeAsyncPointMaker() -> Int32 { #endif } +@_expose(wasm, "bjs_makeAsyncArraySum") +@_cdecl("bjs_makeAsyncArraySum") +public func _bjs_makeAsyncArraySum() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncArraySum() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_awaitArraySum") +@_cdecl("bjs_awaitArraySum") +public func _bjs_awaitArraySum(_ sum: Int32) -> Int32 { + #if arch(wasm32) + let sum = _BJS_Closure_20BridgeJSRuntimeTestsYaSaSi_Si.bridgeJSLift(sum) + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await awaitArraySum(_: sum) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_makeThrowingParser") @_cdecl("bjs_makeThrowingParser") public func _bjs_makeThrowingParser() -> Int32 { @@ -8786,8 +9630,9 @@ public func _bjs_makeThrowingParser() -> Int32 { @_cdecl("bjs_runValidator") public func _bjs_runValidator(_ validate: Int32) -> Int32 { #if arch(wasm32) + let validate = _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb.bridgeJSLift(validate) do { - let ret = try runValidator(_: _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb.bridgeJSLift(validate)) + let ret = try runValidator(_: validate) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -8821,7 +9666,8 @@ public func _bjs_roundTripVoid() -> Void { @_cdecl("bjs_roundTripFloat") public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { #if arch(wasm32) - let ret = roundTripFloat(v: Float.bridgeJSLiftParameter(v)) + let v = Float.bridgeJSLiftParameter(v) + let ret = roundTripFloat(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8832,7 +9678,8 @@ public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { @_cdecl("bjs_roundTripDouble") public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { #if arch(wasm32) - let ret = roundTripDouble(v: Double.bridgeJSLiftParameter(v)) + let v = Double.bridgeJSLiftParameter(v) + let ret = roundTripDouble(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8843,7 +9690,8 @@ public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { @_cdecl("bjs_roundTripBool") public func _bjs_roundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripBool(v: Bool.bridgeJSLiftParameter(v)) + let v = Bool.bridgeJSLiftParameter(v) + let ret = roundTripBool(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8854,7 +9702,8 @@ public func _bjs_roundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripString") public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) + let v = String.bridgeJSLiftParameter(vBytes, vLength) + let ret = roundTripString(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8865,7 +9714,8 @@ public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { @_cdecl("bjs_roundTripSwiftHeapObject") public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) + let v = Greeter.bridgeJSLiftParameter(v) + let ret = roundTripSwiftHeapObject(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8876,7 +9726,8 @@ public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Unsaf @_cdecl("bjs_roundTripUnsafeRawPointer") public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUnsafeRawPointer(v: UnsafeRawPointer.bridgeJSLiftParameter(v)) + let v = UnsafeRawPointer.bridgeJSLiftParameter(v) + let ret = roundTripUnsafeRawPointer(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8887,7 +9738,8 @@ public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> Unsa @_cdecl("bjs_roundTripUnsafeMutableRawPointer") public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUnsafeMutableRawPointer(v: UnsafeMutableRawPointer.bridgeJSLiftParameter(v)) + let v = UnsafeMutableRawPointer.bridgeJSLiftParameter(v) + let ret = roundTripUnsafeMutableRawPointer(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8898,7 +9750,8 @@ public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) @_cdecl("bjs_roundTripOpaquePointer") public func _bjs_roundTripOpaquePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripOpaquePointer(v: OpaquePointer.bridgeJSLiftParameter(v)) + let v = OpaquePointer.bridgeJSLiftParameter(v) + let ret = roundTripOpaquePointer(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8909,7 +9762,8 @@ public func _bjs_roundTripOpaquePointer(_ v: UnsafeMutableRawPointer) -> UnsafeM @_cdecl("bjs_roundTripUnsafePointer") public func _bjs_roundTripUnsafePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUnsafePointer(v: UnsafePointer.bridgeJSLiftParameter(v)) + let v = UnsafePointer.bridgeJSLiftParameter(v) + let ret = roundTripUnsafePointer(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8920,7 +9774,8 @@ public func _bjs_roundTripUnsafePointer(_ v: UnsafeMutableRawPointer) -> UnsafeM @_cdecl("bjs_roundTripUnsafeMutablePointer") public func _bjs_roundTripUnsafeMutablePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUnsafeMutablePointer(v: UnsafeMutablePointer.bridgeJSLiftParameter(v)) + let v = UnsafeMutablePointer.bridgeJSLiftParameter(v) + let ret = roundTripUnsafeMutablePointer(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8931,7 +9786,8 @@ public func _bjs_roundTripUnsafeMutablePointer(_ v: UnsafeMutableRawPointer) -> @_cdecl("bjs_roundTripJSObject") public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) + let v = JSObject.bridgeJSLiftParameter(v) + let ret = roundTripJSObject(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8942,7 +9798,8 @@ public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { @_cdecl("bjs_roundTripDictionaryExport") public func _bjs_roundTripDictionaryExport() -> Void { #if arch(wasm32) - let ret = roundTripDictionaryExport(v: [String: Int].bridgeJSLiftParameter()) + let v = [String: Int].bridgeJSLiftParameter() + let ret = roundTripDictionaryExport(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8953,7 +9810,8 @@ public func _bjs_roundTripDictionaryExport() -> Void { @_cdecl("bjs_roundTripOptionalDictionaryExport") public func _bjs_roundTripOptionalDictionaryExport() -> Void { #if arch(wasm32) - let ret = roundTripOptionalDictionaryExport(v: Optional<[String: String]>.bridgeJSLiftParameter()) + let v = Optional<[String: String]>.bridgeJSLiftParameter() + let ret = roundTripOptionalDictionaryExport(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8964,7 +9822,8 @@ public func _bjs_roundTripOptionalDictionaryExport() -> Void { @_cdecl("bjs_roundTripJSValue") public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) + let v = JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2) + let ret = roundTripJSValue(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8975,7 +9834,8 @@ public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload @_cdecl("bjs_roundTripOptionalJSValue") public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2) + let ret = roundTripOptionalJSValue(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -8986,7 +9846,8 @@ public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vP @_cdecl("bjs_roundTripOptionalJSValueArray") public func _bjs_roundTripOptionalJSValueArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) + let v = Optional<[JSValue]>.bridgeJSLiftParameter() + let ret = roundTripOptionalJSValueArray(v: v) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -8997,8 +9858,9 @@ public func _bjs_roundTripOptionalJSValueArray() -> Void { @_cdecl("bjs_makeImportedFoo") public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { #if arch(wasm32) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) do { - let ret = try makeImportedFoo(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = try makeImportedFoo(value: value) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -9022,7 +9884,8 @@ public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> I @_cdecl("bjs_roundTripOptionalImportedClass") public func _bjs_roundTripOptionalImportedClass(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalImportedClass(v: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) + let ret = roundTripOptionalImportedClass(v: v) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9033,8 +9896,9 @@ public func _bjs_roundTripOptionalImportedClass(_ vIsSome: Int32, _ vValue: Int3 @_cdecl("bjs_throwsSwiftError") public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { #if arch(wasm32) + let shouldThrow = Bool.bridgeJSLiftParameter(shouldThrow) do { - try throwsSwiftError(shouldThrow: Bool.bridgeJSLiftParameter(shouldThrow)) + try throwsSwiftError(shouldThrow: shouldThrow) } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { @@ -9258,8 +10122,9 @@ public func _bjs_asyncRoundTripVoid() -> Int32 { @_cdecl("bjs_asyncRoundTripInt") public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = Int.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { - return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)) + return await asyncRoundTripInt(v: v) } #else fatalError("Only available on WebAssembly") @@ -9270,8 +10135,9 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripFloat") public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) + let v = Float.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { - return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)) + return await asyncRoundTripFloat(v: v) } #else fatalError("Only available on WebAssembly") @@ -9282,8 +10148,9 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { @_cdecl("bjs_asyncRoundTripDouble") public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) + let v = Double.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { - return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)) + return await asyncRoundTripDouble(v: v) } #else fatalError("Only available on WebAssembly") @@ -9294,8 +10161,9 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { @_cdecl("bjs_asyncRoundTripBool") public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = Bool.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { - return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)) + return await asyncRoundTripBool(v: v) } #else fatalError("Only available on WebAssembly") @@ -9306,8 +10174,9 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripString") public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = String.bridgeJSLiftParameter(vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { - return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) + return await asyncRoundTripString(v: v) } #else fatalError("Only available on WebAssembly") @@ -9318,8 +10187,9 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 @_cdecl("bjs_asyncRoundTripSwiftHeapObject") public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) + let v = Greeter.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_7GreeterC, reject: Promise_reject) { - return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) + return await asyncRoundTripSwiftHeapObject(v: v) } #else fatalError("Only available on WebAssembly") @@ -9330,8 +10200,9 @@ public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> @_cdecl("bjs_asyncRoundTripJSObject") public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = JSObject.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { - return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) + return await asyncRoundTripJSObject(v: v) } #else fatalError("Only available on WebAssembly") @@ -9342,7 +10213,9 @@ public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { @_cdecl("bjs_takeGreeter") public func _bjs_takeGreeter(_ g: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - takeGreeter(g: Greeter.bridgeJSLiftParameter(g), name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let g = Greeter.bridgeJSLiftParameter(g) + takeGreeter(g: g, name: name) #else fatalError("Only available on WebAssembly") #endif @@ -9363,7 +10236,10 @@ public func _bjs_createCalculator() -> UnsafeMutableRawPointer { @_cdecl("bjs_useCalculator") public func _bjs_useCalculator(_ calc: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = useCalculator(calc: Calculator.bridgeJSLiftParameter(calc), x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let y = Int.bridgeJSLiftParameter(y) + let x = Int.bridgeJSLiftParameter(x) + let calc = Calculator.bridgeJSLiftParameter(calc) + let ret = useCalculator(calc: calc, x: x, y: y) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9396,7 +10272,8 @@ public func _bjs_testCalculatorToJSValue() -> Int32 { @_cdecl("bjs_testSwiftClassAsJSValue") public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) + let greeter = Greeter.bridgeJSLiftParameter(greeter) + let ret = testSwiftClassAsJSValue(greeter: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9407,7 +10284,8 @@ public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> @_cdecl("bjs_setDirection") public func _bjs_setDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) + let direction = Direction.bridgeJSLiftParameter(direction) + let ret = setDirection(_: direction) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9429,7 +10307,8 @@ public func _bjs_getDirection() -> Int32 { @_cdecl("bjs_processDirection") public func _bjs_processDirection(_ input: Int32) -> Int32 { #if arch(wasm32) - let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) + let input = Direction.bridgeJSLiftParameter(input) + let ret = processDirection(_: input) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9440,7 +10319,8 @@ public func _bjs_processDirection(_ input: Int32) -> Int32 { @_cdecl("bjs_setTheme") public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = Theme.bridgeJSLiftParameter(themeBytes, themeLength) + let ret = setTheme(_: theme) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9462,8 +10342,9 @@ public func _bjs_getTheme() -> Void { @_cdecl("bjs_asyncRoundTripTheme") public func _bjs_asyncRoundTripTheme(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = Theme.bridgeJSLiftParameter(vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_5ThemeO, reject: Promise_reject) { - return await asyncRoundTripTheme(_: Theme.bridgeJSLiftParameter(vBytes, vLength)) + return await asyncRoundTripTheme(_: v) } #else fatalError("Only available on WebAssembly") @@ -9474,8 +10355,9 @@ public func _bjs_asyncRoundTripTheme(_ vBytes: Int32, _ vLength: Int32) -> Int32 @_cdecl("bjs_asyncRoundTripDirection") public func _bjs_asyncRoundTripDirection(_ v: Int32) -> Int32 { #if arch(wasm32) + let v = Direction.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirection(_: Direction.bridgeJSLiftParameter(v)) + return await asyncRoundTripDirection(_: v) } #else fatalError("Only available on WebAssembly") @@ -9486,8 +10368,9 @@ public func _bjs_asyncRoundTripDirection(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripOptionalTheme") public func _bjs_asyncRoundTripOptionalTheme(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) + let v = Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength) return _bjs_makePromise(resolve: Promise_resolve_Sq5ThemeO, reject: Promise_reject) { - return await asyncRoundTripOptionalTheme(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) + return await asyncRoundTripOptionalTheme(_: v) } #else fatalError("Only available on WebAssembly") @@ -9498,8 +10381,9 @@ public func _bjs_asyncRoundTripOptionalTheme(_ vIsSome: Int32, _ vBytes: Int32, @_cdecl("bjs_asyncRoundTripOptionalDirection") public func _bjs_asyncRoundTripOptionalDirection(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { #if arch(wasm32) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) return _bjs_makePromise(resolve: Promise_resolve_Sq9DirectionO, reject: Promise_reject) { - return await asyncRoundTripOptionalDirection(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return await asyncRoundTripOptionalDirection(_: v) } #else fatalError("Only available on WebAssembly") @@ -9510,9 +10394,9 @@ public func _bjs_asyncRoundTripOptionalDirection(_ vIsSome: Int32, _ vValue: Int @_cdecl("bjs_asyncRoundTripDirectionArray") public func _bjs_asyncRoundTripDirectionArray() -> Int32 { #if arch(wasm32) - let _tmp_v = [Direction].bridgeJSStackPop() + let v = [Direction].bridgeJSStackPop() return _bjs_makePromise(resolve: Promise_resolve_Sa9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirectionArray(_: _tmp_v) + return await asyncRoundTripDirectionArray(_: v) } #else fatalError("Only available on WebAssembly") @@ -9523,9 +10407,9 @@ public func _bjs_asyncRoundTripDirectionArray() -> Int32 { @_cdecl("bjs_asyncRoundTripDirectionDict") public func _bjs_asyncRoundTripDirectionDict() -> Int32 { #if arch(wasm32) - let _tmp_v = [String: Direction].bridgeJSLiftParameter() + let v = [String: Direction].bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_SD9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirectionDict(_: _tmp_v) + return await asyncRoundTripDirectionDict(_: v) } #else fatalError("Only available on WebAssembly") @@ -9536,9 +10420,9 @@ public func _bjs_asyncRoundTripDirectionDict() -> Int32 { @_cdecl("bjs_asyncRoundTripThemeArray") public func _bjs_asyncRoundTripThemeArray() -> Int32 { #if arch(wasm32) - let _tmp_v = [Theme].bridgeJSStackPop() + let v = [Theme].bridgeJSStackPop() return _bjs_makePromise(resolve: Promise_resolve_Sa5ThemeO, reject: Promise_reject) { - return await asyncRoundTripThemeArray(_: _tmp_v) + return await asyncRoundTripThemeArray(_: v) } #else fatalError("Only available on WebAssembly") @@ -9549,9 +10433,9 @@ public func _bjs_asyncRoundTripThemeArray() -> Int32 { @_cdecl("bjs_asyncRoundTripThemeDict") public func _bjs_asyncRoundTripThemeDict() -> Int32 { #if arch(wasm32) - let _tmp_v = [String: Theme].bridgeJSLiftParameter() + let v = [String: Theme].bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_SD5ThemeO, reject: Promise_reject) { - return await asyncRoundTripThemeDict(_: _tmp_v) + return await asyncRoundTripThemeDict(_: v) } #else fatalError("Only available on WebAssembly") @@ -9562,8 +10446,9 @@ public func _bjs_asyncRoundTripThemeDict() -> Int32 { @_cdecl("bjs_asyncRoundTripFileSize") public func _bjs_asyncRoundTripFileSize(_ v: Int64) -> Int32 { #if arch(wasm32) + let v = FileSize.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_8FileSizeO, reject: Promise_reject) { - return await asyncRoundTripFileSize(_: FileSize.bridgeJSLiftParameter(v)) + return await asyncRoundTripFileSize(_: v) } #else fatalError("Only available on WebAssembly") @@ -9574,8 +10459,9 @@ public func _bjs_asyncRoundTripFileSize(_ v: Int64) -> Int32 { @_cdecl("bjs_asyncRoundTripOptionalFileSize") public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int64) -> Int32 { #if arch(wasm32) + let v = Optional.bridgeJSLiftParameter(vIsSome, vValue) return _bjs_makePromise(resolve: Promise_resolve_Sq8FileSizeO, reject: Promise_reject) { - return await asyncRoundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return await asyncRoundTripOptionalFileSize(_: v) } #else fatalError("Only available on WebAssembly") @@ -9586,9 +10472,9 @@ public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int6 @_cdecl("bjs_asyncRoundTripAssociatedValueEnum") public func _bjs_asyncRoundTripAssociatedValueEnum(_ v: Int32) -> Int32 { #if arch(wasm32) - let _tmp_v = AsyncPayloadResult.bridgeJSLiftParameter(v) + let v = AsyncPayloadResult.bridgeJSLiftParameter(v) return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripAssociatedValueEnum(_: _tmp_v) + return await asyncRoundTripAssociatedValueEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -9599,9 +10485,9 @@ public func _bjs_asyncRoundTripAssociatedValueEnum(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ vIsSome: Int32, _ vCaseId: Int32) -> Int32 { #if arch(wasm32) - let _tmp_v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + let v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_v) + return await asyncRoundTripOptionalAssociatedValueEnum(_: v) } #else fatalError("Only available on WebAssembly") @@ -9612,7 +10498,8 @@ public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ vIsSome: Int32, _ v @_cdecl("bjs_setHttpStatus") public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) + let status = HttpStatus.bridgeJSLiftParameter(status) + let ret = setHttpStatus(_: status) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9634,7 +10521,8 @@ public func _bjs_getHttpStatus() -> Int32 { @_cdecl("bjs_setFileSize") public func _bjs_setFileSize(_ size: Int64) -> Int64 { #if arch(wasm32) - let ret = setFileSize(_: FileSize.bridgeJSLiftParameter(size)) + let size = FileSize.bridgeJSLiftParameter(size) + let ret = setFileSize(_: size) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9656,7 +10544,8 @@ public func _bjs_getFileSize() -> Int64 { @_cdecl("bjs_setSessionId") public func _bjs_setSessionId(_ session: Int64) -> Int64 { #if arch(wasm32) - let ret = setSessionId(_: SessionId.bridgeJSLiftParameter(session)) + let session = SessionId.bridgeJSLiftParameter(session) + let ret = setSessionId(_: session) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9678,7 +10567,8 @@ public func _bjs_getSessionId() -> Int64 { @_cdecl("bjs_processTheme") public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int32 { #if arch(wasm32) - let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = Theme.bridgeJSLiftParameter(themeBytes, themeLength) + let ret = processTheme(_: theme) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9689,7 +10579,8 @@ public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int3 @_cdecl("bjs_setTSDirection") public func _bjs_setTSDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) + let direction = TSDirection.bridgeJSLiftParameter(direction) + let ret = setTSDirection(_: direction) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9711,7 +10602,8 @@ public func _bjs_getTSDirection() -> Int32 { @_cdecl("bjs_setTSTheme") public func _bjs_setTSTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) + let theme = TSTheme.bridgeJSLiftParameter(themeBytes, themeLength) + let ret = setTSTheme(_: theme) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9744,7 +10636,9 @@ public func _bjs_createConverter() -> UnsafeMutableRawPointer { @_cdecl("bjs_useConverter") public func _bjs_useConverter(_ converter: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = useConverter(converter: Utils.Converter.bridgeJSLiftParameter(converter), value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let converter = Utils.Converter.bridgeJSLiftParameter(converter) + let ret = useConverter(converter: converter, value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9755,7 +10649,8 @@ public func _bjs_useConverter(_ converter: UnsafeMutableRawPointer, _ value: Int @_cdecl("bjs_roundTripConverterArray") public func _bjs_roundTripConverterArray() -> Void { #if arch(wasm32) - let ret = roundTripConverterArray(_: [Utils.Converter].bridgeJSStackPop()) + let converters = [Utils.Converter].bridgeJSStackPop() + let ret = roundTripConverterArray(_: converters) ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") @@ -9777,7 +10672,8 @@ public func _bjs_createHTTPServer() -> UnsafeMutableRawPointer { @_cdecl("bjs_createUUID") public func _bjs_createUUID(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = createUUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = createUUID(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9788,7 +10684,8 @@ public func _bjs_createUUID(_ valueBytes: Int32, _ valueLength: Int32) -> Unsafe @_cdecl("bjs_roundTripUUID") public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUUID(_: UUID.bridgeJSLiftParameter(uuid)) + let uuid = UUID.bridgeJSLiftParameter(uuid) + let ret = roundTripUUID(_: uuid) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9799,7 +10696,8 @@ public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutable @_cdecl("bjs_roundtripNetworkingAPIMethod") public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripNetworkingAPIMethod(_: Networking.API.Method.bridgeJSLiftParameter(method)) + let method = Networking.API.Method.bridgeJSLiftParameter(method) + let ret = roundtripNetworkingAPIMethod(_: method) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9810,7 +10708,8 @@ public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { @_cdecl("bjs_roundtripConfigurationLogLevel") public func _bjs_roundtripConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Void { #if arch(wasm32) - let ret = roundtripConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) + let level = Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength) + let ret = roundtripConfigurationLogLevel(_: level) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9821,7 +10720,8 @@ public func _bjs_roundtripConfigurationLogLevel(_ levelBytes: Int32, _ levelLeng @_cdecl("bjs_roundtripConfigurationPort") public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripConfigurationPort(_: Configuration.Port.bridgeJSLiftParameter(port)) + let port = Configuration.Port.bridgeJSLiftParameter(port) + let ret = roundtripConfigurationPort(_: port) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9832,7 +10732,8 @@ public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { @_cdecl("bjs_processConfigurationLogLevel") public func _bjs_processConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Int32 { #if arch(wasm32) - let ret = processConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) + let level = Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength) + let ret = processConfigurationLogLevel(_: level) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9843,7 +10744,8 @@ public func _bjs_processConfigurationLogLevel(_ levelBytes: Int32, _ levelLength @_cdecl("bjs_roundtripInternalSupportedMethod") public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripInternalSupportedMethod(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) + let method = Internal.SupportedMethod.bridgeJSLiftParameter(method) + let ret = roundtripInternalSupportedMethod(_: method) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9854,7 +10756,8 @@ public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { @_cdecl("bjs_roundtripAPIResult") public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) + let result = APIResult.bridgeJSLiftParameter(result) + let ret = roundtripAPIResult(result: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9865,7 +10768,8 @@ public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { @_cdecl("bjs_makeAPIResultSuccess") public func _bjs_makeAPIResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = makeAPIResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = makeAPIResultSuccess(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9876,7 +10780,8 @@ public func _bjs_makeAPIResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) @_cdecl("bjs_makeAPIResultFailure") public func _bjs_makeAPIResultFailure(_ value: Int32) -> Void { #if arch(wasm32) - let ret = makeAPIResultFailure(_: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = makeAPIResultFailure(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9898,7 +10803,8 @@ public func _bjs_makeAPIResultInfo() -> Void { @_cdecl("bjs_makeAPIResultFlag") public func _bjs_makeAPIResultFlag(_ value: Int32) -> Void { #if arch(wasm32) - let ret = makeAPIResultFlag(_: Bool.bridgeJSLiftParameter(value)) + let value = Bool.bridgeJSLiftParameter(value) + let ret = makeAPIResultFlag(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9909,7 +10815,8 @@ public func _bjs_makeAPIResultFlag(_ value: Int32) -> Void { @_cdecl("bjs_makeAPIResultRate") public func _bjs_makeAPIResultRate(_ value: Float32) -> Void { #if arch(wasm32) - let ret = makeAPIResultRate(_: Float.bridgeJSLiftParameter(value)) + let value = Float.bridgeJSLiftParameter(value) + let ret = makeAPIResultRate(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9920,7 +10827,8 @@ public func _bjs_makeAPIResultRate(_ value: Float32) -> Void { @_cdecl("bjs_makeAPIResultPrecise") public func _bjs_makeAPIResultPrecise(_ value: Float64) -> Void { #if arch(wasm32) - let ret = makeAPIResultPrecise(_: Double.bridgeJSLiftParameter(value)) + let value = Double.bridgeJSLiftParameter(value) + let ret = makeAPIResultPrecise(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9931,7 +10839,8 @@ public func _bjs_makeAPIResultPrecise(_ value: Float64) -> Void { @_cdecl("bjs_roundtripComplexResult") public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) + let result = ComplexResult.bridgeJSLiftParameter(result) + let ret = roundtripComplexResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9942,7 +10851,8 @@ public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { @_cdecl("bjs_makeComplexResultSuccess") public func _bjs_makeComplexResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = makeComplexResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = makeComplexResultSuccess(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9953,7 +10863,9 @@ public func _bjs_makeComplexResultSuccess(_ valueBytes: Int32, _ valueLength: In @_cdecl("bjs_makeComplexResultError") public func _bjs_makeComplexResultError(_ messageBytes: Int32, _ messageLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = makeComplexResultError(_: String.bridgeJSLiftParameter(messageBytes, messageLength), _: Int.bridgeJSLiftParameter(code)) + let code = Int.bridgeJSLiftParameter(code) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let ret = makeComplexResultError(_: message, _: code) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9964,7 +10876,10 @@ public func _bjs_makeComplexResultError(_ messageBytes: Int32, _ messageLength: @_cdecl("bjs_makeComplexResultLocation") public func _bjs_makeComplexResultLocation(_ lat: Float64, _ lng: Float64, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = makeComplexResultLocation(_: Double.bridgeJSLiftParameter(lat), _: Double.bridgeJSLiftParameter(lng), _: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let lng = Double.bridgeJSLiftParameter(lng) + let lat = Double.bridgeJSLiftParameter(lat) + let ret = makeComplexResultLocation(_: lat, _: lng, _: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9975,7 +10890,10 @@ public func _bjs_makeComplexResultLocation(_ lat: Float64, _ lng: Float64, _ nam @_cdecl("bjs_makeComplexResultStatus") public func _bjs_makeComplexResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = makeComplexResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let code = Int.bridgeJSLiftParameter(code) + let active = Bool.bridgeJSLiftParameter(active) + let ret = makeComplexResultStatus(_: active, _: code, _: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9986,7 +10904,10 @@ public func _bjs_makeComplexResultStatus(_ active: Int32, _ code: Int32, _ messa @_cdecl("bjs_makeComplexResultCoordinates") public func _bjs_makeComplexResultCoordinates(_ x: Float64, _ y: Float64, _ z: Float64) -> Void { #if arch(wasm32) - let ret = makeComplexResultCoordinates(_: Double.bridgeJSLiftParameter(x), _: Double.bridgeJSLiftParameter(y), _: Double.bridgeJSLiftParameter(z)) + let z = Double.bridgeJSLiftParameter(z) + let y = Double.bridgeJSLiftParameter(y) + let x = Double.bridgeJSLiftParameter(x) + let ret = makeComplexResultCoordinates(_: x, _: y, _: z) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -9997,7 +10918,16 @@ public func _bjs_makeComplexResultCoordinates(_ x: Float64, _ y: Float64, _ z: F @_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 = 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)) + let text3 = String.bridgeJSLiftParameter(text3Bytes, text3Length) + let text2 = String.bridgeJSLiftParameter(text2Bytes, text2Length) + let text1 = String.bridgeJSLiftParameter(text1Bytes, text1Length) + let value2 = Double.bridgeJSLiftParameter(value2) + let value1 = Double.bridgeJSLiftParameter(value1) + let count2 = Int.bridgeJSLiftParameter(count2) + let count1 = Int.bridgeJSLiftParameter(count1) + let flag2 = Bool.bridgeJSLiftParameter(flag2) + let flag1 = Bool.bridgeJSLiftParameter(flag1) + let ret = makeComplexResultComprehensive(_: flag1, _: flag2, _: count1, _: count2, _: value1, _: value2, _: text1, _: text2, _: text3) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10019,7 +10949,8 @@ public func _bjs_makeComplexResultInfo() -> Void { @_cdecl("bjs_makeUtilitiesResultSuccess") public func _bjs_makeUtilitiesResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let ret = makeUtilitiesResultSuccess(_: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10030,7 +10961,9 @@ public func _bjs_makeUtilitiesResultSuccess(_ messageBytes: Int32, _ messageLeng @_cdecl("bjs_makeUtilitiesResultFailure") public func _bjs_makeUtilitiesResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let code = Int.bridgeJSLiftParameter(code) + let error = String.bridgeJSLiftParameter(errorBytes, errorLength) + let ret = makeUtilitiesResultFailure(_: error, _: code) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10041,7 +10974,10 @@ 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 message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let code = Int.bridgeJSLiftParameter(code) + let active = Bool.bridgeJSLiftParameter(active) + let ret = makeUtilitiesResultStatus(_: active, _: code, _: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10052,7 +10988,8 @@ public func _bjs_makeUtilitiesResultStatus(_ active: Int32, _ code: Int32, _ mes @_cdecl("bjs_makeAPINetworkingResultSuccess") public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let message = String.bridgeJSLiftParameter(messageBytes, messageLength) + let ret = makeAPINetworkingResultSuccess(_: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10063,7 +11000,9 @@ public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ message @_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)) + let code = Int.bridgeJSLiftParameter(code) + let error = String.bridgeJSLiftParameter(errorBytes, errorLength) + let ret = makeAPINetworkingResultFailure(_: error, _: code) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10074,7 +11013,8 @@ public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLeng @_cdecl("bjs_roundtripUtilitiesResult") public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + let result = Utilities.Result.bridgeJSLiftParameter(result) + let ret = roundtripUtilitiesResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10085,7 +11025,8 @@ public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { @_cdecl("bjs_roundtripAPINetworkingResult") public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + let result = API.NetworkingResult.bridgeJSLiftParameter(result) + let ret = roundtripAPINetworkingResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10096,7 +11037,8 @@ public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripAllTypesResult") public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + let result = AllTypesResult.bridgeJSLiftParameter(result) + let ret = roundTripAllTypesResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10107,7 +11049,8 @@ public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripTypedPayloadResult") public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + let result = TypedPayloadResult.bridgeJSLiftParameter(result) + let ret = roundTripTypedPayloadResult(_: result) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10118,7 +11061,13 @@ public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { @_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)) + let jsObject = JSObject.bridgeJSLiftParameter(jsObject) + let stringValue = String.bridgeJSLiftParameter(stringValueBytes, stringValueLength) + let boolValue = Bool.bridgeJSLiftParameter(boolValue) + let doubleValue = Double.bridgeJSLiftParameter(doubleValue) + let floatValue = Float.bridgeJSLiftParameter(floatValue) + let intValue = Int.bridgeJSLiftParameter(intValue) + let ret = createPropertyHolder(intValue: intValue, floatValue: floatValue, doubleValue: doubleValue, boolValue: boolValue, stringValue: stringValue, jsObject: jsObject) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10129,7 +11078,8 @@ public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, @_cdecl("bjs_testPropertyHolder") public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + let holder = PropertyHolder.bridgeJSLiftParameter(holder) + let ret = testPropertyHolder(holder: holder) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10161,7 +11111,9 @@ public func _bjs_getObserverStats() -> Void { @_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)) + let transform = _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = formatName(_: name, transform: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10172,7 +11124,8 @@ public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform @_cdecl("bjs_makeFormatter") public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let ret = makeFormatter(prefix: prefix) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10183,7 +11136,8 @@ public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> I @_cdecl("bjs_makeAdder") public func _bjs_makeAdder(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) + let base = Int.bridgeJSLiftParameter(base) + let ret = makeAdder(base: base) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10194,7 +11148,8 @@ public func _bjs_makeAdder(_ base: Int32) -> Int32 { @_cdecl("bjs_roundTripMessage") public func _bjs_roundTripMessage(_ message: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMessage(_: Message.bridgeJSLiftParameter(message)) + let message = Message.bridgeJSLiftParameter(message) + let ret = roundTripMessage(_: message) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10205,7 +11160,8 @@ public func _bjs_roundTripMessage(_ message: Int32) -> Void { @_cdecl("bjs_renamedEcho") public func _bjs_renamedEcho(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = jsNameEcho(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = jsNameEcho(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10216,7 +11172,8 @@ public func _bjs_renamedEcho(_ valueBytes: Int32, _ valueLength: Int32) -> Void @_cdecl("bjs_greetName") public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = greet(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = greet(_: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10227,7 +11184,8 @@ public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { @_cdecl("bjs_greetCount") public func _bjs_greetCount(_ count: Int32) -> Void { #if arch(wasm32) - let ret = greet(_: Int.bridgeJSLiftParameter(count)) + let count = Int.bridgeJSLiftParameter(count) + let ret = greet(_: count) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10238,7 +11196,8 @@ public func _bjs_greetCount(_ count: Int32) -> Void { @_cdecl("bjs_roundTripPointerFields") public func _bjs_roundTripPointerFields() -> Void { #if arch(wasm32) - let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) + let value = PointerFields.bridgeJSLiftParameter() + let ret = roundTripPointerFields(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10249,7 +11208,8 @@ public func _bjs_roundTripPointerFields() -> Void { @_cdecl("bjs_testStructDefault") public func _bjs_testStructDefault() -> Void { #if arch(wasm32) - let ret = testStructDefault(point: DataPoint.bridgeJSLiftParameter()) + let point = DataPoint.bridgeJSLiftParameter() + let ret = testStructDefault(point: point) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10260,7 +11220,8 @@ public func _bjs_testStructDefault() -> Void { @_cdecl("bjs_cartToJSObject") public func _bjs_cartToJSObject() -> Int32 { #if arch(wasm32) - let ret = cartToJSObject(_: CopyableCart.bridgeJSLiftParameter()) + let cart = CopyableCart.bridgeJSLiftParameter() + let ret = cartToJSObject(_: cart) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10271,7 +11232,8 @@ public func _bjs_cartToJSObject() -> Int32 { @_cdecl("bjs_nestedCartToJSObject") public func _bjs_nestedCartToJSObject() -> Int32 { #if arch(wasm32) - let ret = nestedCartToJSObject(_: CopyableNestedCart.bridgeJSLiftParameter()) + let cart = CopyableNestedCart.bridgeJSLiftParameter() + let ret = nestedCartToJSObject(_: cart) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10282,7 +11244,8 @@ public func _bjs_nestedCartToJSObject() -> Int32 { @_cdecl("bjs_roundTripDataPoint") public func _bjs_roundTripDataPoint() -> Void { #if arch(wasm32) - let ret = roundTripDataPoint(_: DataPoint.bridgeJSLiftParameter()) + let data = DataPoint.bridgeJSLiftParameter() + let ret = roundTripDataPoint(_: data) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10293,7 +11256,8 @@ public func _bjs_roundTripDataPoint() -> Void { @_cdecl("bjs_roundTripPublicPoint") public func _bjs_roundTripPublicPoint() -> Void { #if arch(wasm32) - let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) + let point = PublicPoint.bridgeJSLiftParameter() + let ret = roundTripPublicPoint(_: point) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10304,9 +11268,9 @@ public func _bjs_roundTripPublicPoint() -> Void { @_cdecl("bjs_asyncRoundTripPublicPoint") public func _bjs_asyncRoundTripPublicPoint() -> Int32 { #if arch(wasm32) - let _tmp_point = PublicPoint.bridgeJSLiftParameter() + let point = PublicPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPoint(_: _tmp_point) + return await asyncRoundTripPublicPoint(_: point) } #else fatalError("Only available on WebAssembly") @@ -10317,9 +11281,9 @@ public func _bjs_asyncRoundTripPublicPoint() -> Int32 { @_cdecl("bjs_asyncRoundTripPublicPointThrows") public func _bjs_asyncRoundTripPublicPointThrows() -> Int32 { #if arch(wasm32) - let _tmp_point = PublicPoint.bridgeJSLiftParameter() + let point = PublicPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in - return try await asyncRoundTripPublicPointThrows(_: _tmp_point) + return try await asyncRoundTripPublicPointThrows(_: point) } #else fatalError("Only available on WebAssembly") @@ -10330,8 +11294,9 @@ public func _bjs_asyncRoundTripPublicPointThrows() -> Int32 { @_cdecl("bjs_asyncStructOrThrow") public func _bjs_asyncStructOrThrow(_ shouldThrow: Int32) -> Int32 { #if arch(wasm32) + let shouldThrow = Bool.bridgeJSLiftParameter(shouldThrow) return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in - return try await asyncStructOrThrow(_: Bool.bridgeJSLiftParameter(shouldThrow)) + return try await asyncStructOrThrow(_: shouldThrow) } #else fatalError("Only available on WebAssembly") @@ -10342,10 +11307,10 @@ public func _bjs_asyncStructOrThrow(_ shouldThrow: Int32) -> Int32 { @_cdecl("bjs_asyncCombinePublicPoints") public func _bjs_asyncCombinePublicPoints() -> Int32 { #if arch(wasm32) - let _tmp_b = PublicPoint.bridgeJSLiftParameter() - let _tmp_a = PublicPoint.bridgeJSLiftParameter() + let b = PublicPoint.bridgeJSLiftParameter() + let a = PublicPoint.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await asyncCombinePublicPoints(_: _tmp_a, _: _tmp_b) + return await asyncCombinePublicPoints(_: a, _: b) } #else fatalError("Only available on WebAssembly") @@ -10356,9 +11321,9 @@ public func _bjs_asyncCombinePublicPoints() -> Int32 { @_cdecl("bjs_asyncRoundTripContact") public func _bjs_asyncRoundTripContact() -> Int32 { #if arch(wasm32) - let _tmp_contact = Contact.bridgeJSLiftParameter() + let contact = Contact.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_7ContactV, reject: Promise_reject) { - return await asyncRoundTripContact(_: _tmp_contact) + return await asyncRoundTripContact(_: contact) } #else fatalError("Only available on WebAssembly") @@ -10369,9 +11334,9 @@ public func _bjs_asyncRoundTripContact() -> Int32 { @_cdecl("bjs_asyncRoundTripPublicPointArray") public func _bjs_asyncRoundTripPublicPointArray() -> Int32 { #if arch(wasm32) - let _tmp_points = [PublicPoint].bridgeJSStackPop() + let points = [PublicPoint].bridgeJSStackPop() return _bjs_makePromise(resolve: Promise_resolve_Sa11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPointArray(_: _tmp_points) + return await asyncRoundTripPublicPointArray(_: points) } #else fatalError("Only available on WebAssembly") @@ -10382,9 +11347,9 @@ public func _bjs_asyncRoundTripPublicPointArray() -> Int32 { @_cdecl("bjs_asyncRoundTripOptionalPublicPoint") public func _bjs_asyncRoundTripOptionalPublicPoint() -> Int32 { #if arch(wasm32) - let _tmp_point = Optional.bridgeJSLiftParameter() + let point = Optional.bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_Sq11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripOptionalPublicPoint(_: _tmp_point) + return await asyncRoundTripOptionalPublicPoint(_: point) } #else fatalError("Only available on WebAssembly") @@ -10395,9 +11360,9 @@ public func _bjs_asyncRoundTripOptionalPublicPoint() -> Int32 { @_cdecl("bjs_asyncRoundTripPublicPointDict") public func _bjs_asyncRoundTripPublicPointDict() -> Int32 { #if arch(wasm32) - let _tmp_points = [String: PublicPoint].bridgeJSLiftParameter() + let points = [String: PublicPoint].bridgeJSLiftParameter() return _bjs_makePromise(resolve: Promise_resolve_SD11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPointDict(_: _tmp_points) + return await asyncRoundTripPublicPointDict(_: points) } #else fatalError("Only available on WebAssembly") @@ -10408,7 +11373,8 @@ public func _bjs_asyncRoundTripPublicPointDict() -> Int32 { @_cdecl("bjs_roundTripContact") public func _bjs_roundTripContact() -> Void { #if arch(wasm32) - let ret = roundTripContact(_: Contact.bridgeJSLiftParameter()) + let contact = Contact.bridgeJSLiftParameter() + let ret = roundTripContact(_: contact) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10419,7 +11385,8 @@ public func _bjs_roundTripContact() -> Void { @_cdecl("bjs_roundTripConfig") public func _bjs_roundTripConfig() -> Void { #if arch(wasm32) - let ret = roundTripConfig(_: Config.bridgeJSLiftParameter()) + let config = Config.bridgeJSLiftParameter() + let ret = roundTripConfig(_: config) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10430,7 +11397,8 @@ public func _bjs_roundTripConfig() -> Void { @_cdecl("bjs_roundTripSessionData") public func _bjs_roundTripSessionData() -> Void { #if arch(wasm32) - let ret = roundTripSessionData(_: SessionData.bridgeJSLiftParameter()) + let session = SessionData.bridgeJSLiftParameter() + let ret = roundTripSessionData(_: session) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10441,7 +11409,8 @@ public func _bjs_roundTripSessionData() -> Void { @_cdecl("bjs_roundTripValidationReport") public func _bjs_roundTripValidationReport() -> Void { #if arch(wasm32) - let ret = roundTripValidationReport(_: ValidationReport.bridgeJSLiftParameter()) + let report = ValidationReport.bridgeJSLiftParameter() + let ret = roundTripValidationReport(_: report) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10452,7 +11421,8 @@ public func _bjs_roundTripValidationReport() -> Void { @_cdecl("bjs_roundTripAdvancedConfig") public func _bjs_roundTripAdvancedConfig() -> Void { #if arch(wasm32) - let ret = roundTripAdvancedConfig(_: AdvancedConfig.bridgeJSLiftParameter()) + let config = AdvancedConfig.bridgeJSLiftParameter() + let ret = roundTripAdvancedConfig(_: config) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10463,7 +11433,8 @@ public func _bjs_roundTripAdvancedConfig() -> Void { @_cdecl("bjs_roundTripMeasurementConfig") public func _bjs_roundTripMeasurementConfig() -> Void { #if arch(wasm32) - let ret = roundTripMeasurementConfig(_: MeasurementConfig.bridgeJSLiftParameter()) + let config = MeasurementConfig.bridgeJSLiftParameter() + let ret = roundTripMeasurementConfig(_: config) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10474,9 +11445,9 @@ public func _bjs_roundTripMeasurementConfig() -> Void { @_cdecl("bjs_updateValidationReport") public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCaseId: Int32) -> Void { #if arch(wasm32) - let _tmp_report = ValidationReport.bridgeJSLiftParameter() - let _tmp_newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) - let ret = updateValidationReport(_: _tmp_newResult, _: _tmp_report) + let report = ValidationReport.bridgeJSLiftParameter() + let newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) + let ret = updateValidationReport(_: newResult, _: report) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10487,7 +11458,8 @@ public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCas @_cdecl("bjs_testContainerWithStruct") public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testContainerWithStruct(_: DataPoint.bridgeJSLiftParameter()) + let point = DataPoint.bridgeJSLiftParameter() + let ret = testContainerWithStruct(_: point) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10498,7 +11470,8 @@ public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { @_cdecl("bjs_roundTripJSObjectContainer") public func _bjs_roundTripJSObjectContainer() -> Void { #if arch(wasm32) - let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) + let container = JSObjectContainer.bridgeJSLiftParameter() + let ret = roundTripJSObjectContainer(_: container) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10509,7 +11482,8 @@ public func _bjs_roundTripJSObjectContainer() -> Void { @_cdecl("bjs_roundTripFooContainer") public func _bjs_roundTripFooContainer() -> Void { #if arch(wasm32) - let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) + let container = FooContainer.bridgeJSLiftParameter() + let ret = roundTripFooContainer(_: container) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10520,7 +11494,8 @@ public func _bjs_roundTripFooContainer() -> Void { @_cdecl("bjs_roundTripArrayMembers") public func _bjs_roundTripArrayMembers() -> Void { #if arch(wasm32) - let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) + let value = ArrayMembers.bridgeJSLiftParameter() + let ret = roundTripArrayMembers(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10531,9 +11506,9 @@ public func _bjs_roundTripArrayMembers() -> Void { @_cdecl("bjs_arrayMembersSum") public func _bjs_arrayMembersSum() -> Int32 { #if arch(wasm32) - let _tmp_values = [Int].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) + let values = [Int].bridgeJSStackPop() + let value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersSum(_: value, _: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10544,9 +11519,9 @@ public func _bjs_arrayMembersSum() -> Int32 { @_cdecl("bjs_arrayMembersFirst") public func _bjs_arrayMembersFirst() -> Void { #if arch(wasm32) - let _tmp_values = [String].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) + let values = [String].bridgeJSStackPop() + let value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersFirst(_: value, _: values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10557,7 +11532,9 @@ public func _bjs_arrayMembersFirst() -> Void { @_cdecl("bjs_PolygonReference_init") public func _bjs_PolygonReference_init(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference(verticesData: [Double].bridgeJSStackPop(), label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let verticesData = [Double].bridgeJSStackPop() + let ret = PolygonReference(verticesData: verticesData, label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10568,7 +11545,8 @@ public func _bjs_PolygonReference_init(_ labelBytes: Int32, _ labelLength: Int32 @_cdecl("bjs_PolygonReference_vertexCount") public func _bjs_PolygonReference_vertexCount(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).vertexCount() + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.vertexCount() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10579,7 +11557,8 @@ public func _bjs_PolygonReference_vertexCount(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_PolygonReference_summary") public func _bjs_PolygonReference_summary(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).summary() + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.summary() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10590,7 +11569,8 @@ public func _bjs_PolygonReference_summary(_ _self: UnsafeMutableRawPointer) -> V @_cdecl("bjs_PolygonReference_snapshot") public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.snapshot() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10601,7 +11581,9 @@ 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.bridgeJSLiftParameter(other)) + let other = Polygon.bridgeJSLiftParameter(other) + let _self = PolygonReference.bridgeJSLiftParameter(_self) + let ret = _self.merge(_: other) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10612,7 +11594,8 @@ public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ othe @_cdecl("bjs_PolygonReference_static_origin") public func _bjs_PolygonReference_static_origin(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference.origin(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let ret = PolygonReference.origin(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10654,7 +11637,8 @@ fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPo @_cdecl("bjs_TagReference_describe") public func _bjs_TagReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TagReference.bridgeJSLiftParameter(_self).describe() + let _self = TagReference.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10696,7 +11680,9 @@ fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointe @_cdecl("bjs_TagHolderReference_init") public func _bjs_TagHolderReference_init(_ tag: UnsafeMutableRawPointer, _ version: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TagHolderReference(tag: Tag.bridgeJSLiftParameter(tag), version: Int.bridgeJSLiftParameter(version)) + let version = Int.bridgeJSLiftParameter(version) + let tag = Tag.bridgeJSLiftParameter(tag) + let ret = TagHolderReference(tag: tag, version: version) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10707,7 +11693,8 @@ public func _bjs_TagHolderReference_init(_ tag: UnsafeMutableRawPointer, _ versi @_cdecl("bjs_TagHolderReference_describe") public func _bjs_TagHolderReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).describe() + let _self = TagHolderReference.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10718,7 +11705,8 @@ public func _bjs_TagHolderReference_describe(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_TagHolderReference_tag_get") public func _bjs_TagHolderReference_tag_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).tag + let _self = TagHolderReference.bridgeJSLiftParameter(_self) + let ret = _self.tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10729,7 +11717,9 @@ public func _bjs_TagHolderReference_tag_get(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_TagHolderReference_tag_set") public func _bjs_TagHolderReference_tag_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - TagHolderReference.bridgeJSLiftParameter(_self).tag = Tag.bridgeJSLiftParameter(value) + let value = Tag.bridgeJSLiftParameter(value) + let _self = TagHolderReference.bridgeJSLiftParameter(_self) + _self.tag = value #else fatalError("Only available on WebAssembly") #endif @@ -10739,7 +11729,8 @@ public func _bjs_TagHolderReference_tag_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_TagHolderReference_version_get") public func _bjs_TagHolderReference_version_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).version + let _self = TagHolderReference.bridgeJSLiftParameter(_self) + let ret = _self.version return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10750,7 +11741,9 @@ public func _bjs_TagHolderReference_version_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_TagHolderReference_version_set") public func _bjs_TagHolderReference_version_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - TagHolderReference.bridgeJSLiftParameter(_self).version = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = TagHolderReference.bridgeJSLiftParameter(_self) + _self.version = value #else fatalError("Only available on WebAssembly") #endif @@ -10791,7 +11784,8 @@ fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRaw @_cdecl("bjs_PriorityReference_describe") public func _bjs_PriorityReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PriorityReference.bridgeJSLiftParameter(_self).describe() + let _self = PriorityReference.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10802,7 +11796,8 @@ public func _bjs_PriorityReference_describe(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_PriorityReference_weight") public func _bjs_PriorityReference_weight(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PriorityReference.bridgeJSLiftParameter(_self).weight() + let _self = PriorityReference.bridgeJSLiftParameter(_self) + let ret = _self.weight() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10877,7 +11872,8 @@ fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawP @_cdecl("bjs_ClosureSupportExports_static_makeIntToInt") public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeIntToInt(_: Int.bridgeJSLiftParameter(base)) + let base = Int.bridgeJSLiftParameter(base) + let ret = ClosureSupportExports.makeIntToInt(_: base) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10888,7 +11884,8 @@ public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int @_cdecl("bjs_ClosureSupportExports_static_makeDoubleToDouble") public func _bjs_ClosureSupportExports_static_makeDoubleToDouble(_ base: Float64) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + let base = Double.bridgeJSLiftParameter(base) + let ret = ClosureSupportExports.makeDoubleToDouble(_: base) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10899,7 +11896,8 @@ public func _bjs_ClosureSupportExports_static_makeDoubleToDouble(_ base: Float64 @_cdecl("bjs_ClosureSupportExports_static_makeStringToString") public func _bjs_ClosureSupportExports_static_makeStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let ret = ClosureSupportExports.makeStringToString(_: prefix) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10910,7 +11908,8 @@ public func _bjs_ClosureSupportExports_static_makeStringToString(_ prefixBytes: @_cdecl("bjs_ClosureSupportExports_static_makeJSIntToInt") public func _bjs_ClosureSupportExports_static_makeJSIntToInt(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSIntToInt(_: Int.bridgeJSLiftParameter(base)) + let base = Int.bridgeJSLiftParameter(base) + let ret = ClosureSupportExports.makeJSIntToInt(_: base) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10921,7 +11920,8 @@ public func _bjs_ClosureSupportExports_static_makeJSIntToInt(_ base: Int32) -> I @_cdecl("bjs_ClosureSupportExports_static_makeJSDoubleToDouble") public func _bjs_ClosureSupportExports_static_makeJSDoubleToDouble(_ base: Float64) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + let base = Double.bridgeJSLiftParameter(base) + let ret = ClosureSupportExports.makeJSDoubleToDouble(_: base) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10932,13 +11932,25 @@ public func _bjs_ClosureSupportExports_static_makeJSDoubleToDouble(_ base: Float @_cdecl("bjs_ClosureSupportExports_static_makeJSStringToString") public func _bjs_ClosureSupportExports_static_makeJSStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let ret = ClosureSupportExports.makeJSStringToString(_: prefix) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } +@_expose(wasm, "bjs_ClosureSupportExports_static_makeArrayDifference") +@_cdecl("bjs_ClosureSupportExports_static_makeArrayDifference") +public func _bjs_ClosureSupportExports_static_makeArrayDifference() -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeArrayDifference() + return JSTypedClosure(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 { @@ -10974,7 +11986,8 @@ fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutable @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Workspace(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -10985,7 +11998,8 @@ public func _bjs_Workspace_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsa @_cdecl("bjs_Workspace_describe") public func _bjs_Workspace_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Workspace.bridgeJSLiftParameter(_self).describe() + let _self = Workspace.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11027,7 +12041,12 @@ fileprivate func _bjs_Workspace_wrap_extern(_ pointer: UnsafeMutableRawPointer) @_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 = 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 tag = Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength) + let status = Status.bridgeJSLiftParameter(status) + let enabled = Bool.bridgeJSLiftParameter(enabled) + let count = Int.bridgeJSLiftParameter(count) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = DefaultArgumentConstructorDefaults(name: name, count: count, enabled: enabled, status: status, tag: tag) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11038,7 +12057,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_init(_ nameBytes: Int32, _ n @_cdecl("bjs_DefaultArgumentConstructorDefaults_describe") public func _bjs_DefaultArgumentConstructorDefaults_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).describe() + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11049,7 +12069,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_describe(_ _self: UnsafeMuta @_cdecl("bjs_DefaultArgumentConstructorDefaults_name_get") public func _bjs_DefaultArgumentConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11060,7 +12081,9 @@ public func _bjs_DefaultArgumentConstructorDefaults_name_get(_ _self: UnsafeMuta @_cdecl("bjs_DefaultArgumentConstructorDefaults_name_set") public func _bjs_DefaultArgumentConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -11070,7 +12093,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_name_set(_ _self: UnsafeMuta @_cdecl("bjs_DefaultArgumentConstructorDefaults_count_get") public func _bjs_DefaultArgumentConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).count + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11081,7 +12105,9 @@ public func _bjs_DefaultArgumentConstructorDefaults_count_get(_ _self: UnsafeMut @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif @@ -11091,7 +12117,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_count_set(_ _self: UnsafeMut @_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_get") public func _bjs_DefaultArgumentConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.enabled return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11102,7 +12129,9 @@ public func _bjs_DefaultArgumentConstructorDefaults_enabled_get(_ _self: UnsafeM @_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_set") public func _bjs_DefaultArgumentConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + _self.enabled = value #else fatalError("Only available on WebAssembly") #endif @@ -11112,7 +12141,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_enabled_set(_ _self: UnsafeM @_cdecl("bjs_DefaultArgumentConstructorDefaults_status_get") public func _bjs_DefaultArgumentConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.status return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11123,7 +12153,9 @@ public func _bjs_DefaultArgumentConstructorDefaults_status_get(_ _self: UnsafeMu @_cdecl("bjs_DefaultArgumentConstructorDefaults_status_set") public func _bjs_DefaultArgumentConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) + let value = Status.bridgeJSLiftParameter(value) + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + _self.status = value #else fatalError("Only available on WebAssembly") #endif @@ -11133,7 +12165,8 @@ public func _bjs_DefaultArgumentConstructorDefaults_status_set(_ _self: UnsafeMu @_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_get") public func _bjs_DefaultArgumentConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + let ret = _self.tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11144,7 +12177,9 @@ public func _bjs_DefaultArgumentConstructorDefaults_tag_get(_ _self: UnsafeMutab @_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_set") public func _bjs_DefaultArgumentConstructorDefaults_tag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self) + _self.tag = value #else fatalError("Only available on WebAssembly") #endif @@ -11185,7 +12220,8 @@ fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap_extern(_ pointer: @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Greeter(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11196,7 +12232,8 @@ public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Greeter_greet") public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11207,7 +12244,9 @@ public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_changeName") public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.changeName(name: name) #else fatalError("Only available on WebAssembly") #endif @@ -11217,7 +12256,10 @@ public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameByte @_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)) + let customGreeting = _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLift(customGreeting) + let greeter = Greeter.bridgeJSLiftParameter(greeter) + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greetWith(greeter: greeter, customGreeting: customGreeting) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11228,7 +12270,9 @@ public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: @_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)) + let suffix = String.bridgeJSLiftParameter(suffixBytes, suffixLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.makeFormatter(suffix: suffix) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11239,7 +12283,8 @@ public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffi @_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)) + let defaultName = String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength) + let ret = Greeter.makeCreator(defaultName: defaultName) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11250,7 +12295,8 @@ public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ default @_cdecl("bjs_Greeter_makeCustomGreeter") public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).makeCustomGreeter() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.makeCustomGreeter() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11261,7 +12307,8 @@ public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_Greeter_greetEnthusiastically") public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.greetEnthusiastically() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11283,7 +12330,8 @@ public func _bjs_Greeter_static_greetAnonymously() -> Void { @_cdecl("bjs_Greeter_name_get") public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11294,7 +12342,9 @@ public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Greeter.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -11304,7 +12354,8 @@ public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes @_cdecl("bjs_Greeter_prefix_get") public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).prefix + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.prefix return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11315,7 +12366,8 @@ public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { @_cdecl("bjs_Greeter_nameCount_get") public func _bjs_Greeter_nameCount_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).nameCount + let _self = Greeter.bridgeJSLiftParameter(_self) + let ret = _self.nameCount return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11368,7 +12420,9 @@ fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> @_cdecl("bjs_Calculator_square") public func _bjs_Calculator_square(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.bridgeJSLiftParameter(_self).square(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Calculator.bridgeJSLiftParameter(_self) + let ret = _self.square(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11379,7 +12433,10 @@ public func _bjs_Calculator_square(_ _self: UnsafeMutableRawPointer, _ value: In @_cdecl("bjs_Calculator_add") public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = Calculator.bridgeJSLiftParameter(_self).add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let _self = Calculator.bridgeJSLiftParameter(_self) + let ret = _self.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11390,8 +12447,11 @@ public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ @_cdecl("bjs_Calculator_asyncMakePoint") public func _bjs_Calculator_asyncMakePoint(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) + let y = Int.bridgeJSLiftParameter(y) + let x = Int.bridgeJSLiftParameter(x) + let _self = Calculator.bridgeJSLiftParameter(_self) return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await Calculator.bridgeJSLiftParameter(_self).asyncMakePoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + return await _self.asyncMakePoint(x: x, y: y) } #else fatalError("Only available on WebAssembly") @@ -11537,7 +12597,9 @@ public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Utils_Converter_toString") public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.toString(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11548,7 +12610,8 @@ public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ va @_cdecl("bjs_Utils_Converter_precision_get") public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + let ret = _self.precision return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11559,7 +12622,9 @@ public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_Utils_Converter_precision_set") public func _bjs_Utils_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = Utils.Converter.bridgeJSLiftParameter(_self) + _self.precision = value #else fatalError("Only available on WebAssembly") #endif @@ -11611,7 +12676,9 @@ public func _bjs_Networking_API_HTTPServer_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Networking_API_HTTPServer_call") public func _bjs_Networking_API_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) + let method = Networking.API.Method.bridgeJSLiftParameter(method) + let _self = Networking.API.HTTPServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -11652,7 +12719,8 @@ fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMut @_cdecl("bjs___Swift_Foundation_UUID_init") public func _bjs___Swift_Foundation_UUID_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = UUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = UUID(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11663,7 +12731,8 @@ public func _bjs___Swift_Foundation_UUID_init(_ valueBytes: Int32, _ valueLength @_cdecl("bjs___Swift_Foundation_UUID_uuidString") public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = UUID.bridgeJSLiftParameter(_self).uuidString() + let _self = UUID.bridgeJSLiftParameter(_self) + let ret = _self.uuidString() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11674,7 +12743,8 @@ public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPoi @_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 = UUID.fromValue(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = UUID.fromValue(_: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11738,7 +12808,9 @@ public func _bjs_Networking_APIV2_Internal_TestServer_init() -> UnsafeMutableRaw @_cdecl("bjs_Networking_APIV2_Internal_TestServer_call") public func _bjs_Networking_APIV2_Internal_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) + let method = Internal.SupportedMethod.bridgeJSLiftParameter(method) + let _self = Internal.TestServer.bridgeJSLiftParameter(_self) + _self.call(_: method) #else fatalError("Only available on WebAssembly") #endif @@ -11779,7 +12851,8 @@ fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer @_cdecl("bjs_SimplePropertyHolder_init") public func _bjs_SimplePropertyHolder_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SimplePropertyHolder(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = SimplePropertyHolder(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11790,7 +12863,8 @@ public func _bjs_SimplePropertyHolder_init(_ value: Int32) -> UnsafeMutableRawPo @_cdecl("bjs_SimplePropertyHolder_value_get") public func _bjs_SimplePropertyHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SimplePropertyHolder.bridgeJSLiftParameter(_self).value + let _self = SimplePropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11801,7 +12875,9 @@ public func _bjs_SimplePropertyHolder_value_get(_ _self: UnsafeMutableRawPointer @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = SimplePropertyHolder.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -11842,7 +12918,14 @@ fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableR @_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) - 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 sibling = SimplePropertyHolder.bridgeJSLiftParameter(sibling) + let jsObject = JSObject.bridgeJSLiftParameter(jsObject) + let stringValue = String.bridgeJSLiftParameter(stringValueBytes, stringValueLength) + let boolValue = Bool.bridgeJSLiftParameter(boolValue) + let doubleValue = Double.bridgeJSLiftParameter(doubleValue) + let floatValue = Float.bridgeJSLiftParameter(floatValue) + let intValue = Int.bridgeJSLiftParameter(intValue) + let ret = PropertyHolder(intValue: intValue, floatValue: floatValue, doubleValue: doubleValue, boolValue: boolValue, stringValue: stringValue, jsObject: jsObject, sibling: sibling) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11853,7 +12936,8 @@ public func _bjs_PropertyHolder_init(_ intValue: Int32, _ floatValue: Float32, _ @_cdecl("bjs_PropertyHolder_getAllValues") public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).getAllValues() + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.getAllValues() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11864,7 +12948,8 @@ public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_intValue_get") public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).intValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.intValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11875,7 +12960,9 @@ public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_intValue_set") public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).intValue = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.intValue = value #else fatalError("Only available on WebAssembly") #endif @@ -11885,7 +12972,8 @@ public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_floatValue_get") public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).floatValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.floatValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11896,7 +12984,9 @@ public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Float.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.floatValue = value #else fatalError("Only available on WebAssembly") #endif @@ -11906,7 +12996,8 @@ public func _bjs_PropertyHolder_floatValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_doubleValue_get") public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).doubleValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.doubleValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11917,7 +13008,9 @@ public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer @_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) + let value = Double.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.doubleValue = value #else fatalError("Only available on WebAssembly") #endif @@ -11927,7 +13020,8 @@ public func _bjs_PropertyHolder_doubleValue_set(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_boolValue_get") public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).boolValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.boolValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11938,7 +13032,9 @@ public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Bool.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.boolValue = value #else fatalError("Only available on WebAssembly") #endif @@ -11948,7 +13044,8 @@ public func _bjs_PropertyHolder_boolValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_stringValue_get") public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).stringValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.stringValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11959,7 +13056,9 @@ public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_stringValue_set") public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).stringValue = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.stringValue = value #else fatalError("Only available on WebAssembly") #endif @@ -11969,7 +13068,8 @@ public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_readonlyInt_get") public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyInt + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyInt return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11980,7 +13080,8 @@ public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_PropertyHolder_readonlyFloat_get") public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyFloat + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyFloat return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -11991,7 +13092,8 @@ public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_PropertyHolder_readonlyDouble_get") public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyDouble + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyDouble return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12002,7 +13104,8 @@ public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_PropertyHolder_readonlyBool_get") public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyBool + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyBool return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12013,7 +13116,8 @@ public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_PropertyHolder_readonlyString_get") public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyString + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.readonlyString return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12024,7 +13128,8 @@ public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_PropertyHolder_jsObject_get") public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).jsObject + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12035,7 +13140,9 @@ public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_PropertyHolder_jsObject_set") public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).jsObject = JSObject.bridgeJSLiftParameter(value) + let value = JSObject.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.jsObject = value #else fatalError("Only available on WebAssembly") #endif @@ -12045,7 +13152,8 @@ public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_sibling_get") public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).sibling + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.sibling return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12056,7 +13164,9 @@ public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> @_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) + let value = SimplePropertyHolder.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.sibling = value #else fatalError("Only available on WebAssembly") #endif @@ -12066,7 +13176,8 @@ public func _bjs_PropertyHolder_sibling_set(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_PropertyHolder_lazyValue_get") public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).lazyValue + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.lazyValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12077,7 +13188,9 @@ public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.lazyValue = value #else fatalError("Only available on WebAssembly") #endif @@ -12087,7 +13200,8 @@ public func _bjs_PropertyHolder_lazyValue_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_PropertyHolder_computedReadonly_get") public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadonly + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.computedReadonly return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12098,7 +13212,8 @@ public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_PropertyHolder_computedReadWrite_get") public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.computedReadWrite return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12109,7 +13224,9 @@ public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawP @_cdecl("bjs_PropertyHolder_computedReadWrite_set") public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.computedReadWrite = value #else fatalError("Only available on WebAssembly") #endif @@ -12119,7 +13236,8 @@ public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawP @_cdecl("bjs_PropertyHolder_observedProperty_get") public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).observedProperty + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.observedProperty return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12130,7 +13248,9 @@ public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPo @_cdecl("bjs_PropertyHolder_observedProperty_set") public func _bjs_PropertyHolder_observedProperty_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).observedProperty = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + let _self = PropertyHolder.bridgeJSLiftParameter(_self) + _self.observedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -12171,7 +13291,9 @@ fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPoin @_cdecl("bjs_MathUtils_static_add") public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.add(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12182,7 +13304,9 @@ public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { @_cdecl("bjs_MathUtils_static_substract") public func _bjs_MathUtils_static_substract(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = MathUtils.substract(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let b = Int.bridgeJSLiftParameter(b) + let a = Int.bridgeJSLiftParameter(a) + let ret = MathUtils.substract(a: a, b: b) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12257,7 +13381,8 @@ public func _bjs_StaticPropertyHolder_static_staticVariable_get() -> Int32 { @_cdecl("bjs_StaticPropertyHolder_static_staticVariable_set") public func _bjs_StaticPropertyHolder_static_staticVariable_set(_ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticVariable = Int.bridgeJSLiftParameter(value) + let value = Int.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticVariable = value #else fatalError("Only available on WebAssembly") #endif @@ -12278,7 +13403,8 @@ public func _bjs_StaticPropertyHolder_static_staticString_get() -> Void { @_cdecl("bjs_StaticPropertyHolder_static_staticString_set") public func _bjs_StaticPropertyHolder_static_staticString_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticString = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyHolder.staticString = value #else fatalError("Only available on WebAssembly") #endif @@ -12299,7 +13425,8 @@ public func _bjs_StaticPropertyHolder_static_staticBool_get() -> Int32 { @_cdecl("bjs_StaticPropertyHolder_static_staticBool_set") public func _bjs_StaticPropertyHolder_static_staticBool_set(_ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticBool = Bool.bridgeJSLiftParameter(value) + let value = Bool.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticBool = value #else fatalError("Only available on WebAssembly") #endif @@ -12320,7 +13447,8 @@ public func _bjs_StaticPropertyHolder_static_staticFloat_get() -> Float32 { @_cdecl("bjs_StaticPropertyHolder_static_staticFloat_set") public func _bjs_StaticPropertyHolder_static_staticFloat_set(_ value: Float32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticFloat = Float.bridgeJSLiftParameter(value) + let value = Float.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticFloat = value #else fatalError("Only available on WebAssembly") #endif @@ -12341,7 +13469,8 @@ public func _bjs_StaticPropertyHolder_static_staticDouble_get() -> Float64 { @_cdecl("bjs_StaticPropertyHolder_static_staticDouble_set") public func _bjs_StaticPropertyHolder_static_staticDouble_set(_ value: Float64) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticDouble = Double.bridgeJSLiftParameter(value) + let value = Double.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticDouble = value #else fatalError("Only available on WebAssembly") #endif @@ -12362,7 +13491,8 @@ public func _bjs_StaticPropertyHolder_static_computedProperty_get() -> Void { @_cdecl("bjs_StaticPropertyHolder_static_computedProperty_set") public func _bjs_StaticPropertyHolder_static_computedProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.computedProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyHolder.computedProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -12394,7 +13524,8 @@ public func _bjs_StaticPropertyHolder_static_optionalString_get() -> Void { @_cdecl("bjs_StaticPropertyHolder_static_optionalString_set") public func _bjs_StaticPropertyHolder_static_optionalString_set(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.optionalString = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + StaticPropertyHolder.optionalString = value #else fatalError("Only available on WebAssembly") #endif @@ -12415,7 +13546,8 @@ public func _bjs_StaticPropertyHolder_static_optionalInt_get() -> Void { @_cdecl("bjs_StaticPropertyHolder_static_optionalInt_set") public func _bjs_StaticPropertyHolder_static_optionalInt_set(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.optionalInt = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + StaticPropertyHolder.optionalInt = value #else fatalError("Only available on WebAssembly") #endif @@ -12436,7 +13568,8 @@ public func _bjs_StaticPropertyHolder_static_jsObjectProperty_get() -> Int32 { @_cdecl("bjs_StaticPropertyHolder_static_jsObjectProperty_set") public func _bjs_StaticPropertyHolder_static_jsObjectProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.jsObjectProperty = JSObject.bridgeJSLiftParameter(value) + let value = JSObject.bridgeJSLiftParameter(value) + StaticPropertyHolder.jsObjectProperty = value #else fatalError("Only available on WebAssembly") #endif @@ -12477,7 +13610,8 @@ fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableR @_cdecl("bjs_DataProcessorManager_init") public func _bjs_DataProcessorManager_init(_ processor: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DataProcessorManager(processor: AnyDataProcessor.bridgeJSLiftParameter(processor)) + let processor = AnyDataProcessor.bridgeJSLiftParameter(processor) + let ret = DataProcessorManager(processor: processor) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12488,7 +13622,9 @@ public func _bjs_DataProcessorManager_init(_ processor: Int32) -> UnsafeMutableR @_cdecl("bjs_DataProcessorManager_incrementByAmount") public func _bjs_DataProcessorManager_incrementByAmount(_ _self: UnsafeMutableRawPointer, _ amount: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).incrementByAmount(_: Int.bridgeJSLiftParameter(amount)) + let amount = Int.bridgeJSLiftParameter(amount) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.incrementByAmount(_: amount) #else fatalError("Only available on WebAssembly") #endif @@ -12498,7 +13634,10 @@ public func _bjs_DataProcessorManager_incrementByAmount(_ _self: UnsafeMutableRa @_cdecl("bjs_DataProcessorManager_setProcessorLabel") public func _bjs_DataProcessorManager_setProcessorLabel(_ _self: UnsafeMutableRawPointer, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorLabel(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength), _: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + let suffix = String.bridgeJSLiftParameter(suffixBytes, suffixLength) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorLabel(_: prefix, _: suffix) #else fatalError("Only available on WebAssembly") #endif @@ -12508,7 +13647,8 @@ public func _bjs_DataProcessorManager_setProcessorLabel(_ _self: UnsafeMutableRa @_cdecl("bjs_DataProcessorManager_isProcessorEven") public func _bjs_DataProcessorManager_isProcessorEven(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).isProcessorEven() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.isProcessorEven() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12519,7 +13659,8 @@ public func _bjs_DataProcessorManager_isProcessorEven(_ _self: UnsafeMutableRawP @_cdecl("bjs_DataProcessorManager_getProcessorLabel") public func _bjs_DataProcessorManager_getProcessorLabel(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorLabel() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorLabel() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12530,7 +13671,8 @@ public func _bjs_DataProcessorManager_getProcessorLabel(_ _self: UnsafeMutableRa @_cdecl("bjs_DataProcessorManager_getCurrentValue") public func _bjs_DataProcessorManager_getCurrentValue(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getCurrentValue() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getCurrentValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12541,7 +13683,8 @@ public func _bjs_DataProcessorManager_getCurrentValue(_ _self: UnsafeMutableRawP @_cdecl("bjs_DataProcessorManager_incrementBoth") public func _bjs_DataProcessorManager_incrementBoth(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).incrementBoth() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.incrementBoth() #else fatalError("Only available on WebAssembly") #endif @@ -12551,7 +13694,8 @@ public func _bjs_DataProcessorManager_incrementBoth(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_DataProcessorManager_getBackupValue") public func _bjs_DataProcessorManager_getBackupValue(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getBackupValue() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getBackupValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12562,7 +13706,8 @@ public func _bjs_DataProcessorManager_getBackupValue(_ _self: UnsafeMutableRawPo @_cdecl("bjs_DataProcessorManager_hasBackup") public func _bjs_DataProcessorManager_hasBackup(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).hasBackup() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.hasBackup() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12573,7 +13718,8 @@ public func _bjs_DataProcessorManager_hasBackup(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_DataProcessorManager_getProcessorOptionalTag") public func _bjs_DataProcessorManager_getProcessorOptionalTag(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalTag() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorOptionalTag() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12584,7 +13730,9 @@ public func _bjs_DataProcessorManager_getProcessorOptionalTag(_ _self: UnsafeMut @_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)) + let tag = Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorOptionalTag(_: tag) #else fatalError("Only available on WebAssembly") #endif @@ -12594,7 +13742,8 @@ public func _bjs_DataProcessorManager_setProcessorOptionalTag(_ _self: UnsafeMut @_cdecl("bjs_DataProcessorManager_getProcessorOptionalCount") public func _bjs_DataProcessorManager_getProcessorOptionalCount(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalCount() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorOptionalCount() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12605,7 +13754,9 @@ public func _bjs_DataProcessorManager_getProcessorOptionalCount(_ _self: UnsafeM @_cdecl("bjs_DataProcessorManager_setProcessorOptionalCount") public func _bjs_DataProcessorManager_setProcessorOptionalCount(_ _self: UnsafeMutableRawPointer, _ countIsSome: Int32, _ countValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorOptionalCount(_: Optional.bridgeJSLiftParameter(countIsSome, countValue)) + let count = Optional.bridgeJSLiftParameter(countIsSome, countValue) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorOptionalCount(_: count) #else fatalError("Only available on WebAssembly") #endif @@ -12615,7 +13766,8 @@ public func _bjs_DataProcessorManager_setProcessorOptionalCount(_ _self: UnsafeM @_cdecl("bjs_DataProcessorManager_getProcessorDirection") public func _bjs_DataProcessorManager_getProcessorDirection(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorDirection() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorDirection() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12626,7 +13778,9 @@ public func _bjs_DataProcessorManager_getProcessorDirection(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_setProcessorDirection") public func _bjs_DataProcessorManager_setProcessorDirection(_ _self: UnsafeMutableRawPointer, _ directionIsSome: Int32, _ directionValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorDirection(_: Optional.bridgeJSLiftParameter(directionIsSome, directionValue)) + let direction = Optional.bridgeJSLiftParameter(directionIsSome, directionValue) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorDirection(_: direction) #else fatalError("Only available on WebAssembly") #endif @@ -12636,7 +13790,8 @@ public func _bjs_DataProcessorManager_setProcessorDirection(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_getProcessorTheme") public func _bjs_DataProcessorManager_getProcessorTheme(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorTheme() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorTheme() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12647,7 +13802,9 @@ public func _bjs_DataProcessorManager_getProcessorTheme(_ _self: UnsafeMutableRa @_cdecl("bjs_DataProcessorManager_setProcessorTheme") public func _bjs_DataProcessorManager_setProcessorTheme(_ _self: UnsafeMutableRawPointer, _ themeIsSome: Int32, _ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorTheme(_: Optional.bridgeJSLiftParameter(themeIsSome, themeBytes, themeLength)) + let theme = Optional.bridgeJSLiftParameter(themeIsSome, themeBytes, themeLength) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorTheme(_: theme) #else fatalError("Only available on WebAssembly") #endif @@ -12657,7 +13814,8 @@ public func _bjs_DataProcessorManager_setProcessorTheme(_ _self: UnsafeMutableRa @_cdecl("bjs_DataProcessorManager_getProcessorHttpStatus") public func _bjs_DataProcessorManager_getProcessorHttpStatus(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorHttpStatus() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorHttpStatus() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12668,7 +13826,9 @@ public func _bjs_DataProcessorManager_getProcessorHttpStatus(_ _self: UnsafeMuta @_cdecl("bjs_DataProcessorManager_setProcessorHttpStatus") public func _bjs_DataProcessorManager_setProcessorHttpStatus(_ _self: UnsafeMutableRawPointer, _ statusIsSome: Int32, _ statusValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorHttpStatus(_: Optional.bridgeJSLiftParameter(statusIsSome, statusValue)) + let status = Optional.bridgeJSLiftParameter(statusIsSome, statusValue) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorHttpStatus(_: status) #else fatalError("Only available on WebAssembly") #endif @@ -12678,7 +13838,8 @@ public func _bjs_DataProcessorManager_setProcessorHttpStatus(_ _self: UnsafeMuta @_cdecl("bjs_DataProcessorManager_getProcessorAPIResult") public func _bjs_DataProcessorManager_getProcessorAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorAPIResult() + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.getProcessorAPIResult() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12689,7 +13850,9 @@ public func _bjs_DataProcessorManager_getProcessorAPIResult(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_setProcessorAPIResult") public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutableRawPointer, _ apiResultIsSome: Int32, _ apiResultCaseId: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorAPIResult(_: Optional.bridgeJSLiftParameter(apiResultIsSome, apiResultCaseId)) + let apiResult = Optional.bridgeJSLiftParameter(apiResultIsSome, apiResultCaseId) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.setProcessorAPIResult(_: apiResult) #else fatalError("Only available on WebAssembly") #endif @@ -12699,7 +13862,8 @@ public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutab @_cdecl("bjs_DataProcessorManager_processor_get") public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = _bridgeJSUnwrapProtocolExportable(DataProcessorManager.bridgeJSLiftParameter(_self).processor, "DataProcessor") + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _bridgeJSUnwrapProtocolExportable(_self.processor, "DataProcessor") return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") @@ -12710,7 +13874,9 @@ public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_DataProcessorManager_processor_set") public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).processor = AnyDataProcessor.bridgeJSLiftParameter(value) + let value = AnyDataProcessor.bridgeJSLiftParameter(value) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.processor = value #else fatalError("Only available on WebAssembly") #endif @@ -12720,7 +13886,8 @@ public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_DataProcessorManager_backupProcessor_get") public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + let ret = _self.backupProcessor if let ret { _swift_js_return_optional_object(1, _bridgeJSUnwrapProtocolExportable(ret, "DataProcessor").bridgeJSLowerAsProtocolReturn()) } else { @@ -12735,7 +13902,9 @@ public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutable @_cdecl("bjs_DataProcessorManager_backupProcessor_set") public func _bjs_DataProcessorManager_backupProcessor_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + _self.backupProcessor = value #else fatalError("Only available on WebAssembly") #endif @@ -12787,7 +13956,9 @@ public func _bjs_SwiftDataProcessor_init() -> UnsafeMutableRawPointer { @_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)) + let amount = Int.bridgeJSLiftParameter(amount) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.increment(by: amount) #else fatalError("Only available on WebAssembly") #endif @@ -12797,7 +13968,8 @@ public func _bjs_SwiftDataProcessor_increment(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SwiftDataProcessor_getValue") public func _bjs_SwiftDataProcessor_getValue(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getValue() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.getValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12808,7 +13980,10 @@ public func _bjs_SwiftDataProcessor_getValue(_ _self: UnsafeMutableRawPointer) - @_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)) + let labelSuffix = String.bridgeJSLiftParameter(labelSuffixBytes, labelSuffixLength) + let labelPrefix = String.bridgeJSLiftParameter(labelPrefixBytes, labelPrefixLength) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.setLabelElements(_: labelPrefix, _: labelSuffix) #else fatalError("Only available on WebAssembly") #endif @@ -12818,7 +13993,8 @@ public func _bjs_SwiftDataProcessor_setLabelElements(_ _self: UnsafeMutableRawPo @_cdecl("bjs_SwiftDataProcessor_getLabel") public func _bjs_SwiftDataProcessor_getLabel(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getLabel() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.getLabel() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12829,7 +14005,8 @@ public func _bjs_SwiftDataProcessor_getLabel(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_SwiftDataProcessor_isEven") public func _bjs_SwiftDataProcessor_isEven(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).isEven() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.isEven() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12840,7 +14017,9 @@ public func _bjs_SwiftDataProcessor_isEven(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_SwiftDataProcessor_processGreeter") public func _bjs_SwiftDataProcessor_processGreeter(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).processGreeter(_: Greeter.bridgeJSLiftParameter(greeter)) + let greeter = Greeter.bridgeJSLiftParameter(greeter) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processGreeter(_: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12851,7 +14030,8 @@ public func _bjs_SwiftDataProcessor_processGreeter(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_SwiftDataProcessor_createGreeter") public func _bjs_SwiftDataProcessor_createGreeter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createGreeter() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.createGreeter() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12862,7 +14042,9 @@ public func _bjs_SwiftDataProcessor_createGreeter(_ _self: UnsafeMutableRawPoint @_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)) + let greeter = Optional.bridgeJSLiftParameter(greeterIsSome, greeterValue) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalGreeter(_: greeter) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12873,7 +14055,8 @@ public func _bjs_SwiftDataProcessor_processOptionalGreeter(_ _self: UnsafeMutabl @_cdecl("bjs_SwiftDataProcessor_createOptionalGreeter") public func _bjs_SwiftDataProcessor_createOptionalGreeter(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createOptionalGreeter() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.createOptionalGreeter() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12884,7 +14067,9 @@ public func _bjs_SwiftDataProcessor_createOptionalGreeter(_ _self: UnsafeMutable @_cdecl("bjs_SwiftDataProcessor_handleAPIResult") public func _bjs_SwiftDataProcessor_handleAPIResult(_ _self: UnsafeMutableRawPointer, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).handleAPIResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let result = Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.handleAPIResult(_: result) #else fatalError("Only available on WebAssembly") #endif @@ -12894,7 +14079,8 @@ public func _bjs_SwiftDataProcessor_handleAPIResult(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_SwiftDataProcessor_getAPIResult") public func _bjs_SwiftDataProcessor_getAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getAPIResult() + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.getAPIResult() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12905,7 +14091,8 @@ public func _bjs_SwiftDataProcessor_getAPIResult(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_SwiftDataProcessor_count_get") public func _bjs_SwiftDataProcessor_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).count + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12916,7 +14103,9 @@ public func _bjs_SwiftDataProcessor_count_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.count = value #else fatalError("Only available on WebAssembly") #endif @@ -12926,7 +14115,8 @@ public func _bjs_SwiftDataProcessor_count_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SwiftDataProcessor_name_get") public func _bjs_SwiftDataProcessor_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).name + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12937,7 +14127,8 @@ public func _bjs_SwiftDataProcessor_name_get(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_SwiftDataProcessor_optionalTag_get") public func _bjs_SwiftDataProcessor_optionalTag_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTag + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.optionalTag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12948,7 +14139,9 @@ public func _bjs_SwiftDataProcessor_optionalTag_get(_ _self: UnsafeMutableRawPoi @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.optionalTag = value #else fatalError("Only available on WebAssembly") #endif @@ -12958,7 +14151,8 @@ public func _bjs_SwiftDataProcessor_optionalTag_set(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_SwiftDataProcessor_optionalCount_get") public func _bjs_SwiftDataProcessor_optionalCount_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.optionalCount return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12969,7 +14163,9 @@ public func _bjs_SwiftDataProcessor_optionalCount_get(_ _self: UnsafeMutableRawP @_cdecl("bjs_SwiftDataProcessor_optionalCount_set") public func _bjs_SwiftDataProcessor_optionalCount_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.optionalCount = value #else fatalError("Only available on WebAssembly") #endif @@ -12979,7 +14175,8 @@ public func _bjs_SwiftDataProcessor_optionalCount_set(_ _self: UnsafeMutableRawP @_cdecl("bjs_SwiftDataProcessor_direction_get") public func _bjs_SwiftDataProcessor_direction_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).direction + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.direction return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -12990,7 +14187,9 @@ public func _bjs_SwiftDataProcessor_direction_get(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_SwiftDataProcessor_direction_set") public func _bjs_SwiftDataProcessor_direction_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).direction = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.direction = value #else fatalError("Only available on WebAssembly") #endif @@ -13000,7 +14199,8 @@ public func _bjs_SwiftDataProcessor_direction_set(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_SwiftDataProcessor_optionalTheme_get") public func _bjs_SwiftDataProcessor_optionalTheme_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.optionalTheme return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13011,7 +14211,9 @@ public func _bjs_SwiftDataProcessor_optionalTheme_get(_ _self: UnsafeMutableRawP @_cdecl("bjs_SwiftDataProcessor_optionalTheme_set") public func _bjs_SwiftDataProcessor_optionalTheme_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.optionalTheme = value #else fatalError("Only available on WebAssembly") #endif @@ -13021,7 +14223,8 @@ public func _bjs_SwiftDataProcessor_optionalTheme_set(_ _self: UnsafeMutableRawP @_cdecl("bjs_SwiftDataProcessor_httpStatus_get") public func _bjs_SwiftDataProcessor_httpStatus_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.httpStatus return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13032,7 +14235,9 @@ public func _bjs_SwiftDataProcessor_httpStatus_get(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_SwiftDataProcessor_httpStatus_set") public func _bjs_SwiftDataProcessor_httpStatus_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.httpStatus = value #else fatalError("Only available on WebAssembly") #endif @@ -13042,7 +14247,8 @@ public func _bjs_SwiftDataProcessor_httpStatus_set(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_SwiftDataProcessor_apiResult_get") public func _bjs_SwiftDataProcessor_apiResult_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.apiResult return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13053,7 +14259,9 @@ public func _bjs_SwiftDataProcessor_apiResult_get(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_SwiftDataProcessor_apiResult_set") public func _bjs_SwiftDataProcessor_apiResult_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.apiResult = value #else fatalError("Only available on WebAssembly") #endif @@ -13063,7 +14271,8 @@ public func _bjs_SwiftDataProcessor_apiResult_set(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_SwiftDataProcessor_helper_get") public func _bjs_SwiftDataProcessor_helper_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).helper + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.helper return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13074,7 +14283,9 @@ public func _bjs_SwiftDataProcessor_helper_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_SwiftDataProcessor_helper_set") public func _bjs_SwiftDataProcessor_helper_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).helper = Greeter.bridgeJSLiftParameter(value) + let value = Greeter.bridgeJSLiftParameter(value) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.helper = value #else fatalError("Only available on WebAssembly") #endif @@ -13084,7 +14295,8 @@ public func _bjs_SwiftDataProcessor_helper_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_SwiftDataProcessor_optionalHelper_get") public func _bjs_SwiftDataProcessor_optionalHelper_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + let ret = _self.optionalHelper return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13095,7 +14307,9 @@ public func _bjs_SwiftDataProcessor_optionalHelper_get(_ _self: UnsafeMutableRaw @_cdecl("bjs_SwiftDataProcessor_optionalHelper_set") public func _bjs_SwiftDataProcessor_optionalHelper_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + _self.optionalHelper = value #else fatalError("Only available on WebAssembly") #endif @@ -13237,7 +14451,8 @@ fileprivate func _bjs_ProtocolReturnTests_wrap_extern(_ pointer: UnsafeMutableRa @_cdecl("bjs_TextProcessor_init") public func _bjs_TextProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TextProcessor(transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + let transform = _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform) + let ret = TextProcessor(transform: transform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13248,7 +14463,9 @@ public func _bjs_TextProcessor_init(_ transform: Int32) -> UnsafeMutableRawPoint @_cdecl("bjs_TextProcessor_process") public func _bjs_TextProcessor_process(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).process(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.process(_: text) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13259,7 +14476,10 @@ public func _bjs_TextProcessor_process(_ _self: UnsafeMutableRawPointer, _ textB @_cdecl("bjs_TextProcessor_processWithCustom") public func _bjs_TextProcessor_processWithCustom(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32, _ customTransform: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processWithCustom(_: String.bridgeJSLiftParameter(textBytes, textLength), customTransform: _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS.bridgeJSLift(customTransform)) + let customTransform = _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS.bridgeJSLift(customTransform) + let text = String.bridgeJSLiftParameter(textBytes, textLength) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processWithCustom(_: text, customTransform: customTransform) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13270,7 +14490,8 @@ public func _bjs_TextProcessor_processWithCustom(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_TextProcessor_getTransform") public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).getTransform() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.getTransform() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13281,7 +14502,9 @@ public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_TextProcessor_processOptionalString") public func _bjs_TextProcessor_processOptionalString(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalString(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalString(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13292,7 +14515,9 @@ public func _bjs_TextProcessor_processOptionalString(_ _self: UnsafeMutableRawPo @_cdecl("bjs_TextProcessor_processOptionalInt") public func _bjs_TextProcessor_processOptionalInt(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalInt(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalInt(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13303,7 +14528,9 @@ public func _bjs_TextProcessor_processOptionalInt(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_TextProcessor_processOptionalGreeter") public func _bjs_TextProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalGreeter(_: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalGreeter(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13314,7 +14541,8 @@ public func _bjs_TextProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawP @_cdecl("bjs_TextProcessor_makeOptionalStringFormatter") public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalStringFormatter() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalStringFormatter() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13325,7 +14553,8 @@ public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutabl @_cdecl("bjs_TextProcessor_makeOptionalGreeterCreator") public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalGreeterCreator() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalGreeterCreator() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13336,7 +14565,9 @@ public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutable @_cdecl("bjs_TextProcessor_processDirection") public func _bjs_TextProcessor_processDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processDirection(_: _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processDirection(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13347,7 +14578,9 @@ public func _bjs_TextProcessor_processDirection(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_TextProcessor_processTheme") public func _bjs_TextProcessor_processTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processTheme(_: _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processTheme(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13358,7 +14591,9 @@ public func _bjs_TextProcessor_processTheme(_ _self: UnsafeMutableRawPointer, _ @_cdecl("bjs_TextProcessor_processHttpStatus") public func _bjs_TextProcessor_processHttpStatus(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processHttpStatus(_: _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processHttpStatus(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13369,7 +14604,9 @@ public func _bjs_TextProcessor_processHttpStatus(_ _self: UnsafeMutableRawPointe @_cdecl("bjs_TextProcessor_processAPIResult") public func _bjs_TextProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processAPIResult(_: _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processAPIResult(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13380,7 +14617,8 @@ public func _bjs_TextProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_TextProcessor_makeDirectionChecker") public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDirectionChecker() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeDirectionChecker() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13391,7 +14629,8 @@ public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_TextProcessor_makeThemeValidator") public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeThemeValidator() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeThemeValidator() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13402,7 +14641,8 @@ public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_TextProcessor_makeStatusCodeExtractor") public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeStatusCodeExtractor() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeStatusCodeExtractor() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13413,7 +14653,8 @@ public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRaw @_cdecl("bjs_TextProcessor_makeAPIResultHandler") public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeAPIResultHandler() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeAPIResultHandler() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13424,7 +14665,9 @@ public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_TextProcessor_processOptionalDirection") public func _bjs_TextProcessor_processOptionalDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalDirection(_: _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalDirection(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13435,7 +14678,9 @@ public func _bjs_TextProcessor_processOptionalDirection(_ _self: UnsafeMutableRa @_cdecl("bjs_TextProcessor_processOptionalTheme") public func _bjs_TextProcessor_processOptionalTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalTheme(_: _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS.bridgeJSLift(callback)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalTheme(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13446,7 +14691,9 @@ public func _bjs_TextProcessor_processOptionalTheme(_ _self: UnsafeMutableRawPoi @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalAPIResult(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13457,7 +14704,8 @@ public func _bjs_TextProcessor_processOptionalAPIResult(_ _self: UnsafeMutableRa @_cdecl("bjs_TextProcessor_makeOptionalDirectionFormatter") public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalDirectionFormatter() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeOptionalDirectionFormatter() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13468,7 +14716,9 @@ public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMut @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processDataProcessor(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13479,7 +14729,8 @@ public func _bjs_TextProcessor_processDataProcessor(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_TextProcessor_makeDataProcessorFactory") public func _bjs_TextProcessor_makeDataProcessorFactory(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDataProcessorFactory() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.makeDataProcessorFactory() return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13490,7 +14741,9 @@ public func _bjs_TextProcessor_makeDataProcessorFactory(_ _self: UnsafeMutableRa @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.roundtripDataProcessor(_: callback) return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13501,7 +14754,9 @@ public func _bjs_TextProcessor_roundtripDataProcessor(_ _self: UnsafeMutableRawP @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_SS.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalDataProcessor(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13512,7 +14767,9 @@ public func _bjs_TextProcessor_processOptionalDataProcessor(_ _self: UnsafeMutab @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSd_8Vector2DV.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processVector(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13523,7 +14780,9 @@ public func _bjs_TextProcessor_processVector(_ _self: UnsafeMutableRawPointer, _ @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTestsSd_Sq8Vector2DV.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.processOptionalVector(_: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13534,7 +14793,9 @@ public func _bjs_TextProcessor_processOptionalVector(_ _self: UnsafeMutableRawPo @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_y.bridgeJSLift(callback) + let _self = TextProcessor.bridgeJSLiftParameter(_self) + _self.observeVector(_: callback) #else fatalError("Only available on WebAssembly") #endif @@ -13544,7 +14805,10 @@ public func _bjs_TextProcessor_observeVector(_ _self: UnsafeMutableRawPointer, _ @_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)) + let callback = _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV.bridgeJSLift(callback) + let vector = Vector2D.bridgeJSLiftParameter() + let _self = TextProcessor.bridgeJSLiftParameter(_self) + let ret = _self.mapVector(_: vector, _: callback) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13597,7 +14861,8 @@ public func _bjs_NestedTypeHost_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_NestedTypeHost_describe") public func _bjs_NestedTypeHost_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = NestedTypeHost.bridgeJSLiftParameter(_self).describe() + let _self = NestedTypeHost.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13639,7 +14904,8 @@ fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPoin @_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)) + let name = String.bridgeJSLiftParameter(nameBytes, nameLength) + let ret = Library(name: name) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13650,7 +14916,8 @@ public func _bjs_Library_init(_ nameBytes: Int32, _ nameLength: Int32) -> Unsafe @_cdecl("bjs_Library_describe") public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Library.bridgeJSLiftParameter(_self).describe() + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13661,7 +14928,9 @@ public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { @_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)) + let title = String.bridgeJSLiftParameter(titleBytes, titleLength) + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.rename(_: title) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13672,7 +14941,9 @@ public func _bjs_Library_rename(_ _self: UnsafeMutableRawPointer, _ titleBytes: @_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)) + let label = String.bridgeJSLiftParameter(labelBytes, labelLength) + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.shelf(label: label) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13683,7 +14954,8 @@ public func _bjs_Library_shelf(_ _self: UnsafeMutableRawPointer, _ labelBytes: I @_cdecl("bjs_Library_name_get") public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Library.bridgeJSLiftParameter(_self).name + let _self = Library.bridgeJSLiftParameter(_self) + let ret = _self.name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13694,7 +14966,9 @@ public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { @_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) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let _self = Library.bridgeJSLiftParameter(_self) + _self.name = value #else fatalError("Only available on WebAssembly") #endif @@ -13735,7 +15009,8 @@ fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> @_cdecl("bjs_ImportGenericBox_init") public func _bjs_ImportGenericBox_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ImportGenericBox(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = ImportGenericBox(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13746,7 +15021,8 @@ public func _bjs_ImportGenericBox_init(_ value: Int32) -> UnsafeMutableRawPointe @_cdecl("bjs_ImportGenericBox_get") public func _bjs_ImportGenericBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ImportGenericBox.bridgeJSLiftParameter(_self).get() + let _self = ImportGenericBox.bridgeJSLiftParameter(_self) + let ret = _self.get() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13757,7 +15033,8 @@ public func _bjs_ImportGenericBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 @_cdecl("bjs_ImportGenericBox_value_get") public func _bjs_ImportGenericBox_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ImportGenericBox.bridgeJSLiftParameter(_self).value + let _self = ImportGenericBox.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13768,7 +15045,9 @@ public func _bjs_ImportGenericBox_value_get(_ _self: UnsafeMutableRawPointer) -> @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = ImportGenericBox.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -13809,7 +15088,8 @@ fileprivate func _bjs_ImportGenericBox_wrap_extern(_ pointer: UnsafeMutableRawPo @_cdecl("bjs_JSNameRenamedClass_init") public func _bjs_JSNameRenamedClass_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSNameRenamedClass(value: Int.bridgeJSLiftParameter(value)) + let value = Int.bridgeJSLiftParameter(value) + let ret = JSNameRenamedClass(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13820,7 +15100,8 @@ public func _bjs_JSNameRenamedClass_init(_ value: Int32) -> UnsafeMutableRawPoin @_cdecl("bjs_JSNameRenamedClass_doubled") public func _bjs_JSNameRenamedClass_doubled(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = JSNameRenamedClass.bridgeJSLiftParameter(_self).timesTwo() + let _self = JSNameRenamedClass.bridgeJSLiftParameter(_self) + let ret = _self.timesTwo() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13831,7 +15112,8 @@ public func _bjs_JSNameRenamedClass_doubled(_ _self: UnsafeMutableRawPointer) -> @_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)) + let value = Int.bridgeJSLiftParameter(value) + let ret = JSNameRenamedClass.create(value: value) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13842,7 +15124,8 @@ public func _bjs_JSNameRenamedClass_static_makeWithValue(_ value: Int32) -> Unsa @_cdecl("bjs_JSNameRenamedClass_value_get") public func _bjs_JSNameRenamedClass_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = JSNameRenamedClass.bridgeJSLiftParameter(_self).value + let _self = JSNameRenamedClass.bridgeJSLiftParameter(_self) + let ret = _self.value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13853,7 +15136,9 @@ public func _bjs_JSNameRenamedClass_value_get(_ _self: UnsafeMutableRawPointer) @_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) + let value = Int.bridgeJSLiftParameter(value) + let _self = JSNameRenamedClass.bridgeJSLiftParameter(_self) + _self.value = value #else fatalError("Only available on WebAssembly") #endif @@ -13894,7 +15179,9 @@ fileprivate func _bjs_JSNameRenamedClass_wrap_extern(_ pointer: UnsafeMutableRaw @_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)) + let undefinedNumber = JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue) + let nullableGreeter = Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue) + let ret = OptionalHolder(nullableGreeter: nullableGreeter, undefinedNumber: undefinedNumber) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13905,7 +15192,8 @@ public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableG @_cdecl("bjs_OptionalHolder_nullableGreeter_get") public func _bjs_OptionalHolder_nullableGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter + let _self = OptionalHolder.bridgeJSLiftParameter(_self) + let ret = _self.nullableGreeter return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13916,7 +15204,9 @@ public func _bjs_OptionalHolder_nullableGreeter_get(_ _self: UnsafeMutableRawPoi @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalHolder.bridgeJSLiftParameter(_self) + _self.nullableGreeter = value #else fatalError("Only available on WebAssembly") #endif @@ -13926,7 +15216,8 @@ public func _bjs_OptionalHolder_nullableGreeter_set(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_OptionalHolder_undefinedNumber_get") public func _bjs_OptionalHolder_undefinedNumber_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber + let _self = OptionalHolder.bridgeJSLiftParameter(_self) + let ret = _self.undefinedNumber return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13937,7 +15228,9 @@ public func _bjs_OptionalHolder_undefinedNumber_get(_ _self: UnsafeMutableRawPoi @_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) + let value = JSUndefinedOr.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalHolder.bridgeJSLiftParameter(_self) + _self.undefinedNumber = value #else fatalError("Only available on WebAssembly") #endif @@ -13978,7 +15271,8 @@ fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPoin @_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)) + let optionalName = Optional.bridgeJSLiftParameter(optionalNameIsSome, optionalNameBytes, optionalNameLength) + let ret = OptionalPropertyHolder(optionalName: optionalName) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -13989,7 +15283,8 @@ public func _bjs_OptionalPropertyHolder_init(_ optionalNameIsSome: Int32, _ opti @_cdecl("bjs_OptionalPropertyHolder_optionalName_get") public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalName return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14000,7 +15295,9 @@ public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableR @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalName = value #else fatalError("Only available on WebAssembly") #endif @@ -14010,7 +15307,8 @@ public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableR @_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalAge return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14021,7 +15319,9 @@ public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRa @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalAge = value #else fatalError("Only available on WebAssembly") #endif @@ -14031,7 +15331,8 @@ public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRa @_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + let ret = _self.optionalGreeter return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14042,7 +15343,9 @@ public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutab @_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) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let _self = OptionalPropertyHolder.bridgeJSLiftParameter(_self) + _self.optionalGreeter = value #else fatalError("Only available on WebAssembly") #endif @@ -14083,9 +15386,9 @@ fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutabl @_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) + let config = Optional.bridgeJSLiftParameter() + let location = DataPoint.bridgeJSLiftParameter() + let ret = Container(location: location, config: config) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14096,7 +15399,8 @@ public func _bjs_Container_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_Container_location_get") public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).location + let _self = Container.bridgeJSLiftParameter(_self) + let ret = _self.location return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14107,7 +15411,9 @@ public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Voi @_cdecl("bjs_Container_location_set") public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).location = DataPoint.bridgeJSLiftParameter() + let value = DataPoint.bridgeJSLiftParameter() + let _self = Container.bridgeJSLiftParameter(_self) + _self.location = value #else fatalError("Only available on WebAssembly") #endif @@ -14117,7 +15423,8 @@ public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Voi @_cdecl("bjs_Container_config_get") public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).config + let _self = Container.bridgeJSLiftParameter(_self) + let ret = _self.config return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -14128,7 +15435,9 @@ public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void @_cdecl("bjs_Container_config_set") public func _bjs_Container_config_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).config = Optional.bridgeJSLiftParameter() + let value = Optional.bridgeJSLiftParameter() + let _self = Container.bridgeJSLiftParameter(_self) + _self.config = value #else fatalError("Only available on WebAssembly") #endif @@ -14542,44 +15851,44 @@ func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSExcepti if let error = _swift_js_take_exception() { throw error } } -@JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) +@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_y") -fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void +@_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_y_extern(_ promise: Int32) -> Void { +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_y(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_y_extern(promise) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Si(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Si_extern(promise, value) } -func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { +func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { + let valueValue = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_y(promiseValue) + promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } -@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) +@JSFunction func Promise_resolve_y(_ promise: JSObject) 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 +@_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_Si_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: 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) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_y(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_y_extern(promise) } -func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { - let valueValue = value.bridgeJSLowerParameter() +func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) + promise_resolve_BridgeJSRuntimeTests_y(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -15855,7 +17164,7 @@ func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Vo try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in bjs_AsyncImportImports_jsAsyncRoundTripVoid_static(resolveRef, rejectRef) } @@ -15863,9 +17172,9 @@ func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Vo func _$AsyncImportImports_jsAsyncRoundTripNumber(_ v: Double) async throws(JSException) -> Double { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Double) -> Void>($0) + JSTypedClosure<(sending Double) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripNumber_static(resolveRef, rejectRef, vValue) @@ -15875,9 +17184,9 @@ func _$AsyncImportImports_jsAsyncRoundTripNumber(_ v: Double) async throws(JSExc func _$AsyncImportImports_jsAsyncRoundTripBool(_ v: Bool) async throws(JSException) -> Bool { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Bool) -> Void>($0) + JSTypedClosure<(sending Bool) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vValue = v.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripBool_static(resolveRef, rejectRef, vValue) @@ -15887,9 +17196,9 @@ func _$AsyncImportImports_jsAsyncRoundTripBool(_ v: Bool) async throws(JSExcepti func _$AsyncImportImports_jsAsyncRoundTripString(_ v: String) async throws(JSException) -> String { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) + JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in v.bridgeJSWithLoweredParameter { (vBytes, vLength) in bjs_AsyncImportImports_jsAsyncRoundTripString_static(resolveRef, rejectRef, vBytes, vLength) @@ -15900,9 +17209,9 @@ func _$AsyncImportImports_jsAsyncRoundTripString(_ v: String) async throws(JSExc func _$AsyncImportImports_jsAsyncRoundTripOptionalString(_ v: Optional) async throws(JSException) -> Optional { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Optional) -> Void>($0) + JSTypedClosure<(sending Optional) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in v.bridgeJSWithLoweredParameter { (vIsSome, vBytes, vLength) in bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(resolveRef, rejectRef, vIsSome, vBytes, vLength) @@ -15913,9 +17222,9 @@ func _$AsyncImportImports_jsAsyncRoundTripOptionalString(_ v: Optional) func _$AsyncImportImports_jsAsyncRoundTripOptionalNumber(_ v: Optional) async throws(JSException) -> Optional { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Optional) -> Void>($0) + JSTypedClosure<(sending Optional) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let (vIsSome, vValue) = v.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripOptionalNumber_static(resolveRef, rejectRef, vIsSome, vValue) @@ -15925,9 +17234,9 @@ func _$AsyncImportImports_jsAsyncRoundTripOptionalNumber(_ v: Optional) func _$AsyncImportImports_jsAsyncRoundTripBoolArray(_ values: [Bool]) async throws(JSException) -> [Bool] { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending [Bool]) -> Void>($0) + JSTypedClosure<(sending [Bool]) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let _ = values.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripBoolArray_static(resolveRef, rejectRef) @@ -15937,9 +17246,9 @@ func _$AsyncImportImports_jsAsyncRoundTripBoolArray(_ values: [Bool]) async thro func _$AsyncImportImports_jsAsyncRoundTripIntArray(_ values: [Double]) async throws(JSException) -> [Double] { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending [Double]) -> Void>($0) + JSTypedClosure<(sending [Double]) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let _ = values.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripIntArray_static(resolveRef, rejectRef) @@ -15949,9 +17258,9 @@ func _$AsyncImportImports_jsAsyncRoundTripIntArray(_ values: [Double]) async thr func _$AsyncImportImports_jsAsyncRoundTripStringArray(_ values: [String]) async throws(JSException) -> [String] { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending [String]) -> Void>($0) + JSTypedClosure<(sending [String]) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let _ = values.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static(resolveRef, rejectRef) @@ -15961,9 +17270,9 @@ func _$AsyncImportImports_jsAsyncRoundTripStringArray(_ values: [String]) async func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async throws(JSException) -> FeatureFlag { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending FeatureFlag) -> Void>($0) + JSTypedClosure<(sending FeatureFlag) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in v.bridgeJSWithLoweredParameter { (vBytes, vLength) in bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(resolveRef, rejectRef, vBytes, vLength) @@ -15974,9 +17283,9 @@ func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async th func _$AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum(_ v: AsyncImportedPayloadResult) async throws(JSException) -> AsyncImportedPayloadResult { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending AsyncImportedPayloadResult) -> Void>($0) + JSTypedClosure<(sending AsyncImportedPayloadResult) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let vCaseId = v.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(resolveRef, rejectRef, vCaseId) @@ -15986,9 +17295,9 @@ func _$AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum(_ v: AsyncImported func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optional) async throws(JSException) -> Optional { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Optional) -> Void>($0) + JSTypedClosure<(sending Optional) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in let (vIsSome, vCaseId) = v.bridgeJSLowerParameter() bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(resolveRef, rejectRef, vIsSome, vCaseId) @@ -16012,7 +17321,7 @@ func _$ClosureAsyncImports_runJsClosureAsyncTests() async throws(JSException) -> try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(resolveRef, rejectRef) } @@ -16090,6 +17399,66 @@ fileprivate func bjs_ClosureSupportImports_jsApplyJSObject_static_extern(_ value return bjs_ClosureSupportImports_jsApplyJSObject_static_extern(value, transform) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyArrayInt_static") +fileprivate func bjs_ClosureSupportImports_jsApplyArrayInt_static_extern(_ transform: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyArrayInt_static_extern(_ transform: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyArrayInt_static(_ transform: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyArrayInt_static_extern(transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyArrayDouble_static") +fileprivate func bjs_ClosureSupportImports_jsApplyArrayDouble_static_extern(_ transform: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyArrayDouble_static_extern(_ transform: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyArrayDouble_static(_ transform: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyArrayDouble_static_extern(transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyArrayString_static") +fileprivate func bjs_ClosureSupportImports_jsApplyArrayString_static_extern(_ transform: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyArrayString_static_extern(_ transform: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyArrayString_static(_ transform: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyArrayString_static_extern(transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyArrayJSValue_static") +fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSValue_static_extern(_ transform: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSValue_static_extern(_ transform: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSValue_static(_ transform: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyArrayJSValue_static_extern(transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyArrayJSObject_static") +fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSObject_static_extern(_ transform: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSObject_static_extern(_ transform: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyArrayJSObject_static(_ transform: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyArrayJSObject_static_extern(transform) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeIntToInt_static") fileprivate func bjs_ClosureSupportImports_jsMakeIntToInt_static_extern(_ base: Int32) -> Int32 @@ -16294,6 +17663,56 @@ func _$ClosureSupportImports_jsApplyJSObject(_ value: JSObject, _ transform: JST return JSObject.bridgeJSLiftReturn(ret) } +func _$ClosureSupportImports_jsApplyArrayInt(_ value: [Int], _ transform: JSTypedClosure<([Int]) -> [Int]>) throws(JSException) -> [Int] { + let transformFuncRef = transform.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyArrayInt_static(transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return [Int].bridgeJSLiftReturn() +} + +func _$ClosureSupportImports_jsApplyArrayDouble(_ value: [Double], _ transform: JSTypedClosure<([Double]) -> [Double]>) throws(JSException) -> [Double] { + let transformFuncRef = transform.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyArrayDouble_static(transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return [Double].bridgeJSLiftReturn() +} + +func _$ClosureSupportImports_jsApplyArrayString(_ value: [String], _ transform: JSTypedClosure<([String]) -> [String]>) throws(JSException) -> [String] { + let transformFuncRef = transform.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyArrayString_static(transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return [String].bridgeJSLiftReturn() +} + +func _$ClosureSupportImports_jsApplyArrayJSValue(_ value: [JSValue], _ transform: JSTypedClosure<([JSValue]) -> [JSValue]>) throws(JSException) -> [JSValue] { + let transformFuncRef = transform.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyArrayJSValue_static(transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return [JSValue].bridgeJSLiftReturn() +} + +func _$ClosureSupportImports_jsApplyArrayJSObject(_ value: [JSObject], _ transform: JSTypedClosure<([JSObject]) -> [JSObject]>) throws(JSException) -> [JSObject] { + let transformFuncRef = transform.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyArrayJSObject_static(transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return [JSObject].bridgeJSLiftReturn() +} + func _$ClosureSupportImports_jsMakeIntToInt(_ base: Int) throws(JSException) -> (Int) -> Int { let baseValue = base.bridgeJSLowerParameter() let ret = bjs_ClosureSupportImports_jsMakeIntToInt_static(baseValue) @@ -16858,7 +18277,7 @@ func _$runAsyncWorks() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in bjs_runAsyncWorks(resolveRef, rejectRef) } @@ -16878,9 +18297,9 @@ fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: I func _$fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData { let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending WeatherData) -> Void>($0) + JSTypedClosure<(sending WeatherData) -> Void>.sending($0) }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) + JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in city.bridgeJSWithLoweredParameter { (cityBytes, cityLength) in bjs_fetchWeatherData(resolveRef, rejectRef, cityBytes, cityLength) diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index c1a3e26cc..e0c5a65b8 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -823,6 +823,69 @@ "_0" : "ClosureSupportExports" } } + }, + { + "abiName" : "bjs_ClosureSupportExports_static_makeArrayDifference", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "makeArrayDifference", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSaSiSaSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" + } + } } ], "name" : "ClosureSupportExports", @@ -14153,6 +14216,109 @@ } } }, + { + "abiName" : "bjs_makeAsyncArraySum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncArraySum", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSaSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_awaitArraySum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "awaitArraySum", + "parameters" : [ + { + "label" : "_", + "name" : "sum", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSaSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, { "abiName" : "bjs_makeThrowingParser", "effects" : { @@ -20754,6 +20920,100 @@ "_1" : "null" } } + }, + { + "abiName" : "bjs_ArrayMembers_ownSumAsync", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "ownSumAsync", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_ArrayMembers_sumAsync", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sumAsync", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_ArrayMembers_requireValues", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "requireValues", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } } ], "name" : "ArrayMembers", @@ -22544,6 +22804,353 @@ } } }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyArrayInt", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSaSi_SaSi", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyArrayDouble", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSaSd_SaSd", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyArrayString", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSaSS_SaSS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyArrayJSValue", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSa7JSValueV_Sa7JSValueV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsApplyArrayJSObject", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSa8JSObjectC_Sa8JSObjectC", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + }, { "accessLevel" : "internal", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs index 57a824aa4..3267d8fd6 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs @@ -128,4 +128,13 @@ export async function runJsClosureAsyncTests(exports) { concurrent.release(); } } + + const first = exports.roundTripArrayMembers({ ints: [10], optStrings: null }); + const second = exports.roundTripArrayMembers({ ints: [20], optStrings: null }); + assert.deepEqual(await Promise.all([first.ownSumAsync(), second.ownSumAsync()]), [10, 20]); + assert.deepEqual(await Promise.all([first.sumAsync([1]), second.sumAsync([2])]), [11, 22]); + + const sum = exports.makeAsyncArraySum(); + assert.deepEqual(await Promise.all([sum([1, 2]), sum([10, 20])]), [3, 30]); + assert.equal(await exports.awaitArraySum(async (values) => values.reduce((a, b) => a + b, 0)), 6); } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs index 9461bec1f..2ddc8c866 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs @@ -411,4 +411,7 @@ export function runJsClosureSupportTests(exports) { const jsStringToString = exports.ClosureSupportExports.makeJSStringToString("Hello, "); assert.equal(jsStringToString("world!"), "Hello, world!"); + + const difference = exports.ClosureSupportExports.makeArrayDifference(); + assert.equal(difference([1, 2], [10, 20]), -27); } diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index e11856d41..c74ee1a75 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -327,6 +327,21 @@ extension Vector2D { @JS func firstString(_ values: [String]) -> String? { values.first } + + @JS func ownSumAsync() async -> Int { + ints.reduce(0, +) + } + + @JS func sumAsync(_ values: [Int]) async -> Int { + ints.reduce(0, +) + values.reduce(0, +) + } + + @JS func requireValues(_ values: [Int]) throws(JSException) -> [Int] { + guard !values.isEmpty else { + throw JSException(JSError(message: "Values must not be empty").jsValue) + } + return ints + values + } } @JS func roundTripArrayMembers(_ value: ArrayMembers) -> ArrayMembers { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 78271e1ba..d07f7b3e0 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -301,6 +301,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.deepEqual(arrayStructRoundTrip.optStrings, ["a", "b"]); assert.equal(exports.arrayMembersSum(arrayStruct, [10, 20]), 30); assert.equal(exports.arrayMembersFirst(arrayStruct, ["x", "y"]), "x"); + assert.equal(arrayStructRoundTrip.sumValues([10, 20]), 30); + assert.equal(arrayStructRoundTrip.firstString(["x", "y"]), "x"); + assert.throws(() => arrayStructRoundTrip.requireValues([]), /Values must not be empty/); + assert.deepEqual(arrayStructRoundTrip.requireValues([10, 20]), [1, 2, 3, 10, 20]); const jsValueArray = [true, 42, "ok", { nested: 1 }, null, undefined]; assert.deepEqual(exports.roundTripOptionalJSValueArray(jsValueArray), jsValueArray); assert.equal(exports.roundTripOptionalJSValueArray(null), null); From 511e46a358e9027ebbb3c2e84fa07e59fff1d505 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 15 Sep 2026 15:13:19 +0200 Subject: [PATCH 121/140] BridgeJS: Support custom exported type names --- .../BridgeJSCore/SwiftToSkeleton.swift | 156 +++++++------- .../Sources/BridgeJSLink/BridgeJSLink.swift | 200 +++++++++++------- .../Sources/BridgeJSLink/JSGlueGen.swift | 45 ++-- .../BridgeJSLink/JSIntrinsicRegistry.swift | 6 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 42 +++- .../Exporting-Swift/Exporting-Swift-Class.md | 42 ++++ .../Exporting-Swift/Exporting-Swift-Enum.md | 29 +++ .../Exporting-Swift-Protocols.md | 2 + .../Exporting-Swift/Exporting-Swift-Struct.md | 4 +- .../Exporting-Swift/Using-Namespace.md | 42 ++++ Sources/JavaScriptKit/Macros.swift | 21 +- 11 files changed, 409 insertions(+), 180 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 2fc6f8db3..63ce68fe5 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1068,6 +1068,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { struct NamespaceResolution { let namespace: [String]? + var jsNamespace: [String]? = nil let isValid: Bool } @@ -1079,7 +1080,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { declarationType: String ) -> NamespaceResolution { let attributeNamespace = extractNamespace(from: jsAttribute) - let computedNamespace = computeNamespace(for: node) + let computedNamespace = computeNamespace(for: node, includeParentTypes: true) if computedNamespace != nil && attributeNamespace != nil { diagnose( @@ -1091,7 +1092,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return NamespaceResolution(namespace: nil, isValid: false) } - return NamespaceResolution(namespace: computedNamespace ?? attributeNamespace, isValid: true) + let jsNamespace = computeNamespace(for: node, includeParentTypes: true, useJSNames: true) + return NamespaceResolution( + namespace: computedNamespace ?? attributeNamespace, + jsNamespace: jsNamespace != computedNamespace ? jsNamespace : nil, + isValid: true + ) } enum State { @@ -1288,10 +1294,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { switch type { case .swiftStruct(let name), .nullable(.swiftStruct(let name), _): isStructType = true - expectedTypeName = name.split(separator: ".").last.map(String.init) + expectedTypeName = name case .swiftHeapObject(let name), .nullable(.swiftHeapObject(let name), _): isStructType = false - expectedTypeName = name.split(separator: ".").last.map(String.init) + expectedTypeName = name default: diagnose( node: funcCall, @@ -1301,7 +1307,9 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return nil } - guard let expectedTypeName = expectedTypeName, typeName == expectedTypeName else { + guard let expectedTypeName = expectedTypeName, + typeName == expectedTypeName.split(separator: ".").last.map(String.init) + else { diagnose( node: funcCall, message: "Constructor type name '\(typeName)' doesn't match parameter type", @@ -1335,7 +1343,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .structLiteral(typeName, fields) } else { if funcCall.arguments.isEmpty { - return .object(typeName) + return .object(expectedTypeName) } var constructorArgs: [DefaultValue] = [] @@ -1350,7 +1358,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } constructorArgs.append(argValue) } - return .objectWithArguments(typeName, constructorArgs) + return .objectWithArguments(expectedTypeName, constructorArgs) } } @@ -2017,7 +2025,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } - diagnoseUnsupportedJSName(from: jsAttribute) + let jsName = extractValidatedJSName(from: jsAttribute) if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) @@ -2028,10 +2036,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } - let effectiveNamespace = effectiveNamespace( - resolvedNamespace: namespaceResult.namespace, - parentTypeNamespace: computeParentTypeNamespace(for: node) - ) + let effectiveNamespace = namespaceResult.namespace let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, @@ -2041,12 +2046,14 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let isFinal = node.modifiers.contains { $0.name.tokenKind == .keyword(.final) } ? true : nil let exportedClass = ExportedClass( name: name, + jsName: jsName, swiftCallName: swiftCallName, explicitAccessControl: explicitAccessControl, constructor: nil, methods: [], properties: [], namespace: effectiveNamespace, + jsNamespace: namespaceResult.jsNamespace, identityMode: classIdentityMode, documentation: extractDocumentation(from: node), isFinal: isFinal @@ -2126,6 +2133,14 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { aliasTarget: TypeSyntax ) { let swiftCallName = parent.computeSwiftCallName(for: node, itemName: node.name.text) + if extractJSName(from: jsAttribute) != nil { + diagnose( + node: jsAttribute, + message: "A separate name for JavaScript is not supported on `@JS(as:)` types", + hint: "Remove the name argument; an alias adopts its target's representation" + ) + return + } if extractNamespace(from: jsAttribute) != nil { errors.append( DiagnosticError( @@ -2167,7 +2182,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } - diagnoseUnsupportedJSName(from: jsAttribute) + let jsName = extractValidatedJSName(from: jsAttribute) if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) @@ -2185,10 +2200,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } - let effectiveNamespace = effectiveNamespace( - resolvedNamespace: namespaceResult.namespace, - parentTypeNamespace: computeParentTypeNamespace(for: node) - ) + let effectiveNamespace = namespaceResult.namespace let emitStyle = extractEnumStyle(from: jsAttribute) ?? .const let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( @@ -2196,22 +2208,16 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { message: "Enum visibility must be at least internal" ) - let tsFullPath: String - if let namespace = effectiveNamespace, !namespace.isEmpty { - tsFullPath = namespace.joined(separator: ".") + "." + name - } else { - tsFullPath = name - } - // Create enum directly in dictionary let exportedEnum = ExportedEnum( name: name, + jsName: jsName, swiftCallName: swiftCallName, - tsFullPath: tsFullPath, explicitAccessControl: explicitAccessControl, cases: [], // Will be populated in visit(EnumCaseDeclSyntax) rawType: SwiftEnumRawType(rawType), namespace: effectiveNamespace, + jsNamespace: namespaceResult.jsNamespace, emitStyle: emitStyle, staticMethods: [], staticProperties: [], @@ -2294,7 +2300,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } - diagnoseUnsupportedJSName(from: jsAttribute) + let jsName = extractValidatedJSName(from: jsAttribute) + + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute), jsName != nil { + recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) + return .skipChildren + } let name = node.name.text @@ -2302,10 +2313,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } - let effectiveNamespace = effectiveNamespace( - resolvedNamespace: namespaceResult.namespace, - parentTypeNamespace: computeParentTypeNamespace(for: node) - ) + let effectiveNamespace = namespaceResult.namespace _ = computeExplicitAtLeastInternalAccessControl( for: node, message: "Protocol visibility must be at least internal" @@ -2315,9 +2323,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { exportedProtocolByName[protocolUniqueKey] = ExportedProtocol( name: name, + jsName: jsName, methods: [], properties: [], namespace: effectiveNamespace, + jsNamespace: namespaceResult.jsNamespace, documentation: extractDocumentation(from: node) ) @@ -2340,9 +2350,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let exportedProtocol = ExportedProtocol( name: name, + jsName: jsName, methods: methods, properties: exportedProtocolByName[protocolUniqueKey]?.properties ?? [], namespace: effectiveNamespace, + jsNamespace: namespaceResult.jsNamespace, documentation: extractDocumentation(from: node) ) @@ -2359,7 +2371,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } - diagnoseUnsupportedJSName(from: jsAttribute) + let jsName = extractValidatedJSName(from: jsAttribute) if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) @@ -2372,10 +2384,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard namespaceResult.isValid else { return .skipChildren } - let effectiveNamespace = effectiveNamespace( - resolvedNamespace: namespaceResult.namespace, - parentTypeNamespace: computeParentTypeNamespace(for: node) - ) + let effectiveNamespace = namespaceResult.namespace let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, @@ -2437,11 +2446,13 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let structUniqueKey = makeKey(name: name, namespace: effectiveNamespace) let exportedStruct = ExportedStruct( name: name, + jsName: jsName, swiftCallName: swiftCallName, explicitAccessControl: explicitAccessControl, properties: properties, methods: [], namespace: effectiveNamespace, + jsNamespace: namespaceResult.jsNamespace, documentation: extractDocumentation(from: node) ) @@ -2595,9 +2606,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { currentProtocol = ExportedProtocol( name: currentProtocol.name, + jsName: currentProtocol.jsName, methods: currentProtocol.methods, properties: properties, namespace: currentProtocol.namespace, + jsNamespace: currentProtocol.jsNamespace, documentation: currentProtocol.documentation ) exportedProtocolByName[protocolKey] = currentProtocol @@ -2684,61 +2697,44 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .visitChildren } - /// Computes namespace by walking up the AST hierarchy to find parent namespace enums - /// If parent enum is a namespace enum (no cases) then it will be used as part of namespace for given node - /// - /// - /// 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]? { + /// Computes inherited namespaces using Swift names for ABI generation or public names for exports. + private func computeNamespace( + for node: some SyntaxProtocol, + includeParentTypes: Bool = false, + useJSNames: Bool = false + ) -> [String]? { var namespace: [String] = [] for declaration in parent.enclosingDeclarations(of: node) { + let name: String + let jsAttribute: AttributeSyntax if let enumDecl = declaration.as(EnumDeclSyntax.self), - enumDecl.attributes.hasJSAttribute() + let attribute = enumDecl.attributes.firstJSAttribute, + !enumDecl.memberBlock.members.contains(where: { $0.decl.is(EnumCaseDeclSyntax.self) }) { - let isNamespaceEnum = !enumDecl.memberBlock.members.contains { member in - member.decl.is(EnumCaseDeclSyntax.self) - } - if isNamespaceEnum { - namespace.insert(enumDecl.name.text, at: 0) - - if let jsAttribute = enumDecl.attributes.firstJSAttribute, - let explicitNamespace = extractNamespace(from: jsAttribute) - { - namespace = explicitNamespace + namespace - break - } - } - } - } - - return namespace.isEmpty ? nil : namespace - } - - private func computeParentTypeNamespace(for node: some SyntaxProtocol) -> [String]? { - var path: [String] = [] - - for declaration in parent.enclosingDeclarations(of: node) { - if let structDecl = declaration.as(StructDeclSyntax.self), - structDecl.attributes.hasJSAttribute() + name = enumDecl.name.text + jsAttribute = attribute + } else if includeParentTypes, let structDecl = declaration.as(StructDeclSyntax.self), + let attribute = structDecl.attributes.firstJSAttribute { - path.insert(structDecl.name.text, at: 0) - } else if let classDecl = declaration.as(ClassDeclSyntax.self), - classDecl.attributes.hasJSAttribute() + name = structDecl.name.text + jsAttribute = attribute + } else if includeParentTypes, let classDecl = declaration.as(ClassDeclSyntax.self), + let attribute = classDecl.attributes.firstJSAttribute { - path.insert(classDecl.name.text, at: 0) + name = classDecl.name.text + jsAttribute = attribute + } else { + continue + } + namespace.insert(useJSNames ? extractJSName(from: jsAttribute) ?? name : name, at: 0) + if let explicitNamespace = extractNamespace(from: jsAttribute) { + namespace = explicitNamespace + namespace + break } } - return path.isEmpty ? nil : path - } - - private func effectiveNamespace( - resolvedNamespace: [String]?, - parentTypeNamespace: [String]? - ) -> [String]? { - let combined = (parentTypeNamespace ?? []) + (resolvedNamespace ?? []) - return combined.isEmpty ? nil : combined + return namespace.isEmpty ? nil : namespace } /// Requires the node to have at least internal access control. diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index cf6eab60c..5d41869f8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -226,7 +226,7 @@ public struct BridgeJSLink { } } - for structDefinition in skeleton.structs where structDefinition.namespace == nil { + for structDefinition in skeleton.structs where structDefinition.resolvedJSNamespace == nil { data.topLevelDtsTypeLines.append( contentsOf: renderExportedStructInterface(structDefinition) ) @@ -405,7 +405,6 @@ public struct BridgeJSLink { scope: JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry), printer: printer, hasDirectAccessToSwiftClass: false, - classNamespaces: intrinsicRegistry.classNamespaces ) } @@ -1022,7 +1021,7 @@ 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.write("export interface \(proto.resolvedJSName) {") printer.indent { for method in proto.methods { printer.write( @@ -1057,7 +1056,7 @@ public struct BridgeJSLink { // Use fully-qualified path for namespaced enums let fullEnumValuesPath: String - if let namespace = enumDefinition.namespace, !namespace.isEmpty { + if let namespace = enumDefinition.resolvedJSNamespace, !namespace.isEmpty { fullEnumValuesPath = namespace.joined(separator: ".") + "." + enumValuesName } else { fullEnumValuesPath = enumValuesName @@ -1134,7 +1133,7 @@ public struct BridgeJSLink { renderPropertyEntry: { property in let readonly = property.isReadonly ? "readonly " : "" return self.renderJSDoc(documentation: property.documentation, parameters: []) - + ["\(readonly)\(property.resolvedJSName): \(property.type.tsType);"] + + ["\(readonly)\(property.resolvedJSName): \(self.resolveTypeScriptType(property.type));"] } ) printer.write("export type Exports = {") @@ -1226,7 +1225,6 @@ public struct BridgeJSLink { scope: structScope, printer: structPrinter, hasDirectAccessToSwiftClass: false, - classNamespaces: intrinsicRegistry.classNamespaces ) ) bodyPrinter.write(lines: structPrinter.lines) @@ -1248,7 +1246,6 @@ public struct BridgeJSLink { scope: enumScope, printer: enumPrinter, hasDirectAccessToSwiftClass: false, - classNamespaces: intrinsicRegistry.classNamespaces ) ) bodyPrinter.write(lines: enumPrinter.lines) @@ -1348,12 +1345,14 @@ public struct BridgeJSLink { 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 - guard let skeleton = unified.exported else { return } - for klass in skeleton.classes { - if let namespace = klass.namespace { - result[klass.name] = namespace - } + intrinsicRegistry.classPaths = skeletons.reduce(into: [:]) { result, unified in + for klass in unified.exported?.classes ?? [] { + result[klass.swiftCallName] = klass.tsPathComponents + } + } + intrinsicRegistry.renamedEnumNames = skeletons.reduce(into: [:]) { result, unified in + for enumDef in unified.exported?.enums ?? [] where enumDef.resolvedJSName != enumDef.name { + result[enumDef.swiftCallName] = (value: enumDef.valuesName, type: enumDef.resolvedJSName) } } intrinsicRegistry.typeOwnerModules = collectTypeOwnerModules() @@ -1454,9 +1453,10 @@ public struct BridgeJSLink { for klass in classes.sorted(by: { $0.name < $1.name }) { let wrapperFunctionName = "bjs_\(klass.abiName)_wrap" - let namespacePath = (klass.namespace ?? []).map { ".\($0)" }.joined() + let namespacePath = (klass.resolvedJSNamespace ?? []).map { ".\($0)" }.joined() let exportsPath = - namespacePath.isEmpty ? "_exports['\(klass.name)']" : "_exports\(namespacePath).\(klass.name)" + namespacePath.isEmpty + ? "_exports['\(klass.resolvedJSName)']" : "_exports\(namespacePath).\(klass.resolvedJSName)" wrapperLines.append("importObject[\"\(moduleName)\"][\"\(wrapperFunctionName)\"] = function(pointer) {") wrapperLines.append(" const obj = \(exportsPath).__construct(pointer);") wrapperLines.append(" return \(JSGlueVariableScope.reservedSwift).memory.retain(obj);") @@ -1570,7 +1570,6 @@ public struct BridgeJSLink { scope: scope, printer: body, hasDirectAccessToSwiftClass: hasDirectAccessToSwiftClass, - classNamespaces: intrinsicRegistry.classNamespaces ) } @@ -1665,7 +1664,10 @@ public struct BridgeJSLink { ) -> [String] { let printer = CodeFragmentPrinter() - let parameterList = DefaultValueUtils.formatParameterList(parameters) + let parameterList = DefaultValueUtils.formatParameterList( + parameters, + resolveTypeName: context.defaultValueTypeName + ) printer.write( "\(declarationPrefixKeyword.map { "\($0) "} ?? "")\(name)(\(parameterList)) {" @@ -1679,15 +1681,12 @@ public struct BridgeJSLink { } } - /// Returns TypeScript type string for a BridgeType, using full paths for enums - /// If the type is an enum, looks up the ExportedEnum and uses its tsFullPath - /// Otherwise, uses the default tsType property + /// Resolves public TypeScript names without changing the skeleton's Swift type identities. private func resolveTypeScriptType(_ type: BridgeType) -> String { return Self.resolveTypeScriptType(type, exportedSkeletons: skeletons.compactMap(\.exported)) } - /// Static helper for resolving TypeScript types with full enum paths - /// Can be used by both BridgeJSLink and NamespaceBuilder + /// Recursively resolves nominal types in signatures shared by the linker and namespace builder. fileprivate static func resolveTypeScriptType(_ type: BridgeType, exportedSkeletons: [ExportedSkeleton]) -> String { switch type { case .caseEnum(let name), .rawValueEnum(let name, _), @@ -1723,11 +1722,18 @@ public struct BridgeJSLink { for skeleton in exportedSkeletons { for klass in skeleton.classes { if klass.swiftCallName == name { - return klass.name + return klass.resolvedJSName } } } return type.tsType + case .swiftProtocol(let name): + for skeleton in exportedSkeletons { + if let proto = skeleton.protocols.first(where: { $0.name == name }) { + return proto.resolvedJSName + } + } + return type.tsType case .closure(let signature, _): return signature.renderTSFunctionType { resolveTypeScriptType($0, exportedSkeletons: exportedSkeletons) } case .alias(_, let underlying): @@ -1790,7 +1796,7 @@ public struct BridgeJSLink { for line in renderJSDoc(documentation: structDefinition.documentation, parameters: []) { dtsTypePrinter.write(line) } - dtsTypePrinter.write("export interface \(structDefinition.name) {") + dtsTypePrinter.write("export interface \(structDefinition.resolvedJSName) {") dtsTypePrinter.indent { for property in structDefinition.properties where !property.isStatic { let tsType = resolveTypeScriptType(property.type) @@ -1865,7 +1871,10 @@ public struct BridgeJSLink { ) let constructorPrinter = CodeFragmentPrinter() - let paramList = DefaultValueUtils.formatParameterList(constructor.parameters) + let paramList = DefaultValueUtils.formatParameterList( + constructor.parameters, + resolveTypeName: thunkBuilder.context.defaultValueTypeName + ) constructorPrinter.write("init: function(\(paramList)) {") constructorPrinter.indent { thunkBuilder.renderFunctionBody(into: constructorPrinter, returnExpr: returnExpr) @@ -1924,7 +1933,7 @@ public struct BridgeJSLink { break } - if enumDefinition.namespace == nil { + if enumDefinition.resolvedJSNamespace == nil { dtsTypeLines.append(contentsOf: generateDeclarations(enumDefinition: enumDefinition)) } @@ -1933,7 +1942,7 @@ public struct BridgeJSLink { if enumDefinition.enumType != .namespace && enumDefinition.emitStyle != .tsEnum - && enumDefinition.namespace == nil + && enumDefinition.resolvedJSNamespace == nil { var enumMethodLines: [String] = [] for function in enumDefinition.staticMethods { @@ -1953,7 +1962,7 @@ public struct BridgeJSLink { let exportsPrinter = CodeFragmentPrinter() if !enumMethodLines.isEmpty || !enumPropertyLines.isEmpty { - exportsPrinter.write("\(enumDefinition.name): {") + exportsPrinter.write("\(enumDefinition.resolvedJSName): {") exportsPrinter.indent { exportsPrinter.write("...\(enumValuesName),") var allLines = enumMethodLines + enumPropertyLines @@ -1964,11 +1973,11 @@ public struct BridgeJSLink { } exportsPrinter.write("},") } else { - exportsPrinter.write("\(enumDefinition.name): \(enumValuesName),") + exportsPrinter.write("\(enumDefinition.resolvedJSName): \(enumValuesName),") } jsExportEntryLines = exportsPrinter.lines - dtsExportEntryLines = ["\(enumDefinition.name): \(enumDefinition.objectTypeName)"] + dtsExportEntryLines = ["\(enumDefinition.resolvedJSName): \(enumDefinition.objectTypeName)"] } return (jsTopLevelLines, jsExportEntryLines, dtsTypeLines, dtsExportEntryLines) @@ -1986,7 +1995,7 @@ public struct BridgeJSLink { case .tsEnum: switch enumDefinition.enumType { case .simple, .rawValue: - printer.write("export enum \(enumDefinition.name) {") + printer.write("export enum \(enumDefinition.resolvedJSName) {") printer.indent { for (index, enumCase) in enumDefinition.cases.enumerated() { let caseName = enumCase.name.capitalizedFirstLetter @@ -2020,7 +2029,7 @@ public struct BridgeJSLink { } printer.write("};") printer.write( - "export type \(enumDefinition.name)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" + "export type \(enumDefinition.resolvedJSName)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" ) printer.nextLine() case .associatedValue: @@ -2057,7 +2066,8 @@ public struct BridgeJSLink { } let unionTypeName = - enumDefinition.emitStyle == .tsEnum ? enumDefinition.name : "\(enumDefinition.name)Tag" + enumDefinition.emitStyle == .tsEnum + ? enumDefinition.resolvedJSName : "\(enumDefinition.resolvedJSName)Tag" printer.write("export type \(unionTypeName) =") printer.write(" " + unionParts.joined(separator: " | ")) printer.nextLine() @@ -2170,7 +2180,11 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let printer = CodeFragmentPrinter() - printer.write("\(function.resolvedJSName)(\(DefaultValueUtils.formatParameterList(function.parameters))) {") + let parameterList = DefaultValueUtils.formatParameterList( + function.parameters, + resolveTypeName: thunkBuilder.context.defaultValueTypeName + ) + printer.write("\(function.resolvedJSName)(\(parameterList)) {") printer.indent { thunkBuilder.renderFunctionBody(into: printer, returnExpr: returnExpr) } @@ -2226,8 +2240,12 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: method.abiName, returnType: method.returnType) let methodPrinter = CodeFragmentPrinter() + let parameterList = DefaultValueUtils.formatParameterList( + method.parameters, + resolveTypeName: thunkBuilder.context.defaultValueTypeName + ) methodPrinter.write( - "\(method.resolvedJSName): function(\(DefaultValueUtils.formatParameterList(method.parameters))) {" + "\(method.resolvedJSName): function(\(parameterList)) {" ) methodPrinter.indent { thunkBuilder.renderFunctionBody(into: methodPrinter, returnExpr: returnExpr) @@ -2296,8 +2314,8 @@ extension BridgeJSLink { for line in renderJSDoc(documentation: klass.documentation, parameters: []) { dtsTypePrinter.write(line) } - dtsTypePrinter.write("export interface \(klass.name) extends SwiftHeapObject {") - jsPrinter.write("class \(klass.name) extends SwiftHeapObject {") + dtsTypePrinter.write("export interface \(klass.resolvedJSName) extends SwiftHeapObject {") + jsPrinter.write("class \(klass.resolvedJSName) extends SwiftHeapObject {") // Per-class identity mode: determine at codegen time whether this class uses identity caching let useIdentity = shouldUseIdentityCache(for: klass) @@ -2310,11 +2328,11 @@ extension BridgeJSLink { jsPrinter.indent { if useIdentity { jsPrinter.write( - "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype, \(klass.name).__identityCache);" + "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.resolvedJSName).prototype, \(klass.resolvedJSName).__identityCache);" ) } else { jsPrinter.write( - "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.name).prototype, null);" + "return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_\(klass.abiName)_deinit, \(klass.resolvedJSName).prototype, null);" ) } } @@ -2331,12 +2349,15 @@ extension BridgeJSLink { try thunkBuilder.lowerParameter(param: param) } - let constructorParamList = DefaultValueUtils.formatParameterList(constructor.parameters) + let constructorParamList = DefaultValueUtils.formatParameterList( + constructor.parameters, + resolveTypeName: thunkBuilder.context.defaultValueTypeName + ) jsPrinter.indent { jsPrinter.write("constructor(\(constructorParamList)) {") let returnExpr = thunkBuilder.callConstructor(abiName: constructor.abiName) - let constructCall = "\(klass.name).__construct(\(returnExpr))" + let constructCall = "\(klass.resolvedJSName).__construct(\(returnExpr))" jsPrinter.indent { thunkBuilder.renderFunctionBody( into: jsPrinter, @@ -2430,7 +2451,7 @@ extension BridgeJSLink { lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) ) printer.write( - "new\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.name), effects: constructor.effects));" + "new\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.swiftCallName), effects: constructor.effects));" ) } for method in klass.methods where method.effects.isStatic { @@ -2452,12 +2473,12 @@ extension BridgeJSLink { ) -> [String] { let printer = CodeFragmentPrinter() printer.write(lines: renderJSDoc(documentation: klass.documentation, parameters: [])) - printer.write("class \(klass.name) {") + printer.write("class \(klass.resolvedJSName) {") 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)" + return "\(param.name)\(optional): \(resolveTypeScriptType(param.type))" } printer.write( lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) @@ -2584,7 +2605,6 @@ extension BridgeJSLink { scope: scope, printer: body, hasDirectAccessToSwiftClass: false, - classNamespaces: intrinsicRegistry.classNamespaces ) } @@ -2922,9 +2942,9 @@ extension BridgeJSLink { return Set( exportedSkeletons.flatMap { skeleton in let itemNamespaces = - (skeleton.functions.compactMap(\.namespace) + skeleton.classes.compactMap(\.namespace) - + skeleton.enums.filter { $0.namespace != nil && $0.enumType != .namespace } - .compactMap(\.namespace)) + (skeleton.functions.compactMap(\.namespace) + skeleton.classes.compactMap(\.resolvedJSNamespace) + + skeleton.enums.filter { $0.resolvedJSNamespace != nil && $0.enumType != .namespace } + .compactMap(\.resolvedJSNamespace)) let namespaceEnumPaths = skeleton.enums .filter { $0.enumType == .namespace } @@ -2951,8 +2971,9 @@ extension BridgeJSLink { var namespacedEnumPaths: Set<[String]> = [] for skeleton in globalSkeletons { - for enumDef in skeleton.enums where enumDef.namespace != nil && enumDef.enumType != .namespace { - namespacedEnumPaths.insert(enumDef.namespace!) + for enumDef in skeleton.enums where enumDef.resolvedJSNamespace != nil && enumDef.enumType != .namespace + { + namespacedEnumPaths.insert(enumDef.resolvedJSNamespace!) } } @@ -2962,8 +2983,9 @@ extension BridgeJSLink { printer.write(lines: initCode) for skeleton in globalSkeletons { - for enumDef in skeleton.enums where enumDef.namespace != nil && enumDef.enumType != .namespace { - let namespacePath = enumDef.namespace!.joined(separator: ".") + for enumDef in skeleton.enums where enumDef.resolvedJSNamespace != nil && enumDef.enumType != .namespace + { + let namespacePath = enumDef.resolvedJSNamespace!.joined(separator: ".") printer.write("globalThis.\(namespacePath).\(enumDef.valuesName) = \(enumDef.valuesName);") } } @@ -2975,9 +2997,11 @@ extension BridgeJSLink { let printer = CodeFragmentPrinter() for skeleton in exportedSkeletons where skeleton.exposeToGlobal { - for klass in skeleton.classes where klass.namespace != nil { - let namespacePath = klass.namespace!.joined(separator: ".") - printer.write("globalThis.\(namespacePath).\(klass.name) = exports.\(namespacePath).\(klass.name);") + for klass in skeleton.classes where klass.resolvedJSNamespace != nil { + let namespacePath = klass.resolvedJSNamespace!.joined(separator: ".") + printer.write( + "globalThis.\(namespacePath).\(klass.resolvedJSName) = exports.\(namespacePath).\(klass.resolvedJSName);" + ) } for function in skeleton.functions where function.namespace != nil { let namespacePath = function.namespace!.joined(separator: ".") @@ -3120,9 +3144,10 @@ extension BridgeJSLink { currentNode.content.declaration = .structType(structDef) } - for enumDef in skeleton.enums where enumDef.namespace != nil && enumDef.enumType != .namespace { + for enumDef in skeleton.enums where enumDef.resolvedJSNamespace != nil && enumDef.enumType != .namespace + { var currentNode = rootNode - for part in enumDef.namespace! { + for part in enumDef.resolvedJSNamespace! { currentNode = currentNode.addChild(part) } currentNode.content.enums.append(enumDef) @@ -3199,7 +3224,9 @@ extension BridgeJSLink { } for enumDef in node.content.enums { - node.content.enumDtsLines.append((enumDef.name, "\(enumDef.name): \(enumDef.objectTypeName)")) + node.content.enumDtsLines.append( + (enumDef.resolvedJSName, "\(enumDef.resolvedJSName): \(enumDef.objectTypeName)") + ) } for (_, childNode) in node.children { @@ -3410,7 +3437,7 @@ extension BridgeJSLink { printer.write(lines: node.content.structJsLines) for enumDef in node.content.enums.sorted(by: { $0.name < $1.name }) { - printer.write("\(enumDef.name): \(enumDef.valuesName),") + printer.write("\(enumDef.resolvedJSName): \(enumDef.valuesName),") } // Print function and property implementations @@ -3573,7 +3600,7 @@ extension BridgeJSLink { case .simple: switch style { case .tsEnum: - printer.write("enum \(enumDefinition.name) {") + printer.write("enum \(enumDefinition.resolvedJSName) {") printer.indent { for (index, enumCase) in enumDefinition.cases.enumerated() { let caseName = enumCase.name.capitalizedFirstLetter @@ -3591,14 +3618,14 @@ extension BridgeJSLink { } printer.write("};") printer.write( - "type \(enumDefinition.name)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" + "type \(enumDefinition.resolvedJSName)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" ) } case .rawValue: guard let rawType = enumDefinition.rawType else { continue } switch style { case .tsEnum: - printer.write("enum \(enumDefinition.name) {") + printer.write("enum \(enumDefinition.resolvedJSName) {") printer.indent { for (index, enumCase) in enumDefinition.cases.enumerated() { let caseName = enumCase.name.capitalizedFirstLetter @@ -3624,7 +3651,7 @@ extension BridgeJSLink { } printer.write("};") printer.write( - "type \(enumDefinition.name)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" + "type \(enumDefinition.resolvedJSName)Tag = typeof \(enumValuesName)[keyof typeof \(enumValuesName)];" ) } case .associatedValue: @@ -3663,7 +3690,8 @@ extension BridgeJSLink { } } let unionTypeName = - enumDefinition.emitStyle == .tsEnum ? enumDefinition.name : "\(enumDefinition.name)Tag" + enumDefinition.emitStyle == .tsEnum + ? enumDefinition.resolvedJSName : "\(enumDefinition.resolvedJSName)Tag" printer.write("type \(unionTypeName) =") printer.write(" " + unionParts.joined(separator: " | ")) case .namespace: @@ -3688,7 +3716,9 @@ extension BridgeJSLink { for property in sortedProperties { let readonly = property.isReadonly ? "var " : "let " printer.write(lines: renderDocCallback(property.documentation, [])) - printer.write("\(readonly)\(property.resolvedJSName): \(property.type.tsType);") + printer.write( + "\(readonly)\(property.resolvedJSName): \(BridgeJSLink.resolveTypeScriptType(property.type, exportedSkeletons: exportedSkeletons));" + ) } } @@ -3769,7 +3799,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)): \(resolveTypeScriptType(getter.type));"] ) } importObjectBuilder.assignToImportObject(name: abiName, function: funcLines) @@ -4036,7 +4067,11 @@ enum DefaultValueUtils { } /// Generates default value representation for JavaScript or TypeScript - static func format(_ defaultValue: DefaultValue, as format: OutputFormat) -> String { + static func format( + _ defaultValue: DefaultValue, + as format: OutputFormat, + resolveTypeName: (BridgeType, OutputFormat) -> String? = { _, _ in nil } + ) -> String { switch defaultValue { case .string(let value): let escapedValue = @@ -4056,23 +4091,26 @@ enum DefaultValueUtils { return "null" case .enumCase(let enumName, let caseName): let simpleName = enumName.components(separatedBy: ".").last ?? enumName - let jsEnumName = format == .javascript ? "\(simpleName)\(ExportedEnum.valuesSuffix)" : simpleName + let jsEnumName = + resolveTypeName(.caseEnum(enumName), format) + ?? (format == .javascript ? "\(simpleName)\(ExportedEnum.valuesSuffix)" : simpleName) return "\(jsEnumName).\(caseName.capitalizedFirstLetter)" case .object(let className): - return "new \(className)()" + return "new \(resolveTypeName(.swiftHeapObject(className), format) ?? className)()" case .objectWithArguments(let className, let args): let argStrings = args.map { arg in - Self.format(arg, as: format) + Self.format(arg, as: format, resolveTypeName: resolveTypeName) } - return "new \(className)(\(argStrings.joined(separator: ", ")))" + let name = resolveTypeName(.swiftHeapObject(className), format) ?? className + return "new \(name)(\(argStrings.joined(separator: ", ")))" case .structLiteral(_, let fields): let fieldStrings = fields.map { field in - "\(field.name): \(Self.format(field.value, as: format))" + "\(field.name): \(Self.format(field.value, as: format, resolveTypeName: resolveTypeName))" } return "{ \(fieldStrings.joined(separator: ", ")) }" case .array(let elements): let elementStrings = elements.map { element in - DefaultValueUtils.format(element, as: format) + DefaultValueUtils.format(element, as: format, resolveTypeName: resolveTypeName) } return "[\(elementStrings.joined(separator: ", "))]" } @@ -4086,10 +4124,13 @@ enum DefaultValueUtils { } /// Generates a JavaScript parameter list with default values - static func formatParameterList(_ parameters: [Parameter]) -> String { + static func formatParameterList( + _ parameters: [Parameter], + resolveTypeName: (BridgeType, OutputFormat) -> String? = { _, _ in nil } + ) -> String { return parameters.map { param in if let defaultValue = param.defaultValue { - let defaultJs = format(defaultValue, as: .javascript) + let defaultJs = format(defaultValue, as: .javascript, resolveTypeName: resolveTypeName) return "\(param.name) = \(defaultJs)" } return param.name @@ -4104,10 +4145,17 @@ extension BridgeJSLink { fileprivate func renderJSDoc(documentation: String?, parameters: [Parameter]) -> [String] { let parsed = documentation.map(DocCComment.init(parsing:)) ?? DocCComment() + let resolveTypeName = makeCodecPrintContext(printer: CodeFragmentPrinter()).defaultValueTypeName var tagLines: [String] = [] for parameter in parameters { let docText = parsed.parameter(named: parameter.name) - let defaultValue = parameter.defaultValue.map { DefaultValueUtils.format($0, as: .typescript) } + let defaultValue = parameter.defaultValue.map { + DefaultValueUtils.format( + $0, + as: .typescript, + resolveTypeName: resolveTypeName + ) + } switch (docText, defaultValue) { case let (.some(text), .some(value)): tagLines.append("@param \(parameter.name) \(text) (default: \(value))") diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index cb79b5625..747c9f532 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -110,6 +110,14 @@ final class JSGlueVariableScope { intrinsicRegistry.typeOwnerModules[typeName] } + func exportedClassPath(forSwiftName name: String) -> [String]? { + intrinsicRegistry.classPaths[name] + } + + func renamedEnumNames(forSwiftName name: String) -> (value: String, type: String)? { + intrinsicRegistry.renamedEnumNames[name] + } + func makeChildScope() -> JSGlueVariableScope { JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) } @@ -532,8 +540,6 @@ struct IntrinsicJSFragment: Sendable { /// Whether the fragment has direct access to the SwiftHeapObject classes. /// If false, the fragment needs to use `_exports` to access the class. var hasDirectAccessToSwiftClass: Bool = true - /// Maps class names to their namespace path components for resolving `_exports` access. - var classNamespaces: [String: [String]] = [:] func with(_ keyPath: WritableKeyPath, _ value: T) -> PrintCodeContext { var new = self @@ -545,20 +551,30 @@ struct IntrinsicJSFragment: Sendable { qualifiedName.split(separator: ".").last.map(String.init) ?? qualifiedName } - private func exportsAccess(forClass name: String) -> String { - if let namespace = classNamespaces[name], !namespace.isEmpty { - let path = namespace.map { ".\($0)" }.joined() - return "_exports\(path).\(name)" - } - return "_exports['\(name)']" - } - func classReference(forQualifiedName qualifiedName: String) -> String { + if let path = scope.exportedClassPath(forSwiftName: qualifiedName), let name = path.last { + if hasDirectAccessToSwiftClass { + return name + } + return path.count == 1 ? "_exports['\(name)']" : "_exports.\(path.joined(separator: "."))" + } if hasDirectAccessToSwiftClass { return unqualifiedClassName(for: qualifiedName) } - let unqualified = unqualifiedClassName(for: qualifiedName) - return exportsAccess(forClass: unqualified) + return "_exports['\(unqualifiedClassName(for: qualifiedName))']" + } + + func defaultValueTypeName(_ type: BridgeType, _ format: DefaultValueUtils.OutputFormat) -> String? { + switch type { + case .swiftHeapObject(let name): + guard let jsName = scope.exportedClassPath(forSwiftName: name)?.last else { return nil } + return format == .javascript ? classReference(forQualifiedName: name) : jsName + case .caseEnum(let name): + guard let renamed = scope.renamedEnumNames(forSwiftName: name) else { return nil } + return format == .javascript ? renamed.value : renamed.type + default: + return nil + } } } @@ -2565,7 +2581,10 @@ struct IntrinsicJSFragment: Sendable { // Attach instance methods to the struct instance for method in structDef.methods where !method.effects.isStatic { - let paramList = DefaultValueUtils.formatParameterList(method.parameters) + let paramList = DefaultValueUtils.formatParameterList( + method.parameters, + resolveTypeName: context.defaultValueTypeName + ) printer.write( "\(instanceVar).\(method.resolvedJSName) = function(\(paramList)) {" ) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift index d0bf2781f..8dfca16b6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift @@ -5,7 +5,8 @@ import BridgeJSUtilities /// Registry for JS helper intrinsics used during code generation. final class JSIntrinsicRegistry { private var entries: [String: [String]] = [:] - var classNamespaces: [String: [String]] = [:] + var classPaths: [String: [String]] = [:] + var renamedEnumNames: [String: (value: String, type: String)] = [:] var typeOwnerModules: [String: String] = [:] @@ -42,7 +43,8 @@ final class JSIntrinsicRegistry { func reset() { entries.removeAll() - classNamespaces.removeAll() + classPaths.removeAll() + renamedEnumNames.removeAll() typeOwnerModules.removeAll() codecNameOrder.removeAll() codecBodies.removeAll() diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 8aaa6d5cd..ce85176cc 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -4,10 +4,17 @@ public protocol NamespacedExportedType { var name: String { get } + var jsName: String? { get } + /// The namespace using Swift declaration names, retained for ABI generation. var namespace: [String]? { get } + /// The public namespace when an enclosing declaration has an exported name override. + var jsNamespace: [String]? { get } } extension NamespacedExportedType { + public var resolvedJSName: String { jsName ?? name } + public var resolvedJSNamespace: [String]? { jsNamespace ?? namespace } + public var abiName: String { if let namespace = namespace, !namespace.isEmpty { return (namespace + [name]).joined(separator: "_") @@ -16,7 +23,7 @@ extension NamespacedExportedType { } public var tsPathComponents: [String] { - (namespace ?? []) + [name] + (resolvedJSNamespace ?? []) + [resolvedJSName] } public var tsFullPath: String { @@ -778,31 +785,37 @@ public struct StructField: Codable, Equatable, Sendable { public struct ExportedStruct: Codable, Equatable, Sendable, NamespacedExportedType { public let name: String + public let jsName: String? public let swiftCallName: String public let explicitAccessControl: String? public var properties: [ExportedProperty] public var constructor: ExportedConstructor? public var methods: [ExportedFunction] public let namespace: [String]? + public let jsNamespace: [String]? public var documentation: String? public init( name: String, + jsName: String? = nil, swiftCallName: String, explicitAccessControl: String?, properties: [ExportedProperty] = [], constructor: ExportedConstructor? = nil, methods: [ExportedFunction] = [], namespace: [String]?, + jsNamespace: [String]? = nil, documentation: String? = nil ) { self.name = name + self.jsName = jsName self.swiftCallName = swiftCallName self.explicitAccessControl = explicitAccessControl self.properties = properties self.constructor = constructor self.methods = methods self.namespace = namespace + self.jsNamespace = jsNamespace self.documentation = documentation } } @@ -864,12 +877,14 @@ public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType public static let objectSuffix = "Object" public let name: String + public let jsName: String? public let swiftCallName: String public let tsFullPath: String public let explicitAccessControl: String? public var cases: [EnumCase] public let rawType: SwiftEnumRawType? public let namespace: [String]? + public let jsNamespace: [String]? public let emitStyle: EnumEmitStyle public var staticMethods: [ExportedFunction] public var staticProperties: [ExportedProperty] = [] @@ -885,33 +900,36 @@ public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType } public var valuesName: String { - emitStyle == .tsEnum ? name : "\(name)\(Self.valuesSuffix)" + emitStyle == .tsEnum ? resolvedJSName : "\(resolvedJSName)\(Self.valuesSuffix)" } public var objectTypeName: String { - "\(name)\(Self.objectSuffix)" + "\(resolvedJSName)\(Self.objectSuffix)" } public init( name: String, + jsName: String? = nil, swiftCallName: String, - tsFullPath: String, explicitAccessControl: String?, cases: [EnumCase], rawType: SwiftEnumRawType?, namespace: [String]?, + jsNamespace: [String]? = nil, emitStyle: EnumEmitStyle, staticMethods: [ExportedFunction] = [], staticProperties: [ExportedProperty] = [], documentation: String? = nil ) { self.name = name + self.jsName = jsName self.swiftCallName = swiftCallName - self.tsFullPath = tsFullPath + self.tsFullPath = ((jsNamespace ?? namespace ?? []) + [jsName ?? name]).joined(separator: ".") self.explicitAccessControl = explicitAccessControl self.cases = cases self.rawType = rawType self.namespace = namespace + self.jsNamespace = jsNamespace self.emitStyle = emitStyle self.staticMethods = staticMethods self.staticProperties = staticProperties @@ -947,24 +965,30 @@ public struct ExportedProtocolProperty: Codable, Equatable, Sendable { } } -public struct ExportedProtocol: Codable, Equatable { +public struct ExportedProtocol: Codable, Equatable, NamespacedExportedType { public let name: String + public let jsName: String? public let methods: [ExportedFunction] public let properties: [ExportedProtocolProperty] public let namespace: [String]? + public let jsNamespace: [String]? public var documentation: String? public init( name: String, + jsName: String? = nil, methods: [ExportedFunction], properties: [ExportedProtocolProperty] = [], namespace: [String]? = nil, + jsNamespace: [String]? = nil, documentation: String? = nil ) { self.name = name + self.jsName = jsName self.methods = methods self.properties = properties self.namespace = namespace + self.jsNamespace = jsNamespace self.documentation = documentation } } @@ -1007,35 +1031,41 @@ public struct ExportedFunction: Codable, Equatable, Sendable { public struct ExportedClass: Codable, NamespacedExportedType { public var name: String + public var jsName: String? public var swiftCallName: String public var explicitAccessControl: String? public var constructor: ExportedConstructor? public var methods: [ExportedFunction] public var properties: [ExportedProperty] public var namespace: [String]? + public var jsNamespace: [String]? public var identityMode: Bool? // nil = use config default, true/false = override public var documentation: String? public var isFinal: Bool? public init( name: String, + jsName: String? = nil, swiftCallName: String, explicitAccessControl: String?, constructor: ExportedConstructor? = nil, methods: [ExportedFunction], properties: [ExportedProperty] = [], namespace: [String]? = nil, + jsNamespace: [String]? = nil, identityMode: Bool? = nil, documentation: String? = nil, isFinal: Bool? = nil ) { self.name = name + self.jsName = jsName self.swiftCallName = swiftCallName self.explicitAccessControl = explicitAccessControl self.constructor = constructor self.methods = methods self.properties = properties self.namespace = namespace + self.jsNamespace = jsNamespace self.identityMode = identityMode self.documentation = documentation self.isFinal = isFinal diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md index 8a1b7dff5..09bc51d79 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -77,6 +77,48 @@ export type Exports = { } ``` +## Choosing an Exported Name + +Pass a name to `@JS` to expose a class under a different JavaScript and TypeScript name while keeping its Swift identifier: + +```swift +@JS("Counter") class InternalCounter { + @JS var value: Int + + @JS init(value: Int) { + self.value = value + } + + @JS static func make(_ value: Int) -> InternalCounter { + InternalCounter(value: value) + } + + @JS func roundTrip(_ other: InternalCounter?) -> InternalCounter? { + other + } +} +``` + +After initializing the package, use the constructor and static factory on that WASM instance's `exports` object: + +```javascript +const counter = new exports.Counter(1); +const other = exports.Counter.make(2); +const returned = counter.roundTrip(other); +console.log(returned.value); // 2 +returned.release(); +other.release(); +counter.release(); +``` + +The generated TypeScript interface is named `Counter`, and signatures refer to `Counter`, including in optionals, arrays, and callbacks. For example, `roundTrip` accepts and returns `Counter | null`. The old name `InternalCounter` is not also exported. Swift code continues to use `InternalCounter`, including in extensions and return types. + +The constructor remains instance-owned: use `exports.Counter`, not a named JavaScript module import such as `import { Counter } from "./bridge-js.js"`. A TypeScript type-only import of `Counter` refers to the generated interface, not a constructor value. Renaming does not change reference semantics, `release()`, or identity mode. + +This naming option also applies to structs, enums, and protocols. For namespace composition and nested types, see . + +> Important: `@JS("Counter")` only changes the exported symbol. `@JS(as: Other.self)` instead changes the JavaScript representation through `bridgeToJS()` and `bridgeFromJS(_:)`. Combining a name override with `as:` on the same declaration produces a diagnostic. + ## Adding Members via Extensions You can add exported methods, computed properties, and static members to a `@JS` class using extensions. The extension block itself does not need `@JS` - only the individual members do: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md index 68996b27b..6d7af6799 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md @@ -19,6 +19,35 @@ BridgeJS generates separate objects with descriptive naming for `.const` enums: - **`EnumNameTag`**: Represents the union type for enums - **`EnumNameObject`**: Object type for all const-style enums, contains static members for enums with methods/properties or references the values type for simple enums +### Choosing an Exported Name + +A name passed to `@JS` changes the generated naming stem, not the Swift enum or its representation: + +```swift +@JS("TaskState") enum InternalTaskState: String { + case pending + case complete +} + +@JS func roundTripState(_ state: InternalTaskState) -> InternalTaskState { + state +} +``` + +With the default `.const` style, this generates `TaskStateValues`, `TaskStateTag`, and `TaskStateObject` instead of names beginning with `InternalTaskState`. The instance export is `exports.TaskState`, and function signatures use `TaskStateTag`: + +```typescript +import { TaskStateValues } from "./bridge-js.js"; +import type { TaskStateTag } from "./bridge-js.js"; + +const state: TaskStateTag = exports.roundTripState(TaskStateValues.Pending); +console.log(state === exports.TaskState.Pending); // true +``` + +The same naming rule applies to associated-value enums, including their payload type references. With `@JS("TaskState", enumStyle: .tsEnum)`, the TypeScript enum itself is named `TaskState`. Case names, raw values, and associated-value layouts are unchanged. + +For empty enums used as namespaces, the override names the namespace object. Nested declarations use that renamed parent in their export paths; see . + ### Case Enums ```swift diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md index 3b2ec1526..d62d71051 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md @@ -13,6 +13,8 @@ When you mark a protocol with `@JS`, BridgeJS generates: - A TypeScript interface with the protocol's method signatures - A Swift wrapper struct (`Any{ProtocolName}`) that conforms to the protocol and bridges calls to JavaScript objects +Use `@JS("PublicName")` on a protocol to rename its TypeScript interface and generated type references. Swift still uses the original protocol name for conformances and signatures. JavaScript objects still satisfy the interface structurally; renaming does not create a protocol constructor or change how callbacks and protocol values cross the boundary. Unlike `@JS(as: Other.self)`, it does not change the representation, and combining the two options is not supported. + ## Example: Counter Protocol Mark a Swift protocol with `@JS` to expose it: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md index c4a9524d9..208c80a25 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md @@ -6,7 +6,9 @@ Learn how to export Swift structs to JavaScript. > 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/). -To export a Swift struct, mark it with `@JS`: +To export a Swift struct, mark it with `@JS`. + +Use `@JS("PublicName")` to choose a different JavaScript and TypeScript name while keeping the Swift struct name. Generated interfaces, type references, and the instance export containing any exported initializer or static members use the chosen name. This does not change copy semantics or field names. Unlike `@JS(as: Other.self)`, it does not change the representation; the two options cannot be combined. See for an example of naming an exported type. ```swift import JavaScriptKit diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md index 1aff82f65..e24f45a24 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md @@ -121,3 +121,45 @@ export interface Greeter extends SwiftHeapObject { ``` Using namespaces can be preferable for projects with many global functions, as they help prevent naming collisions. Namespaces also provide intuitive hierarchies for organizing your exported Swift code, and they do not affect the code generated by `@JS` declarations without namespaces. + +## Renamed Types in Namespaces + +The first argument to `@JS` controls a declaration's exported name; `namespace:` controls where it appears. Use both to separate Swift implementation names from your JavaScript API. + +Type names must be valid JavaScript/TypeScript identifiers. + +```swift +@JS("Store", namespace: "MyApp") enum InternalStore { + @JS("Item") class InternalItem { + @JS var title: String + + @JS init(title: String) { + self.title = title + } + + @JS enum State: String { + case available + case reserved + } + } + + @JS static func makeItem(_ title: String) -> InternalStore.InternalItem { + InternalStore.InternalItem(title: title) + } +} +``` + +Nested declarations use their parents' exported names, even when a nested declaration has no name override of its own: + +```javascript +const item = new exports.MyApp.Store.Item("Notebook"); +const another = exports.MyApp.Store.makeItem("Pencil"); +console.log(item.title); // "Notebook" +console.log(exports.MyApp.Store.Item.State.Available); // "available" +item.release(); +another.release(); +``` + +The export paths contain neither `InternalStore` nor `InternalItem`. Generated TypeScript type references also use the renamed types. Swift paths remain `InternalStore.InternalItem` and `InternalStore.InternalItem.State`. + +The same exported paths are available under `globalThis` only when `exposeToGlobal: true` is enabled. Renaming does not enable global exports or turn instance-owned constructors into named JavaScript module exports. See for the distinction between a type name and a constructor value. diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index a1cdc0c44..1e1b72dfb 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -50,7 +50,7 @@ public enum JSName: ExpressibleByStringLiteral { } } -/// A macro that exposes Swift functions, classes, and methods to JavaScript. +/// A macro that exposes Swift declarations to JavaScript and TypeScript. /// /// Apply this macro to Swift declarations that you want to make callable from JavaScript: /// @@ -138,9 +138,26 @@ public enum JSName: ExpressibleByStringLiteral { /// accessible from JavaScript, and TypeScript declaration files (`.d.ts`) will be /// automatically generated to provide type safety. /// +/// Use the first argument to choose a JavaScript and TypeScript name without changing +/// the Swift identifier: `@JS("Counter") class InternalCounter`. This also works on +/// structs, enums, and protocols. Generated type references use the chosen name, +/// including references in optional, array, and callback signatures. Nested exported +/// declarations inherit their enclosing types' exported names in their namespace paths. +/// For const-style enums, the chosen name is the stem of the generated `Values`, `Tag`, +/// and `Object` names. +/// +/// A renamed class constructor is still accessed through the WASM instance's exports +/// object, such as `exports.Counter`, not as a named JavaScript module export. +/// Renaming does not change bridging or memory-management semantics. In contrast, +/// `@JS(as: Other.self)` changes the JavaScript representation using conversion methods. +/// Combining a custom name with `as:` on the same declaration is not supported. +/// /// For detailed usage information, see the article . /// -/// - Parameter name: A different name to use in the exported JavaScript. +/// - Parameter name: A different JavaScript and TypeScript name for the exported declaration. +/// Does not rename the Swift declaration or change its representation. +/// - Parameter aliasOf: A different JavaScript representation, supplied as `as: Other.self`. +/// Requires `bridgeToJS()` and `bridgeFromJS(_:)` conversions and cannot be combined with `name`. /// - 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: From 1711b358e1b7a565b111fbbdb55105e5ffb5a266 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 15 Sep 2026 15:13:37 +0200 Subject: [PATCH 122/140] BridgeJS: Test custom exported type names --- .../BridgeJSToolTests/DiagnosticsTests.swift | 36 -- .../ExportedTypeNameTests.swift | 60 ++++ .../Inputs/MacroSwift/JSNameTypes.swift | 11 + .../BridgeJSCodegenTests/JSNameTypes.json | 115 +++++++ .../BridgeJSCodegenTests/JSNameTypes.swift | 124 +++++++ .../BridgeJSLinkTests/JSNameTypes.d.ts | 40 +++ .../BridgeJSLinkTests/JSNameTypes.js | 313 ++++++++++++++++++ .../Generated/BridgeJS.swift | 103 ++++++ .../Generated/JavaScript/BridgeJS.json | 153 +++++++++ Tests/BridgeJSRuntimeTests/JSNameAPIs.swift | 20 +- .../JavaScript/JSNameTests.mjs | 37 +++ Tests/prelude.mjs | 13 +- 12 files changed, 977 insertions(+), 48 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportedTypeNameTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/JSNameTests.mjs diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index ea8ae9402..580360bb7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -696,42 +696,6 @@ 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 = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportedTypeNameTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportedTypeNameTests.swift new file mode 100644 index 000000000..9d7c9a689 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportedTypeNameTests.swift @@ -0,0 +1,60 @@ +import Foundation +import SwiftParser +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct ExportedTypeNameTests { + private func parse(_ source: String) throws -> ExportedSkeleton { + let generator = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + generator.addSourceFile(Parser.parse(source: source), inputFilePath: "Types.swift") + return try #require(generator.finalize().exported) + } + + @Test + func renamedTypesKeepSwiftIdentities() throws { + let exported = try parse( + """ + @JS func box() -> SwiftBox + @JS func record() -> SwiftRecord + @JS func choice() -> SwiftChoice + @JS func delegate(_ value: SwiftDelegate) + @JS("PublicBox") class SwiftBox { @JS init() {} } + @JS("PublicRecord") struct SwiftRecord { var value: Int } + @JS("PublicChoice") enum SwiftChoice { case first } + @JS("PublicDelegate") protocol SwiftDelegate { func run() } + """ + ) + #expect(exported.classes.first?.resolvedJSName == "PublicBox") + #expect(exported.structs.first?.resolvedJSName == "PublicRecord") + #expect(exported.enums.first?.resolvedJSName == "PublicChoice") + #expect(exported.protocols.first?.resolvedJSName == "PublicDelegate") + #expect(exported.functions[0].returnType == .swiftHeapObject("SwiftBox")) + #expect(exported.functions[1].returnType == .swiftStruct("SwiftRecord")) + #expect(exported.functions[2].returnType == .caseEnum("SwiftChoice")) + #expect(exported.functions[3].parameters.first?.type == .swiftProtocol("SwiftDelegate")) + } + + @Test + func renamedParentsKeepSwiftThunkABI() throws { + let source = """ + @JS(namespace: "API") enum InternalAPI { + @JS class Item { @JS init() {} } + } + """ + let original = try parse(source) + let renamed = try parse( + source.replacingOccurrences(of: "@JS(namespace:", with: "@JS(\"PublicAPI\", namespace:") + ) + let originalThunks = try ExportSwift(progress: .silent, moduleName: "TestModule", skeleton: original).finalize() + let renamedThunks = try ExportSwift(progress: .silent, moduleName: "TestModule", skeleton: renamed).finalize() + #expect(renamedThunks == originalThunks) + #expect(renamed.classes.first?.tsFullPath == "API.PublicAPI.Item") + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameTypes.swift new file mode 100644 index 000000000..40a41bf78 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameTypes.swift @@ -0,0 +1,11 @@ +@JS("PublicBox") final class SwiftBox { + @JS init() + @JS func copy() -> SwiftBox +} + +@JS("PublicChoice") enum SwiftChoice { + case first + case second +} + +@JS func renamedChoice(_ value: SwiftChoice) -> SwiftChoice diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.json new file mode 100644 index 000000000..9e3bc099c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.json @@ -0,0 +1,115 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_SwiftBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "isFinal" : true, + "jsName" : "PublicBox", + "methods" : [ + { + "abiName" : "bjs_SwiftBox_copy", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "copy", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "SwiftBox" + } + } + } + ], + "name" : "SwiftBox", + "properties" : [ + + ], + "swiftCallName" : "SwiftBox" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "first" + }, + { + "associatedValues" : [ + + ], + "name" : "second" + } + ], + "emitStyle" : "const", + "jsName" : "PublicChoice", + "name" : "SwiftChoice", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "SwiftChoice", + "tsFullPath" : "PublicChoice" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_renamedChoice", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "renamedChoice", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "caseEnum" : { + "_0" : "SwiftChoice" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "SwiftChoice" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.swift new file mode 100644 index 000000000..ddcf5b98b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameTypes.swift @@ -0,0 +1,124 @@ +extension SwiftChoice: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> SwiftChoice { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> SwiftChoice { + return SwiftChoice(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .first + case 1: + self = .second + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .first: + return 0 + case .second: + return 1 + } + } +} + +@_expose(wasm, "bjs_renamedChoice") +@_cdecl("bjs_renamedChoice") +public func _bjs_renamedChoice(_ value: Int32) -> Int32 { + #if arch(wasm32) + let value = SwiftChoice.bridgeJSLiftParameter(value) + let ret = renamedChoice(_: value) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftBox_init") +@_cdecl("bjs_SwiftBox_init") +public func _bjs_SwiftBox_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = SwiftBox() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftBox_copy") +@_cdecl("bjs_SwiftBox_copy") +public func _bjs_SwiftBox_copy(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let _self = SwiftBox.bridgeJSLiftParameter(_self) + let ret = _self.copy() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftBox_deinit") +@_cdecl("bjs_SwiftBox_deinit") +public func _bjs_SwiftBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension SwiftBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_SwiftBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_SwiftBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_SwiftBox_wrap") +fileprivate func _bjs_SwiftBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_SwiftBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_SwiftBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SwiftBox_wrap_extern(pointer) +} + +extension SwiftBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SwiftBox.bridgeJSMakeTypeHandle() +} + +extension SwiftChoice: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SwiftChoice.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] = [ + SwiftBox.bridgeJSTypeID, + SwiftChoice.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/JSNameTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.d.ts new file mode 100644 index 000000000..e7a00d877 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.d.ts @@ -0,0 +1,40 @@ +// 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 PublicChoiceValues: { + readonly First: 0; + readonly Second: 1; +}; +export type PublicChoiceTag = typeof PublicChoiceValues[keyof typeof PublicChoiceValues]; + +export type PublicChoiceObject = typeof PublicChoiceValues; + +/// 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 PublicBox extends SwiftHeapObject { + copy(): PublicBox; +} +export type Exports = { + renamedChoice(value: PublicChoiceTag): PublicChoiceTag; + PublicChoice: PublicChoiceObject + PublicBox: { + new(): PublicBox; + }, +} +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/JSNameTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js new file mode 100644 index 000000000..fb061d342 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js @@ -0,0 +1,313 @@ +// 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 PublicChoiceValues = { + First: 0, + Second: 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 >>> 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() {}; + 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_SwiftBox_wrap"] = function(pointer) { + const obj = _exports['PublicBox'].__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 PublicBox extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_SwiftBox_deinit, PublicBox.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_SwiftBox_init(); + return PublicBox.__construct(ret); + } + copy() { + const ret = instance.exports.bjs_SwiftBox_copy(this.pointer); + return PublicBox.__construct(ret); + } + } + const exports = { + renamedChoice: function bjs_renamedChoice(value) { + const ret = instance.exports.bjs_renamedChoice(value); + return ret; + }, + PublicChoice: PublicChoiceValues, + PublicBox, + }; + _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 6ad1711a3..4496316e7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4858,6 +4858,33 @@ fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) } +struct AnyJSNameTransformer: JSNameTransformer, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + func apply(_ value: Int) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_apply(jsObjectValue, valueValue) + return Int.bridgeJSLiftReturn(ret) + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyJSNameTransformer(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSNameTransformer_apply") +fileprivate func _extern_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 +#else +fileprivate func _extern_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_apply(_ jsObject: Int32, _ value: Int32) -> Int32 { + return _extern_apply_extern(jsObject, value) +} + extension Severity: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -6899,6 +6926,19 @@ public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) - #endif } +@_expose(wasm, "bjs_Renaming_JSNameTools_static_apply") +@_cdecl("bjs_Renaming_JSNameTools_static_apply") +public func _bjs_Renaming_JSNameTools_static_apply(_ transformer: Int32, _ value: Int32) -> Int32 { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let transformer = AnyJSNameTransformer.bridgeJSLiftParameter(transformer) + let ret = JSNameTools.apply(_: transformer, _: value) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripUint8Array") @_cdecl("bjs_JSTypedArrayExports_static_roundTripUint8Array") public func _bjs_JSTypedArrayExports_static_roundTripUint8Array(_ v: Int32) -> Int32 { @@ -7897,6 +7937,64 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { return _bjs_struct_lift_Point_extern() } +extension JSNameSnapshot: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSNameSnapshot { + let value = Int.bridgeJSStackPop() + return JSNameSnapshot(value: value) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.value.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_JSNameSnapshot(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSNameSnapshot())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSNameSnapshot") +fileprivate func _bjs_struct_lower_JSNameSnapshot_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_JSNameSnapshot_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_JSNameSnapshot(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSNameSnapshot_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSNameSnapshot") +fileprivate func _bjs_struct_lift_JSNameSnapshot_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_JSNameSnapshot_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_JSNameSnapshot() -> Int32 { + return _bjs_struct_lift_JSNameSnapshot_extern() +} + +@_expose(wasm, "bjs_JSNameSnapshot_init") +@_cdecl("bjs_JSNameSnapshot_init") +public func _bjs_JSNameSnapshot_init(_ value: Int32) -> Void { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let ret = JSNameSnapshot(value: value) + 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() @@ -15552,6 +15650,10 @@ extension Point: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() } +extension JSNameSnapshot: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSNameSnapshot.bridgeJSMakeTypeHandle() +} + extension PointerFields: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PointerFields.bridgeJSMakeTypeHandle() } @@ -20859,6 +20961,7 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { GenericRTPoint.bridgeJSTypeID, GenericRTNamespace.Metadata.bridgeJSTypeID, Point.bridgeJSTypeID, + JSNameSnapshot.bridgeJSTypeID, PointerFields.bridgeJSTypeID, DataPoint.bridgeJSTypeID, PublicPoint.bridgeJSTypeID, diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index e0c5a65b8..0084d9f6a 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -5143,6 +5143,7 @@ } ] }, + "jsName" : "NamedCounter", "methods" : [ { "abiName" : "bjs_JSNameRenamedClass_doubled", @@ -11291,6 +11292,73 @@ { "cases" : [ + ], + "emitStyle" : "const", + "jsName" : "CounterTools", + "name" : "JSNameTools", + "namespace" : [ + "Renaming" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Renaming_JSNameTools_static_apply", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "apply", + "namespace" : [ + "Renaming", + "JSNameTools" + ], + "parameters" : [ + { + "label" : "_", + "name" : "transformer", + "type" : { + "swiftProtocol" : { + "_0" : "JSNameTransformer" + } + } + }, + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "JSNameTools" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "JSNameTools", + "tsFullPath" : "Renaming.CounterTools" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "JSTypedArrayExports", @@ -18915,6 +18983,46 @@ } } ] + }, + { + "jsName" : "CounterTransform", + "methods" : [ + { + "abiName" : "bjs_JSNameTransformer_apply", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "apply", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "JSNameTransformer", + "properties" : [ + + ] } ], "structs" : [ @@ -19378,6 +19486,51 @@ ], "swiftCallName" : "Point" }, + { + "constructor" : { + "abiName" : "bjs_JSNameSnapshot_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "jsName" : "CounterSnapshot", + "methods" : [ + + ], + "name" : "JSNameSnapshot", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "JSNameSnapshot" + }, { "constructor" : { "abiName" : "bjs_PointerFields_init", diff --git a/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift b/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift index 48efcff59..43d5b1fc5 100644 --- a/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift @@ -12,7 +12,7 @@ import JavaScriptKit return "Hello, \(count) people!" } -@JS class JSNameRenamedClass { +@JS("NamedCounter") class JSNameRenamedClass { private var storage: Int @JS init(value: Int) { @@ -32,3 +32,21 @@ import JavaScriptKit return JSNameRenamedClass(value: value) } } + +@JS("CounterSnapshot") struct JSNameSnapshot { + var value: Int + + @JS init(value: Int) { + self.value = value + } +} + +@JS("CounterTransform") protocol JSNameTransformer { + func apply(_ value: Int) -> Int +} + +@JS("CounterTools", namespace: "Renaming") enum JSNameTools { + @JS static func apply(_ transformer: JSNameTransformer, _ value: Int) -> Int { + transformer.apply(value) + } +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/JSNameTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/JSNameTests.mjs new file mode 100644 index 000000000..5b7ddd1fa --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/JSNameTests.mjs @@ -0,0 +1,37 @@ +// @ts-check + +import assert from "node:assert"; + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +export function runJSNameTests(exports) { + assert.equal(exports.renamedEcho("hi"), "echo: hi"); + assert.ok(!("jsNameEcho" in exports)); + assert.equal(exports.greetName("John"), "Hello, John!"); + assert.equal(exports.greetCount(3), "Hello, 3 people!"); + assert.ok(!("JSNameRenamedClass" in exports)); + + /** @type {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').NamedCounter} */ + const counter = new exports.NamedCounter(21); + assert.equal(counter.doubled(), 42); + assert.equal(counter.current, 21); + counter.current = 5; + assert.equal(counter.doubled(), 10); + const made = exports.NamedCounter.makeWithValue(7); + assert.equal(made.current, 7); + assert.ok(made instanceof exports.NamedCounter); + + /** @type {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').CounterSnapshot} */ + const snapshot = exports.CounterSnapshot.init(9); + assert.equal(snapshot.value, 9); + + /** @type {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').CounterTransform} */ + const transformer = { + apply(value) { return value * 2; }, + }; + assert.equal(exports.Renaming.CounterTools.apply(transformer, 6), 12); + + made.release(); + counter.release(); +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index d07f7b3e0..977a1f386 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -19,6 +19,7 @@ import { getImports as getIntegerTypesSupportImports } from './BridgeJSRuntimeTe import { getImports as getAsyncImportImports, runAsyncWorksTests } from './BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs'; import { getImports as getJSTypedArrayImports } from './BridgeJSRuntimeTests/JavaScript/JSTypedArrayTests.mjs'; import { getImports as getIdentityModeTestImports } from './BridgeJSIdentityTests/JavaScript/IdentityModeTests.mjs'; +import { runJSNameTests } from './BridgeJSRuntimeTests/JavaScript/JSNameTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { @@ -317,17 +318,7 @@ 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); + runJSNameTests(exports); const g = new exports.Greeter("John"); assert.equal(g.greet(), "Hello, John!"); From edca6f9f4fe2a7d3b3cf6ea99c86562bef9488c3 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 22 Sep 2026 15:48:17 +0200 Subject: [PATCH 123/140] BridgeJS: Support protocol refinement and constrained imports --- .../Sources/BridgeJSCore/ExportSwift.swift | 52 +- .../BridgeJSCore/ExternalModuleIndex.swift | 15 +- .../Sources/BridgeJSCore/ImportTS.swift | 18 +- .../BridgeJSCore/SwiftToSkeleton.swift | 157 +++++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 36 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 70 ++- .../GenericImportDiagnosticsTests.swift | 113 ++++- .../Inputs/MacroSwift/GenericImports.swift | 22 + .../BridgeJSCodegenTests/Alias.swift | 8 +- .../BridgeJSCodegenTests/DocComments.swift | 18 +- .../BridgeJSCodegenTests/GenericImports.json | 289 ++++++++++- .../BridgeJSCodegenTests/GenericImports.swift | 199 ++++++++ .../BridgeJSCodegenTests/Protocol.swift | 128 ++--- .../ProtocolInClosure.swift | 18 +- .../BridgeJSLinkTests/GenericImports.d.ts | 20 + .../BridgeJSLinkTests/GenericImports.js | 101 ++++ .../Exporting-Swift-Protocols.md | 12 +- .../Importing-JS-Function.md | 12 + .../Generated/BridgeJS.swift | 476 +++++++++++++++--- .../Generated/JavaScript/BridgeJS.json | 366 +++++++++++++- .../ImportGenericAPIs.swift | 54 ++ Tests/prelude.mjs | 9 + 22 files changed, 1933 insertions(+), 260 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 55e3b063c..6b5d3ef76 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -1425,7 +1425,7 @@ struct ProtocolCodegen { for method in proto.methods { let builder = try ImportTS.CallJSEmission( moduleName: moduleName, - abiName: "_extern_\(method.name)", + abiName: method.abiName, effects: method.effects, returnType: method.returnType, context: .exportSwift @@ -1450,7 +1450,7 @@ struct ProtocolCodegen { printer: externDeclPrinter, moduleName: moduleName, abiName: method.abiName, - functionName: "_extern_\(method.name)", + functionName: method.abiName, abiParameters: builder.abiParameterSignatures, returnType: builder.abiReturnType ) @@ -1478,32 +1478,34 @@ struct ProtocolCodegen { externDecls.append(contentsOf: propertyExternDecls) } - let structDeclPrinter = CodeFragmentPrinter() - structDeclPrinter.write("struct \(wrapperName): \(protocolName), _BridgedSwiftProtocolWrapper {") - structDeclPrinter.indent { - structDeclPrinter.write("let jsObject: JSObject") - structDeclPrinter.nextLine() - - for methodDecl in methodDecls { - structDeclPrinter.write(lines: methodDecl.lines) - structDeclPrinter.nextLine() - } - - for decl in propertyDecls { - structDeclPrinter.write(lines: decl.lines) - structDeclPrinter.nextLine() + var decls: [DeclSyntax] = [] + if !methodDecls.isEmpty || !propertyDecls.isEmpty { + let extensionPrinter = CodeFragmentPrinter() + extensionPrinter.write("extension \(protocolName) where Self: _BridgedSwiftProtocolWrapper {") + extensionPrinter.indent { + var first = true + for decl in methodDecls + propertyDecls { + if !first { extensionPrinter.nextLine() } + first = false + extensionPrinter.write(lines: decl.lines) + } } - structDeclPrinter.write( - multilineString: """ - static func bridgeJSLiftParameter(_ value: Int32) -> Self { - return \(wrapperName)(jsObject: JSObject(id: UInt32(bitPattern: value))) - } - """ - ) + extensionPrinter.write("}") + decls.append("\(raw: extensionPrinter.lines.joined(separator: "\n"))") } - structDeclPrinter.write("}") - return ["\(raw: structDeclPrinter.lines.joined(separator: "\n"))"] + externDecls + decls.append( + """ + struct \(raw: wrapperName): \(raw: protocolName), _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return \(raw: wrapperName)(jsObject: JSObject(id: UInt32(bitPattern: value))) + } + } + """ + ) + return decls + externDecls } private func renderProtocolProperty( diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift index 33a27d087..b07fada44 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift @@ -7,6 +7,7 @@ public struct ExternalModuleIndex { public struct ExternalType: Equatable { public let moduleName: String public let bridgeType: BridgeType + public var isGenericBridgeableProtocol = false } public enum LookupResult: Equatable { @@ -31,8 +32,12 @@ public struct ExternalModuleIndex { guard let exported = skeleton.exported else { continue } var moduleEntries = entriesByModule[moduleName] ?? [:] - func register(dotPath: String, bridgeType: BridgeType) { - let externalType = ExternalType(moduleName: moduleName, bridgeType: bridgeType) + func register(dotPath: String, bridgeType: BridgeType, isGenericBridgeableProtocol: Bool = false) { + let externalType = ExternalType( + moduleName: moduleName, + bridgeType: bridgeType, + isGenericBridgeableProtocol: isGenericBridgeableProtocol + ) if moduleEntries[dotPath] == nil { moduleEntries[dotPath] = externalType entriesByDotPath[dotPath, default: []].append(externalType) @@ -61,7 +66,11 @@ public struct ExternalModuleIndex { register(dotPath: enumDef.swiftCallName, bridgeType: bridgeType) } for proto in exported.protocols { - register(dotPath: proto.name, bridgeType: .swiftProtocol(proto.name)) + register( + dotPath: proto.name, + bridgeType: .swiftProtocol(proto.name), + isGenericBridgeableProtocol: proto.isGenericBridgeable == true + ) } for alias in exported.aliases { register( diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 0ec5457fa..378fe2012 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -381,7 +381,7 @@ public struct ImportTS { parameters: [Parameter], returnType: BridgeType, effects: Effects, - genericParameters: [String] = [] + genericParameters: [GenericParameter] = [] ) -> DeclSyntax { let printer = CodeFragmentPrinter() let signature = SwiftSignatureBuilder.buildFunctionSignature( @@ -393,7 +393,13 @@ public struct ImportTS { let genericClause = genericParameters.isEmpty ? "" - : "<" + genericParameters.map { "\($0): BridgedSwiftGenericBridgeable" }.joined(separator: ", ") + : "<" + + genericParameters.map { genericParameter in + let constraints = + ["BridgedSwiftGenericBridgeable"] + + (genericParameter.swiftConstraints ?? genericParameter.constraints) + return "\(genericParameter.name): \(constraints.joined(separator: " & "))" + }.joined(separator: ", ") + ">" printer.write("func \(name.backtickIfNeeded())\(genericClause)\(signature) {") printer.indent { @@ -465,7 +471,7 @@ public struct ImportTS { parameters: function.parameters, returnType: function.returnType, effects: function.effects, - genericParameters: function.genericParameterNames + genericParameters: function.genericParameters ?? [] ) .with(\.leadingTrivia, Self.renderDocumentation(documentation: function.documentation)) ] @@ -496,7 +502,7 @@ public struct ImportTS { parameters: [selfParameter] + method.parameters, returnType: method.returnType, effects: method.effects, - genericParameters: method.genericParameterNames + genericParameters: method.genericParameters ?? [] ) ] } @@ -522,7 +528,7 @@ public struct ImportTS { parameters: method.parameters, returnType: method.returnType, effects: method.effects, - genericParameters: method.genericParameterNames + genericParameters: method.genericParameters ?? [] ) ] } @@ -548,7 +554,7 @@ public struct ImportTS { parameters: constructor.parameters, returnType: .jsObject(nil), effects: effects, - genericParameters: constructor.genericParameterNames + genericParameters: constructor.genericParameters ?? [] ) ] } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 63ce68fe5..0f9f79c06 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -7,6 +7,11 @@ import BridgeJSUtilities import BridgeJSSkeleton #endif +enum GenericConstraintParseResult { + case parsed(GenericParameter) + case failed(message: String) +} + /// Outcome of attempting to resolve a type as a reference to a generic parameter. enum GenericParameterResolution { case resolved(BridgeType) @@ -762,6 +767,13 @@ public final class SwiftToSkeleton { } private func resolveExternal(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { + resolveExternalType(for: type, errors: &errors)?.bridgeType + } + + private func resolveExternalType( + for type: TypeSyntax, + errors: inout [DiagnosticError] + ) -> ExternalModuleIndex.ExternalType? { guard !externalModuleIndex.isEmpty, var components = type.qualifiedComponents @@ -787,7 +799,7 @@ public final class SwiftToSkeleton { switch lookupResult { case .unique(let externalType): usedExternalModules.insert(externalType.moduleName) - return externalType.bridgeType + return externalType case .ambiguous(let candidates): let moduleNames = candidates.map(\.moduleName).sorted().joined(separator: ", ") errors.append( @@ -981,11 +993,94 @@ public final class SwiftToSkeleton { return name.unicodeScalars.dropFirst().allSatisfy { isIdentifierPart($0, isStart: false) } } - fileprivate static func isBridgeableGenericConstraint(_ constraint: String?) -> Bool { + fileprivate static func isBridgeableGenericConstraint(_ constraint: String) -> Bool { constraint == "BridgedSwiftGenericBridgeable" || constraint == "JavaScriptKit.BridgedSwiftGenericBridgeable" } + fileprivate func inheritsGenericBridgeability(for type: TypeSyntax, visited: Set = []) -> Bool { + if Self.isBridgeableGenericConstraint(type.trimmedDescription) { return true } + if let proto = typeDeclResolver.resolve(type)?.as(ProtocolDeclSyntax.self) { + guard !visited.contains(proto.id) else { return false } + return (proto.inheritanceClause?.inheritedTypes ?? []).contains { + inheritsGenericBridgeability(for: $0.type, visited: visited.union([proto.id])) + } + } + var errors: [DiagnosticError] = [] + return resolveExternalType(for: type, errors: &errors)?.isGenericBridgeableProtocol == true + } + + fileprivate func resolveJSProtocolConstraint(for type: TypeSyntax) -> String? { + if let typeDecl = typeDeclResolver.resolve(type) { + guard let protocolDecl = typeDecl.as(ProtocolDeclSyntax.self), + protocolDecl.attributes.hasJSAttribute() + else { + return nil + } + return protocolDecl.name.text + } + var scratchErrors: [DiagnosticError] = [] + if let externalType = resolveExternal(for: type, errors: &scratchErrors), + case .swiftProtocol(let name) = externalType + { + return name + } + return nil + } + + fileprivate func parseGenericParameterConstraints( + _ genericParam: GenericParameterSyntax, + attributeName: String + ) -> GenericConstraintParseResult { + let paramName = genericParam.name.text + guard let inheritedType = genericParam.inheritedType else { + return .failed( + message: + "Generic parameter '\(paramName)' must be constrained to 'BridgedSwiftGenericBridgeable' to be used with \(attributeName)." + ) + } + let elements: [TypeSyntax] + if let composition = inheritedType.as(CompositionTypeSyntax.self) { + elements = composition.elements.map { TypeSyntax($0.type) } + } else { + elements = [inheritedType] + } + var hasBridgeableConstraint = false + var constraints: [String] = [] + var swiftConstraints: [String] = [] + for element in elements { + if SwiftToSkeleton.isBridgeableGenericConstraint(element.trimmedDescription) { + hasBridgeableConstraint = true + continue + } + guard let protocolName = resolveJSProtocolConstraint(for: element) else { + return .failed( + message: + "Generic parameter '\(paramName)' has unsupported constraint '\(element.trimmedDescription)'. " + + "Constraints on generic \(attributeName) declarations must be 'BridgedSwiftGenericBridgeable', " + + "optionally composed with '@JS' protocols (e.g. '\(paramName): BridgedSwiftGenericBridgeable & MyProtocol')." + ) + } + hasBridgeableConstraint = hasBridgeableConstraint || inheritsGenericBridgeability(for: element) + if !constraints.contains(protocolName) { + constraints.append(protocolName) + } + let swiftConstraint = element.is(MemberTypeSyntax.self) ? element.trimmedDescription : protocolName + if !swiftConstraints.contains(swiftConstraint) { + swiftConstraints.append(swiftConstraint) + } + } + guard hasBridgeableConstraint else { + let suggested = (["BridgedSwiftGenericBridgeable"] + swiftConstraints).joined(separator: " & ") + return .failed( + message: + "Generic parameter '\(paramName)' is missing the 'BridgedSwiftGenericBridgeable' constraint. " + + "Write '\(paramName): \(suggested)' to combine it with '@JS' protocol constraints on \(attributeName) declarations." + ) + } + return .parsed(GenericParameter(name: paramName, constraints: constraints, swiftConstraints: swiftConstraints)) + } + } private enum ExportSwiftConstants { @@ -2321,6 +2416,23 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let protocolUniqueKey = makeKey(name: name, namespace: effectiveNamespace) + var inheritedJSProtocols: [String] = [] + for inherited in node.inheritanceClause?.inheritedTypes ?? [] { + guard let baseName = parent.resolveJSProtocolConstraint(for: inherited.type) else { continue } + guard parent.typeDeclResolver.resolve(inherited.type)?.is(ProtocolDeclSyntax.self) == true else { + diagnose( + node: inherited, + message: "Refining @JS protocol '\(baseName)' from another module is not supported yet.", + hint: + "Declare the inherited requirements on '\(name)' directly, or move the base protocol into this module." + ) + return .skipChildren + } + if !inheritedJSProtocols.contains(baseName) { + inheritedJSProtocols.append(baseName) + } + } + exportedProtocolByName[protocolUniqueKey] = ExportedProtocol( name: name, jsName: jsName, @@ -2355,7 +2467,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { properties: exportedProtocolByName[protocolUniqueKey]?.properties ?? [], namespace: effectiveNamespace, jsNamespace: namespaceResult.jsNamespace, - documentation: extractDocumentation(from: node) + documentation: extractDocumentation(from: node), + inheritedJSProtocols: inheritedJSProtocols.isEmpty ? nil : inheritedJSProtocols, + isGenericBridgeable: (node.inheritanceClause?.inheritedTypes ?? []).contains { + parent.inheritsGenericBridgeability(for: $0.type) + } ? true : nil ) exportedProtocolByName[protocolUniqueKey] = exportedProtocol @@ -3453,27 +3569,21 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { /// /// Returns `nil` when a diagnostic was emitted; an empty array when the /// declaration is not generic. - private func parseGenericParameterNames( + private func parseGenericParameters( genericParameterClause: GenericParameterClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, node: Syntax - ) -> [String]? { - var genericParameterNames: [String] = [] + ) -> [GenericParameter]? { + var genericParameters: [GenericParameter] = [] 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." - ) - ) + switch parent.parseGenericParameterConstraints(genericParam, attributeName: "@JSFunction") { + case .failed(let message): + errors.append(DiagnosticError(node: Syntax(genericParam), message: message)) return nil + case .parsed(let genericParameter): + genericParameters.append(genericParameter) } - genericParameterNames.append(paramName) } } if genericWhereClause != nil { @@ -3485,7 +3595,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { ) return nil } - return genericParameterNames + return genericParameters } private func parseConstructor( @@ -3502,7 +3612,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } guard - let genericParameterNames = parseGenericParameterNames( + let genericParameters = parseGenericParameters( genericParameterClause: initializer.genericParameterClause, genericWhereClause: initializer.genericWhereClause, node: Syntax(initializer) @@ -3510,6 +3620,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { else { return nil } + let genericParameterNames = genericParameters.map(\.name) if !genericParameterNames.isEmpty && effects.isAsync { errors.append( DiagnosticError( @@ -3542,7 +3653,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return ImportedConstructorSkeleton( parameters: parameters, accessLevel: accessLevel, - genericParameters: genericParameterNames.isEmpty ? nil : genericParameterNames + genericParameters: genericParameters.isEmpty ? nil : genericParameters ) } @@ -3561,7 +3672,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } guard - let genericParameterNames = parseGenericParameterNames( + let genericParameters = parseGenericParameters( genericParameterClause: node.genericParameterClause, genericWhereClause: node.genericWhereClause, node: Syntax(node) @@ -3570,6 +3681,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } + let genericParameterNames = genericParameters.map(\.name) + let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) let extractedJSName = extractJSName(from: jsFunction) let from = extractJSImportFrom(from: jsFunction) @@ -3632,7 +3745,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { effects: effects, documentation: nil, accessLevel: accessLevel, - genericParameters: genericParameterNames.isEmpty ? nil : genericParameterNames + genericParameters: genericParameters.isEmpty ? nil : genericParameters ) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 5d41869f8..40b1c13c3 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1021,7 +1021,10 @@ 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.resolvedJSName) {") + let extendsClause = + inheritedProtocolTSNames(of: proto, in: exportedSkeletons) + .map { " extends \($0.joined(separator: ", "))" } ?? "" + printer.write("export interface \(proto.resolvedJSName)\(extendsClause) {") printer.indent { for method in proto.methods { printer.write( @@ -1521,7 +1524,7 @@ public struct BridgeJSLink { // Add methods for method in type.methods { let methodName = method.resolvedJSName - let genericClause = renderGenericClause(method.genericParameterNames) + let genericClause = renderGenericClause(method.genericParameters ?? []) let methodSignature = "\(renderTSPropertyName(methodName))\(genericClause)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" printer.write(methodSignature) @@ -1681,6 +1684,18 @@ public struct BridgeJSLink { } } + private func inheritedProtocolTSNames(of proto: ExportedProtocol, in skeletons: [ExportedSkeleton]) -> [String]? { + guard let inherited = proto.inheritedJSProtocols, !inherited.isEmpty else { return nil } + return inherited.map { baseName in + for skeleton in skeletons { + if let base = skeleton.protocols.first(where: { $0.name == baseName }) { + return base.resolvedJSName + } + } + return baseName + } + } + /// Resolves public TypeScript names without changing the skeleton's Swift type identities. private func resolveTypeScriptType(_ type: BridgeType) -> String { return Self.resolveTypeScriptType(type, exportedSkeletons: skeletons.compactMap(\.exported)) @@ -1771,8 +1786,15 @@ public struct BridgeJSLink { return "(\(parameterSignatures.joined(separator: ", "))): \(returnTypeWithEffect)" } - private func renderGenericClause(_ genericParameterNames: [String]) -> String { - genericParameterNames.isEmpty ? "" : "<\(genericParameterNames.joined(separator: ", "))>" + private func renderGenericClause(_ genericParameters: [GenericParameter]) -> String { + guard !genericParameters.isEmpty else { return "" } + let renderedParameters = genericParameters.map { genericParameter in + let constraints = genericParameter.constraints.map { resolveTypeScriptType(.swiftProtocol($0)) } + return constraints.isEmpty + ? genericParameter.name + : "\(genericParameter.name) extends \(constraints.joined(separator: " & "))" + } + return "<\(renderedParameters.joined(separator: ", "))>" } private func renderTSPropertyName(_ name: String) -> String { @@ -3767,7 +3789,7 @@ extension BridgeJSLink { try thunkBuilder.call(calleeExpr: calleeExpr) let funcLines = thunkBuilder.renderFunction(name: function.abiName(context: nil)) if function.from == nil { - let genericClause = renderGenericClause(genericParameters) + let genericClause = renderGenericClause(function.genericParameters ?? []) importObjectBuilder.appendDts( [ "\(renderTSPropertyName(jsName))\(genericClause)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" @@ -3861,14 +3883,14 @@ extension BridgeJSLink { dtsPrinter.indent { if let constructor = type.constructor { let returnType = BridgeType.jsObject(type.name) - let genericClause = renderGenericClause(constructor.genericParameterNames) + let genericClause = renderGenericClause(constructor.genericParameters ?? []) dtsPrinter.write( "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 genericClause = renderGenericClause(method.genericParameters ?? []) let signature = "\(renderTSPropertyName(methodName))\(genericClause)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" dtsPrinter.write(signature) diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index ce85176cc..8da9f2e4e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -382,6 +382,14 @@ extension ExportedSkeleton { guard let bridgeType = enumDef.genericBridgeType else { continue } entries.append(GenericBridgeableTypeEntry(swiftName: enumDef.swiftCallName, bridgeType: bridgeType)) } + for proto in protocols where proto.isGenericBridgeable == true { + entries.append( + GenericBridgeableTypeEntry( + swiftName: "Any\(proto.name)", + bridgeType: .swiftProtocol(proto.name) + ) + ) + } return entries } } @@ -546,6 +554,44 @@ public struct Parameter: Codable, Equatable, Sendable { } } +public struct GenericParameter: Codable, Equatable, Hashable, Sendable { + public let name: String + public let constraints: [String] + public let swiftConstraints: [String]? + + public init(name: String, constraints: [String] = [], swiftConstraints: [String]? = nil) { + self.name = name + self.constraints = constraints + self.swiftConstraints = swiftConstraints == constraints ? nil : swiftConstraints + } + + private enum CodingKeys: String, CodingKey { + case name, constraints, swiftConstraints + } + + public init(from decoder: any Decoder) throws { + if let single = try? decoder.singleValueContainer(), let name = try? single.decode(String.self) { + self.name = name + self.constraints = [] + self.swiftConstraints = nil + return + } + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.constraints = try container.decodeIfPresent([String].self, forKey: .constraints) ?? [] + self.swiftConstraints = try container.decodeIfPresent([String].self, forKey: .swiftConstraints) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + if !constraints.isEmpty { + try container.encode(constraints, forKey: .constraints) + } + try container.encodeIfPresent(swiftConstraints, forKey: .swiftConstraints) + } +} + // MARK: - BridgeSkeleton Visitor public protocol BridgeSkeletonVisitor { @@ -973,6 +1019,8 @@ public struct ExportedProtocol: Codable, Equatable, NamespacedExportedType { public let namespace: [String]? public let jsNamespace: [String]? public var documentation: String? + public var inheritedJSProtocols: [String]? + public var isGenericBridgeable: Bool? public init( name: String, @@ -981,7 +1029,9 @@ public struct ExportedProtocol: Codable, Equatable, NamespacedExportedType { properties: [ExportedProtocolProperty] = [], namespace: [String]? = nil, jsNamespace: [String]? = nil, - documentation: String? = nil + documentation: String? = nil, + inheritedJSProtocols: [String]? = nil, + isGenericBridgeable: Bool? = nil ) { self.name = name self.jsName = jsName @@ -990,6 +1040,8 @@ public struct ExportedProtocol: Codable, Equatable, NamespacedExportedType { self.namespace = namespace self.jsNamespace = jsNamespace self.documentation = documentation + self.inheritedJSProtocols = inheritedJSProtocols + self.isGenericBridgeable = isGenericBridgeable } } @@ -1397,8 +1449,8 @@ 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 let genericParameters: [GenericParameter]? + public var genericParameterNames: [String] { (genericParameters ?? []).map(\.name) } public var isGeneric: Bool { !genericParameterNames.isEmpty } public var resolvedJSName: String { jsName ?? name } @@ -1412,7 +1464,7 @@ public struct ImportedFunctionSkeleton: Codable { effects: Effects = Effects(isAsync: false, isThrows: true), documentation: String? = nil, accessLevel: BridgeJSAccessLevel = .internal, - genericParameters: [String]? = nil + genericParameters: [GenericParameter]? = nil ) { self.name = name self.jsName = jsName @@ -1439,7 +1491,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) + self.genericParameters = try container.decodeIfPresent([GenericParameter].self, forKey: .genericParameters) } public func abiName(context: ImportedTypeSkeleton?) -> String { @@ -1460,14 +1512,14 @@ 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 let genericParameters: [GenericParameter]? + public var genericParameterNames: [String] { (genericParameters ?? []).map(\.name) } public var isGeneric: Bool { !genericParameterNames.isEmpty } public init( parameters: [Parameter], accessLevel: BridgeJSAccessLevel = .internal, - genericParameters: [String]? = nil + genericParameters: [GenericParameter]? = nil ) { self.parameters = parameters self.accessLevel = accessLevel @@ -1482,7 +1534,7 @@ public struct ImportedConstructorSkeleton: Codable { 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) + self.genericParameters = try container.decodeIfPresent([GenericParameter].self, forKey: .genericParameters) } public func abiName(context: ImportedTypeSkeleton) -> String { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift index 4a421b73b..f2ff5dc81 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift @@ -1,9 +1,116 @@ +import Foundation import Testing +@testable import BridgeJSCore +@testable import BridgeJSLink @testable import BridgeJSSkeleton @Suite struct GenericImportDiagnosticsTests { + @Test(arguments: [ + ("protocol P {}", "BridgedSwiftGenericBridgeable & P", "unsupported constraint 'P'"), + ("@JS protocol P {}", "P", "missing the 'BridgedSwiftGenericBridgeable' constraint"), + ]) + func invalidProtocolConstraint(declaration: String, constraint: String, diagnostic: String) { + expectDiagnostic( + source: "\(declaration)\n@JSFunction func f(_ value: T) throws(JSException) -> T", + contains: diagnostic + ) + } + + @Test func qualifiedExternalProtocolConstraint() throws { + let dependency = try makeSkeleton( + "@JS public protocol Node: BridgedSwiftGenericBridgeable {}", + moduleName: "GraphKit" + ) + let decoded = try JSONDecoder().decode(BridgeJSSkeleton.self, from: JSONEncoder().encode(dependency)) + let skeleton = try makeSkeleton( + """ + import GraphKit + protocol Node {} + @JSFunction func f(_ value: T) throws(JSException) -> T + """, + dependencies: [(moduleName: "GraphKit", skeleton: decoded)] + ) + let roundTrip = try JSONDecoder().decode(BridgeJSSkeleton.self, from: JSONEncoder().encode(skeleton)) + let imported = try #require(roundTrip.imported) + #expect( + imported.children.flatMap(\.functions).first?.genericParameters == [ + GenericParameter(name: "T", constraints: ["Node"], swiftConstraints: ["GraphKit.Node"]) + ] + ) + let glue = try #require( + try ImportTS(progress: .silent, moduleName: skeleton.moduleName, skeleton: imported).finalize() + ) + #expect(glue.contains("T: BridgedSwiftGenericBridgeable & GraphKit.Node")) + #expect(roundTrip.usedExternalModules == ["GraphKit"]) + } + + @Test func refinedProtocolRequirementsAndAdapter() throws { + let skeleton = try makeSkeleton( + """ + @JS(namespace: "API") protocol Base: BridgedSwiftGenericBridgeable { + func read() -> Int + var value: Int { get set } + } + @JS protocol Middle: Base {} + @JS("PublicNode", namespace: "API") protocol Node: Middle { + var value: Int { get } + } + @JSFunction func f(_ value: T) throws(JSException) -> T + """ + ) + let exported = try #require(skeleton.exported) + let node = try #require(exported.protocols.first { $0.name == "Node" }) + #expect(node.methods.isEmpty) + #expect(node.properties.map(\.name) == ["value"]) + #expect(node.inheritedJSProtocols == ["Middle"]) + #expect(node.jsName == "PublicNode") + #expect( + exported.genericBridgeableTypeEntries.contains { + $0.swiftName == "AnyNode" && $0.bridgeType == .swiftProtocol("Node") + } + ) + let glue = try #require( + try ExportSwift(progress: .silent, moduleName: skeleton.moduleName, skeleton: exported).finalize() + ) + #expect(glue.contains("extension Base where Self: _BridgedSwiftProtocolWrapper {")) + #expect(glue.contains("extension Node where Self: _BridgedSwiftProtocolWrapper {")) + #expect(!glue.contains("extension Middle where Self")) + #expect(glue.contains("struct AnyNode: Node, _BridgedSwiftProtocolWrapper {")) + #expect(glue.contains("name: \"bjs_Base_read\"")) + #expect(!glue.contains("bjs_Node_read")) + let linked = try BridgeJSLink(skeletons: [skeleton]).link() + #expect(linked.outputDts.contains("f")) + #expect(linked.outputDts.contains("export interface PublicNode extends Middle {")) + #expect(linked.outputDts.contains("export interface Middle extends Base {")) + } + + @Test func externalProtocolRefinementIsRejected() throws { + let dependency = try makeSkeleton("@JS public protocol Base {}", moduleName: "GraphKit") + do { + _ = try makeSkeleton( + "import GraphKit\n@JS protocol Child: GraphKit.Base {}", + dependencies: [(moduleName: "GraphKit", skeleton: dependency)] + ) + Issue.record("Expected external refinement diagnostic") + } catch let error as BridgeJSCoreDiagnosticError { + #expect( + error.diagnostics.contains { + $0.diagnostic.message.contains("from another module is not supported") + } + ) + } + } + + @Test func legacyGenericParameterDecoding() throws { + let constructor = try JSONDecoder().decode( + ImportedConstructorSkeleton.self, + from: Data(#"{"parameters":[],"genericParameters":["T"]}"#.utf8) + ) + #expect(constructor.genericParameters == [GenericParameter(name: "T")]) + } + @Test func genericParameterRequiresBridgeableConstraint() { expectDiagnostic( @@ -48,7 +155,7 @@ import Testing 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"]) + #expect(method.genericParameters == [GenericParameter(name: "T")]) } @Test @@ -65,7 +172,7 @@ import Testing 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.genericParameters == [GenericParameter(name: "T")]) #expect(constructor.parameters.map(\.type) == [.generic("T")]) } @@ -205,6 +312,6 @@ import Testing 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"]) + #expect(function.genericParameters == [GenericParameter(name: "T")]) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift index 5fd3d0226..546207cd3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift @@ -72,3 +72,25 @@ struct GenericPoint { @JSFunction func identity(_ value: T) throws(JSException) -> T @JSFunction static func box(_ value: T) throws(JSException) -> T } + +@JS protocol GenericReadable: BridgedSwiftGenericBridgeable { + func read() -> Int +} + +@JS protocol GenericWritable { + var value: Int { get set } +} + +@JS protocol GenericNode: GenericReadable, GenericWritable {} + +@JSFunction func constrainedRoundTrip(_ value: T) throws(JSException) -> T + +@JSFunction func constrainedComposition( + _ value: T +) throws(JSException) -> T + +@JSClass struct ConstrainedConsumer { + @JSFunction init(_ value: T) throws(JSException) + @JSFunction func accept(_ value: T) throws(JSException) -> T + @JSFunction static func identity(_ 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 af8a8a453..2529f22d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -1,6 +1,4 @@ -struct AnyHasOptionalUserId: HasOptionalUserId, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension HasOptionalUserId where Self: _BridgedSwiftProtocolWrapper { var userId: Optional { get { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -8,6 +6,10 @@ struct AnyHasOptionalUserId: HasOptionalUserId, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } } +} + +struct AnyHasOptionalUserId: HasOptionalUserId, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyHasOptionalUserId(jsObject: JSObject(id: UInt32(bitPattern: value))) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift index b9c65e28f..05c575b73 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -1,10 +1,8 @@ -struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension Listener where Self: _BridgedSwiftProtocolWrapper { func onEvent(id: Int) -> Void { let idValue = id.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onEvent(jsObjectValue, idValue) + bjs_Listener_onEvent(jsObjectValue, idValue) } var name: String { @@ -14,6 +12,10 @@ struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { return String.bridgeJSLiftReturn(ret) } } +} + +struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyListener(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -22,14 +24,14 @@ struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Listener_onEvent") -fileprivate func _extern_onEvent_extern(_ jsObject: Int32, _ id: Int32) -> Void +fileprivate func bjs_Listener_onEvent_extern(_ jsObject: Int32, _ id: Int32) -> Void #else -fileprivate func _extern_onEvent_extern(_ jsObject: Int32, _ id: Int32) -> Void { +fileprivate func bjs_Listener_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) +@inline(never) fileprivate func bjs_Listener_onEvent(_ jsObject: Int32, _ id: Int32) -> Void { + return bjs_Listener_onEvent_extern(jsObject, id) } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json index c7f3e98ae..9f9f7a834 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json @@ -172,7 +172,69 @@ ], "protocols" : [ + { + "isGenericBridgeable" : true, + "methods" : [ + { + "abiName" : "bjs_GenericReadable_read", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "read", + "parameters" : [ + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "GenericReadable", + "properties" : [ + + ] + }, + { + "methods" : [ + + ], + "name" : "GenericWritable", + "properties" : [ + { + "isReadonly" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "GenericReadable", + "GenericWritable" + ], + "isGenericBridgeable" : true, + "methods" : [ + + ], + "name" : "GenericNode", + "properties" : [ + + ] + } ], "structs" : [ { @@ -224,7 +286,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "genericRoundTrip", "parameters" : [ @@ -251,7 +315,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "genericParse", "parameters" : [ @@ -278,8 +344,12 @@ "isThrows" : true }, "genericParameters" : [ - "T", - "U" + { + "name" : "T" + }, + { + "name" : "U" + } ], "name" : "importGenericCombine", "parameters" : [ @@ -314,8 +384,12 @@ "isThrows" : true }, "genericParameters" : [ - "T", - "t" + { + "name" : "T" + }, + { + "name" : "t" + } ], "name" : "importGenericCaseDistinct", "parameters" : [ @@ -350,7 +424,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "importGenericArray", "parameters" : [ @@ -385,7 +461,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "importGenericOptional", "parameters" : [ @@ -422,7 +500,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "importGenericDictionary", "parameters" : [ @@ -457,7 +537,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "importGenericAfterOptionalArray", "parameters" : [ @@ -495,6 +577,70 @@ "_0" : "T" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericNode" + ], + "name" : "T" + } + ], + "name" : "constrainedRoundTrip", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericWritable" + ], + "name" : "T" + } + ], + "name" : "constrainedComposition", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } } ], "types" : [ @@ -503,8 +649,12 @@ "constructor" : { "accessLevel" : "internal", "genericParameters" : [ - "T", - "U" + { + "name" : "T" + }, + { + "name" : "U" + } ], "parameters" : [ { @@ -552,7 +702,9 @@ "constructor" : { "accessLevel" : "internal", "genericParameters" : [ - "T" + { + "name" : "T" + } ], "parameters" : [ { @@ -577,7 +729,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "accept", "parameters" : [ @@ -604,7 +758,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "identity", "parameters" : [ @@ -637,7 +793,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "box", "parameters" : [ @@ -657,6 +815,105 @@ } } ] + }, + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "genericParameters" : [ + { + "constraints" : [ + "GenericNode" + ], + "name" : "T" + } + ], + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ] + }, + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericNode" + ], + "name" : "T" + } + ], + "name" : "accept", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "name" : "ConstrainedConsumer", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericNode" + ], + "name" : "T" + } + ], + "name" : "identity", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ] } ] } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift index cf07236fc..ecb1512cf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -1,3 +1,86 @@ +extension GenericReadable where Self: _BridgedSwiftProtocolWrapper { + func read() -> Int { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_GenericReadable_read(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } +} + +struct AnyGenericReadable: GenericReadable, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyGenericReadable(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericReadable_read") +fileprivate func bjs_GenericReadable_read_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_GenericReadable_read_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericReadable_read(_ jsObject: Int32) -> Int32 { + return bjs_GenericReadable_read_extern(jsObject) +} + +extension GenericWritable where Self: _BridgedSwiftProtocolWrapper { + var value: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_GenericWritable_value_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + set { + let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_GenericWritable_value_set(jsObjectValue, newValueValue) + } + } +} + +struct AnyGenericWritable: GenericWritable, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyGenericWritable(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericWritable_value_get") +fileprivate func bjs_GenericWritable_value_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_GenericWritable_value_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericWritable_value_get(_ jsObject: Int32) -> Int32 { + return bjs_GenericWritable_value_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericWritable_value_set") +fileprivate func bjs_GenericWritable_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_GenericWritable_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericWritable_value_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_GenericWritable_value_set_extern(jsObject, newValue) +} + +struct AnyGenericNode: GenericNode, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyGenericNode(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + extension GenericColor: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -207,6 +290,14 @@ extension GenericTagged: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericTagged.bridgeJSMakeTypeHandle() } +extension AnyGenericReadable: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyGenericReadable.bridgeJSMakeTypeHandle() +} + +extension AnyGenericNode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyGenericNode.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_genericRoundTrip") fileprivate func bjs_genericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void @@ -379,6 +470,48 @@ func _$importGenericAfterOptionalArray(_ value return T.bridgeJSStackPop() } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_constrainedRoundTrip") +fileprivate func bjs_constrainedRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_constrainedRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_constrainedRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_constrainedRoundTrip_extern(_generic0TypeId) +} + +func _$constrainedRoundTrip(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_constrainedRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_constrainedComposition") +fileprivate func bjs_constrainedComposition_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_constrainedComposition_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_constrainedComposition(_ _generic0TypeId: Int32) -> Void { + return bjs_constrainedComposition_extern(_generic0TypeId) +} + +func _$constrainedComposition(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_constrainedComposition(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 @@ -490,6 +623,70 @@ func _$GenericConsumer_identity(_ self: JSObje return T.bridgeJSStackPop() } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ConstrainedConsumer_init") +fileprivate func bjs_ConstrainedConsumer_init_extern(_ _generic0TypeId: Int32) -> Int32 +#else +fileprivate func bjs_ConstrainedConsumer_init_extern(_ _generic0TypeId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ConstrainedConsumer_init(_ _generic0TypeId: Int32) -> Int32 { + return bjs_ConstrainedConsumer_init_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ConstrainedConsumer_identity_static") +fileprivate func bjs_ConstrainedConsumer_identity_static_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_ConstrainedConsumer_identity_static_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ConstrainedConsumer_identity_static(_ _generic0TypeId: Int32) -> Void { + return bjs_ConstrainedConsumer_identity_static_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ConstrainedConsumer_accept") +fileprivate func bjs_ConstrainedConsumer_accept_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_ConstrainedConsumer_accept_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ConstrainedConsumer_accept(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_ConstrainedConsumer_accept_extern(self, _generic0TypeId) +} + +func _$ConstrainedConsumer_init(_ value: T) throws(JSException) -> JSObject { + value.bridgeJSStackPush() + let ret = bjs_ConstrainedConsumer_init(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ConstrainedConsumer_identity(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_ConstrainedConsumer_identity_static(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +func _$ConstrainedConsumer_accept(_ self: JSObject, _ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + let selfValue = self.bridgeJSLowerParameter() + bjs_ConstrainedConsumer_accept(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) @@ -502,6 +699,8 @@ public func _bjs_TestModule_register_type_handles() { GenericColor.bridgeJSTypeID, GenericMode.bridgeJSTypeID, GenericTagged.bridgeJSTypeID, + AnyGenericReadable.bridgeJSTypeID, + AnyGenericNode.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index ef9beefac..ec3d2f65a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1,22 +1,20 @@ -struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { func onSomethingHappened() -> Void { let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onSomethingHappened(jsObjectValue) + bjs_MyViewControllerDelegate_onSomethingHappened(jsObjectValue) } func onValueChanged(_ value: String) -> Void { value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onValueChanged(jsObjectValue, valueBytes, valueLength) + bjs_MyViewControllerDelegate_onValueChanged(jsObjectValue, valueBytes, valueLength) } } func onCountUpdated(count: Int) -> Bool { let countValue = count.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_onCountUpdated(jsObjectValue, countValue) + let ret = bjs_MyViewControllerDelegate_onCountUpdated(jsObjectValue, countValue) return Bool.bridgeJSLiftReturn(ret) } @@ -24,56 +22,56 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in suffix.bridgeJSWithLoweredParameter { (suffixBytes, suffixLength) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onLabelUpdated(jsObjectValue, prefixBytes, prefixLength, suffixBytes, suffixLength) + bjs_MyViewControllerDelegate_onLabelUpdated(jsObjectValue, prefixBytes, prefixLength, suffixBytes, suffixLength) } } } func isCountEven() -> Bool { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_isCountEven(jsObjectValue) + let ret = bjs_MyViewControllerDelegate_isCountEven(jsObjectValue) return Bool.bridgeJSLiftReturn(ret) } func onHelperUpdated(_ helper: Helper) -> Void { let helperPointer = helper.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onHelperUpdated(jsObjectValue, helperPointer) + bjs_MyViewControllerDelegate_onHelperUpdated(jsObjectValue, helperPointer) } func createHelper() -> Helper { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createHelper(jsObjectValue) + let ret = bjs_MyViewControllerDelegate_createHelper(jsObjectValue) return Helper.bridgeJSLiftReturn(ret) } func onOptionalHelperUpdated(_ helper: Optional) -> Void { let (helperIsSome, helperPointer) = helper.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_onOptionalHelperUpdated(jsObjectValue, helperIsSome, helperPointer) + bjs_MyViewControllerDelegate_onOptionalHelperUpdated(jsObjectValue, helperIsSome, helperPointer) } func createOptionalHelper() -> Optional { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createOptionalHelper(jsObjectValue) + let ret = bjs_MyViewControllerDelegate_createOptionalHelper(jsObjectValue) return Optional.bridgeJSLiftReturn(ret) } func createEnum() -> ExampleEnum { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createEnum(jsObjectValue) + let ret = bjs_MyViewControllerDelegate_createEnum(jsObjectValue) return ExampleEnum.bridgeJSLiftReturn(ret) } func handleResult(_ result: Result) -> Void { let resultCaseId = result.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_handleResult(jsObjectValue, resultCaseId) + bjs_MyViewControllerDelegate_handleResult(jsObjectValue, resultCaseId) } func getResult() -> Result { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getResult(jsObjectValue) + let ret = bjs_MyViewControllerDelegate_getResult(jsObjectValue) return Result.bridgeJSLiftReturn(ret) } @@ -217,6 +215,10 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto bjs_MyViewControllerDelegate_priorityOptional_set(jsObjectValue, newValueIsSome, newValueValue) } } +} + +struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyMyViewControllerDelegate(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -225,146 +227,146 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onSomethingHappened") -fileprivate func _extern_onSomethingHappened_extern(_ jsObject: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_onSomethingHappened_extern(_ jsObject: Int32) -> Void #else -fileprivate func _extern_onSomethingHappened_extern(_ jsObject: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onSomethingHappened_extern(_ jsObject: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onSomethingHappened(_ jsObject: Int32) -> Void { - return _extern_onSomethingHappened_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onSomethingHappened(_ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_onSomethingHappened_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onValueChanged") -fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void #else -fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onValueChanged(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return _extern_onValueChanged_extern(jsObject, valueBytes, valueLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onValueChanged(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return bjs_MyViewControllerDelegate_onValueChanged_extern(jsObject, valueBytes, valueLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onCountUpdated") -fileprivate func _extern_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 #else -fileprivate func _extern_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 { +fileprivate func bjs_MyViewControllerDelegate_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onCountUpdated(_ jsObject: Int32, _ count: Int32) -> Int32 { - return _extern_onCountUpdated_extern(jsObject, count) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onCountUpdated(_ jsObject: Int32, _ count: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_onCountUpdated_extern(jsObject, count) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onLabelUpdated") -fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void #else -fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onLabelUpdated(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { - return _extern_onLabelUpdated_extern(jsObject, prefixBytes, prefixLength, suffixBytes, suffixLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { + return bjs_MyViewControllerDelegate_onLabelUpdated_extern(jsObject, prefixBytes, prefixLength, suffixBytes, suffixLength) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_isCountEven") -fileprivate func _extern_isCountEven_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_isCountEven_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_isCountEven_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_MyViewControllerDelegate_isCountEven_extern(_ jsObject: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_isCountEven(_ jsObject: Int32) -> Int32 { - return _extern_isCountEven_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_isCountEven(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_isCountEven_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onHelperUpdated") -fileprivate func _extern_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void +fileprivate func bjs_MyViewControllerDelegate_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void #else -fileprivate func _extern_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onHelperUpdated(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { - return _extern_onHelperUpdated_extern(jsObject, helper) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onHelperUpdated(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { + return bjs_MyViewControllerDelegate_onHelperUpdated_extern(jsObject, helper) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createHelper") -fileprivate func _extern_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_MyViewControllerDelegate_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer #else -fileprivate func _extern_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func bjs_MyViewControllerDelegate_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_createHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return _extern_createHelper_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_createHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_MyViewControllerDelegate_createHelper_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onOptionalHelperUpdated") -fileprivate func _extern_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void +fileprivate func bjs_MyViewControllerDelegate_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void #else -fileprivate func _extern_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_onOptionalHelperUpdated(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { - return _extern_onOptionalHelperUpdated_extern(jsObject, helperIsSome, helperPointer) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onOptionalHelperUpdated(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { + return bjs_MyViewControllerDelegate_onOptionalHelperUpdated_extern(jsObject, helperIsSome, helperPointer) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createOptionalHelper") -fileprivate func _extern_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_MyViewControllerDelegate_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer #else -fileprivate func _extern_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func bjs_MyViewControllerDelegate_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_createOptionalHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return _extern_createOptionalHelper_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_createOptionalHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_MyViewControllerDelegate_createOptionalHelper_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createEnum") -fileprivate func _extern_createEnum_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_createEnum_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_createEnum_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_MyViewControllerDelegate_createEnum_extern(_ jsObject: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_createEnum(_ jsObject: Int32) -> Int32 { - return _extern_createEnum_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_createEnum(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_createEnum_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_handleResult") -fileprivate func _extern_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void #else -fileprivate func _extern_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_handleResult(_ jsObject: Int32, _ result: Int32) -> Void { - return _extern_handleResult_extern(jsObject, result) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_handleResult(_ jsObject: Int32, _ result: Int32) -> Void { + return bjs_MyViewControllerDelegate_handleResult_extern(jsObject, result) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_getResult") -fileprivate func _extern_getResult_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_getResult_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_getResult_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_MyViewControllerDelegate_getResult_extern(_ jsObject: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_getResult(_ jsObject: Int32) -> Int32 { - return _extern_getResult_extern(jsObject) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_getResult(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_getResult_extern(jsObject) } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift index f02cd4019..bc63b1f65 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift @@ -257,14 +257,16 @@ public func _invoke_swift_closure_TestModule_10TestModuley_10RenderableP(_ boxPt #endif } -struct AnyRenderable: Renderable, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension Renderable where Self: _BridgedSwiftProtocolWrapper { func render() -> String { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_render(jsObjectValue) + let ret = bjs_Renderable_render(jsObjectValue) return String.bridgeJSLiftReturn(ret) } +} + +struct AnyRenderable: Renderable, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyRenderable(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -273,14 +275,14 @@ struct AnyRenderable: Renderable, _BridgedSwiftProtocolWrapper { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Renderable_render") -fileprivate func _extern_render_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_Renderable_render_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_render_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_Renderable_render_extern(_ jsObject: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_render(_ jsObject: Int32) -> Int32 { - return _extern_render_extern(jsObject) +@inline(never) fileprivate func bjs_Renderable_render(_ jsObject: Int32) -> Int32 { + return bjs_Renderable_render_extern(jsObject) } @_expose(wasm, "bjs_processRenderable") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts index 026713ce3..8ff2aad15 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts @@ -4,6 +4,17 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export interface GenericReadable { + read(): number; +} + +export interface GenericWritable { + value: number; +} + +export interface GenericNode extends GenericReadable, GenericWritable { +} + export const GenericColorValues: { readonly Red: 0; readonly Green: 1; @@ -53,6 +64,9 @@ export interface GenericConsumer { accept(value: T): void; identity(value: T): T; } +export interface ConstrainedConsumer { + accept(value: T): T; +} export type Exports = { GenericColor: GenericColorObject GenericMode: GenericModeObject @@ -70,6 +84,8 @@ export type Imports = { importGenericOptional(value: T | null): T | null; importGenericDictionary(values: Record): Record; importGenericAfterOptionalArray(values: number[] | null, value: T): T; + constrainedRoundTrip(value: T): T; + constrainedComposition(value: T): T; GenericPairFactory: { new(tag: string, first: T, second: U): GenericPairFactory; } @@ -77,6 +93,10 @@ export type Imports = { new(value: T): GenericConsumer; box(value: T): T; } + ConstrainedConsumer: { + new(value: T): ConstrainedConsumer; + identity(value: T): T; + } } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index d8b1fdf15..529f1772e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -428,6 +428,30 @@ export async function createInstantiator(options, swift) { return enumValue; }, }; + const __bjs_codec_M10TestModuleT15GenericReadable = { + 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_M10TestModuleT11GenericNode = { + 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_createStructHelpers_M10TestModuleT12GenericPoint = () => ({ lower: (value) => { @@ -586,6 +610,8 @@ export async function createInstantiator(options, swift) { __bjs_codec_M10TestModuleT12GenericColor, __bjs_stringCodec, __bjs_codec_M10TestModuleT13GenericTagged, + __bjs_codec_M10TestModuleT15GenericReadable, + __bjs_codec_M10TestModuleT11GenericNode, ]; const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); for (let i = 0; i < count; i++) { @@ -783,6 +809,26 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_constrainedRoundTrip"] = function bjs_constrainedRoundTrip(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = imports.constrainedRoundTrip(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_constrainedComposition"] = function bjs_constrainedComposition(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = imports.constrainedComposition(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); @@ -835,6 +881,61 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_ConstrainedConsumer_init"] = function bjs_ConstrainedConsumer_init(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + return swift.memory.retain(new imports.ConstrainedConsumer(value)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ConstrainedConsumer_identity_static"] = function bjs_ConstrainedConsumer_identity_static(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = imports.ConstrainedConsumer.identity(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_ConstrainedConsumer_accept"] = function bjs_ConstrainedConsumer_accept(self, tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = swift.memory.getObject(self).accept(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_GenericReadable_read"] = function bjs_GenericReadable_read(self) { + try { + let ret = swift.memory.getObject(self).read(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_GenericWritable_value_get"] = function bjs_GenericWritable_value_get(self) { + try { + let ret = swift.memory.getObject(self).value; + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_GenericWritable_value_set"] = function bjs_GenericWritable_value_set(self, value) { + try { + swift.memory.getObject(self).value = value; + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md index d62d71051..4c91ba749 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md @@ -15,6 +15,8 @@ When you mark a protocol with `@JS`, BridgeJS generates: Use `@JS("PublicName")` on a protocol to rename its TypeScript interface and generated type references. Swift still uses the original protocol name for conformances and signatures. JavaScript objects still satisfy the interface structurally; renaming does not create a protocol constructor or change how callbacks and protocol values cross the boundary. Unlike `@JS(as: Other.self)`, it does not change the representation, and combining the two options is not supported. +An `@JS` protocol can refine other `@JS` protocols declared in the same module. Its generated TypeScript interface and Swift wrapper expose inherited methods and properties. Cross-module protocol refinement is not supported. + ## Example: Counter Protocol Mark a Swift protocol with `@JS` to expose it: @@ -220,8 +222,10 @@ struct AnyCounter: Counter, _BridgedSwiftProtocolWrapper { | Optional properties | ✅ | | Optional protocol methods | ❌ | | Associated types | ❌ | -| Protocol inheritance | ❌ | -| Protocol composition: `Protocol1 & Protocol2` | ❌ | -| Generics | ❌ | +| Same-module `@JS` protocol inheritance | ✅ | +| Cross-module protocol inheritance | ❌ | +| Existential protocol composition: `any Protocol1 & Protocol2` | ❌ | +| Generic requirements | ❌ | +| Protocol-valued properties, parameters, or results in requirements | ❌ | -> Note: Protocol type support matches that of regular `@JS func` and `@JS class` exports. See , , and for more information. +> Note: For supported requirement types, see , , and . 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 ebc9ac857..02f0a349d 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 @@ -89,6 +89,17 @@ 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. +Generic imports can also constrain `T` to `@JS` protocols, as in `T: BridgedSwiftGenericBridgeable & P & Q`. If `P` inherits `BridgedSwiftGenericBridgeable`, use `T: P`: + +```swift +import JavaScriptKit + +@JS protocol Named: BridgedSwiftGenericBridgeable { var name: String { get } } +@JSFunction func display(_ value: T) throws(JSException) +``` + +Constraints may use `@JS` protocols from dependency modules, including qualified names such as `T: BridgedSwiftGenericBridgeable & Models.Named`. Concrete conformers must expose the required members to JavaScript too, including marking methods with `@JS`. This does not enable existential compositions such as `any P & Q`; the generic-import limitations above still apply. + ## Supported features | Feature | Status | @@ -96,4 +107,5 @@ let user: User = try parse(jsonString) // T inferred from the call site | Primitive parameter/result types (e.g. `Double`, `Bool`) | ✅ | | `String` parameter/result type | ✅ | | Generic parameter/result types (constrained to `BridgedSwiftGenericBridgeable`) | ✅ | +| `@JS` protocol constraints on generic imports | ✅ | | Async function | ❌ | diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 4496316e7..acb3e23f1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4247,9 +4247,7 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y #endif } -struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension ArrayElementProtocol where Self: _BridgedSwiftProtocolWrapper { var value: Int { get { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -4262,6 +4260,10 @@ struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapp bjs_ArrayElementProtocol_value_set(jsObjectValue, newValueValue) } } +} + +struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyArrayElementProtocol(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -4292,18 +4294,16 @@ fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ return bjs_ArrayElementProtocol_value_set_extern(jsObject, newValue) } -struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - +extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { func increment(by amount: Int) -> Void { let amountValue = amount.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_increment(jsObjectValue, amountValue) + bjs_DataProcessor_increment(jsObjectValue, amountValue) } func getValue() -> Int { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getValue(jsObjectValue) + let ret = bjs_DataProcessor_getValue(jsObjectValue) return Int.bridgeJSLiftReturn(ret) } @@ -4311,58 +4311,58 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) + bjs_DataProcessor_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) } } } func getLabel() -> String { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getLabel(jsObjectValue) + let ret = bjs_DataProcessor_getLabel(jsObjectValue) return String.bridgeJSLiftReturn(ret) } func isEven() -> Bool { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_isEven(jsObjectValue) + let ret = bjs_DataProcessor_isEven(jsObjectValue) return Bool.bridgeJSLiftReturn(ret) } func processGreeter(_ greeter: Greeter) -> String { let greeterPointer = greeter.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_processGreeter(jsObjectValue, greeterPointer) + let ret = bjs_DataProcessor_processGreeter(jsObjectValue, greeterPointer) return String.bridgeJSLiftReturn(ret) } func createGreeter() -> Greeter { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createGreeter(jsObjectValue) + let ret = bjs_DataProcessor_createGreeter(jsObjectValue) return Greeter.bridgeJSLiftReturn(ret) } func processOptionalGreeter(_ greeter: Optional) -> String { let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_processOptionalGreeter(jsObjectValue, greeterIsSome, greeterPointer) + let ret = bjs_DataProcessor_processOptionalGreeter(jsObjectValue, greeterIsSome, greeterPointer) return String.bridgeJSLiftReturn(ret) } func createOptionalGreeter() -> Optional { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createOptionalGreeter(jsObjectValue) + let ret = bjs_DataProcessor_createOptionalGreeter(jsObjectValue) return Optional.bridgeJSLiftReturn(ret) } func handleAPIResult(_ result: Optional) -> Void { let (resultIsSome, resultCaseId) = result.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - _extern_handleAPIResult(jsObjectValue, resultIsSome, resultCaseId) + bjs_DataProcessor_handleAPIResult(jsObjectValue, resultIsSome, resultCaseId) } func getAPIResult() -> Optional { let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getAPIResult(jsObjectValue) + let ret = bjs_DataProcessor_getAPIResult(jsObjectValue) return Optional.bridgeJSLiftReturn(ret) } @@ -4492,6 +4492,10 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { bjs_DataProcessor_optionalHelper_set(jsObjectValue, newValueIsSome, newValuePointer) } } +} + +struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyDataProcessor(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -4500,134 +4504,134 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_increment") -fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void +fileprivate func bjs_DataProcessor_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void #else -fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_increment(_ jsObject: Int32, _ amount: Int32) -> Void { + return bjs_DataProcessor_increment_extern(jsObject, amount) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getValue") -fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_getValue_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_getValue(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_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 +fileprivate func bjs_DataProcessor_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 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_setLabelElements(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { + return bjs_DataProcessor_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 +fileprivate func bjs_DataProcessor_getLabel_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_getLabel(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_getLabel_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_isEven") -fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_isEven_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_isEven(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_isEven_extern(jsObject) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processGreeter") -fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 +fileprivate func bjs_DataProcessor_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_processGreeter(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { + return bjs_DataProcessor_processGreeter_extern(jsObject, greeter) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createGreeter") -fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_DataProcessor_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer #else -fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_createGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_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 +fileprivate func bjs_DataProcessor_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_processOptionalGreeter(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { + return bjs_DataProcessor_processOptionalGreeter_extern(jsObject, greeterIsSome, greeterPointer) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createOptionalGreeter") -fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_DataProcessor_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer #else -fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_createOptionalGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_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 +fileprivate func bjs_DataProcessor_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void #else -fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_handleAPIResult(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + return bjs_DataProcessor_handleAPIResult_extern(jsObject, resultIsSome, resultCaseId) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getAPIResult") -fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_getAPIResult_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 { +fileprivate func bjs_DataProcessor_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) +@inline(never) fileprivate func bjs_DataProcessor_getAPIResult(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_getAPIResult_extern(jsObject) } #if arch(wasm32) @@ -4858,15 +4862,266 @@ fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) } -struct AnyJSNameTransformer: JSNameTransformer, _BridgedSwiftProtocolWrapper { +extension GenericRTPosition where Self: _BridgedSwiftProtocolWrapper { + func sum() -> Int { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_GenericRTPosition_sum(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + + var x: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_GenericRTPosition_x_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyGenericRTPosition: GenericRTPosition, _BridgedSwiftProtocolWrapper { let jsObject: JSObject + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyGenericRTPosition(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_GenericRTPosition_sum") +fileprivate func bjs_GenericRTPosition_sum_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_GenericRTPosition_sum_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericRTPosition_sum(_ jsObject: Int32) -> Int32 { + return bjs_GenericRTPosition_sum_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_GenericRTPosition_x_get") +fileprivate func bjs_GenericRTPosition_x_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_GenericRTPosition_x_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericRTPosition_x_get(_ jsObject: Int32) -> Int32 { + return bjs_GenericRTPosition_x_get_extern(jsObject) +} + +extension GenericRTNode where Self: _BridgedSwiftProtocolWrapper { + var y: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_GenericRTNode_y_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyGenericRTNode: GenericRTNode, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyGenericRTNode(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_GenericRTNode_y_get") +fileprivate func bjs_GenericRTNode_y_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_GenericRTNode_y_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericRTNode_y_get(_ jsObject: Int32) -> Int32 { + return bjs_GenericRTNode_y_get_extern(jsObject) +} + +extension RefineIdentified where Self: _BridgedSwiftProtocolWrapper { + var id: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineIdentified_id_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } + + var score: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineIdentified_score_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + set { + let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_RefineIdentified_score_set(jsObjectValue, newValueValue) + } + } +} + +struct AnyRefineIdentified: RefineIdentified, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyRefineIdentified(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineIdentified_id_get") +fileprivate func bjs_RefineIdentified_id_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineIdentified_id_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineIdentified_id_get(_ jsObject: Int32) -> Int32 { + return bjs_RefineIdentified_id_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineIdentified_score_get") +fileprivate func bjs_RefineIdentified_score_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineIdentified_score_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineIdentified_score_get(_ jsObject: Int32) -> Int32 { + return bjs_RefineIdentified_score_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineIdentified_score_set") +fileprivate func bjs_RefineIdentified_score_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_RefineIdentified_score_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineIdentified_score_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_RefineIdentified_score_set_extern(jsObject, newValue) +} + +extension RefineNamed where Self: _BridgedSwiftProtocolWrapper { + func label() -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineNamed_label(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + + var name: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineNamed_name_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyRefineNamed: RefineNamed, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyRefineNamed(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineNamed_label") +fileprivate func bjs_RefineNamed_label_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineNamed_label_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineNamed_label(_ jsObject: Int32) -> Int32 { + return bjs_RefineNamed_label_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineNamed_name_get") +fileprivate func bjs_RefineNamed_name_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineNamed_name_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineNamed_name_get(_ jsObject: Int32) -> Int32 { + return bjs_RefineNamed_name_get_extern(jsObject) +} + +extension RefineEntity where Self: _BridgedSwiftProtocolWrapper { + func label() -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineEntity_label(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + + var id: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_RefineEntity_id_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyRefineEntity: RefineEntity, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyRefineEntity(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineEntity_label") +fileprivate func bjs_RefineEntity_label_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineEntity_label_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineEntity_label(_ jsObject: Int32) -> Int32 { + return bjs_RefineEntity_label_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_RefineEntity_id_get") +fileprivate func bjs_RefineEntity_id_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_RefineEntity_id_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_RefineEntity_id_get(_ jsObject: Int32) -> Int32 { + return bjs_RefineEntity_id_get_extern(jsObject) +} + +struct AnyRefineTagged: RefineTagged, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyRefineTagged(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +extension JSNameTransformer where Self: _BridgedSwiftProtocolWrapper { func apply(_ value: Int) -> Int { let valueValue = value.bridgeJSLowerParameter() let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_apply(jsObjectValue, valueValue) + let ret = bjs_JSNameTransformer_apply(jsObjectValue, valueValue) return Int.bridgeJSLiftReturn(ret) } +} + +struct AnyJSNameTransformer: JSNameTransformer, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject static func bridgeJSLiftParameter(_ value: Int32) -> Self { return AnyJSNameTransformer(jsObject: JSObject(id: UInt32(bitPattern: value))) @@ -4875,14 +5130,14 @@ struct AnyJSNameTransformer: JSNameTransformer, _BridgedSwiftProtocolWrapper { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSNameTransformer_apply") -fileprivate func _extern_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 +fileprivate func bjs_JSNameTransformer_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 #else -fileprivate func _extern_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 { +fileprivate func bjs_JSNameTransformer_apply_extern(_ jsObject: Int32, _ value: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_apply(_ jsObject: Int32, _ value: Int32) -> Int32 { - return _extern_apply_extern(jsObject, value) +@inline(never) fileprivate func bjs_JSNameTransformer_apply(_ jsObject: Int32, _ value: Int32) -> Int32 { + return bjs_JSNameTransformer_apply_extern(jsObject, value) } extension Severity: _BridgedSwiftCaseEnum { @@ -7841,6 +8096,18 @@ fileprivate func _bjs_struct_lift_GenericRTPoint_extern() -> Int32 { return _bjs_struct_lift_GenericRTPoint_extern() } +@_expose(wasm, "bjs_GenericRTPoint_sum") +@_cdecl("bjs_GenericRTPoint_sum") +public func _bjs_GenericRTPoint_sum() -> Int32 { + #if arch(wasm32) + let _self = GenericRTPoint.bridgeJSLiftParameter() + let ret = _self.sum() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension GenericRTNamespace.Metadata: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericRTNamespace.Metadata { let count = Int.bridgeJSStackPop() @@ -11254,6 +11521,30 @@ public func _bjs_roundTripMessage(_ message: Int32) -> Void { #endif } +@_expose(wasm, "bjs_describeRefinedEntity") +@_cdecl("bjs_describeRefinedEntity") +public func _bjs_describeRefinedEntity(_ entity: Int32) -> Void { + #if arch(wasm32) + let entity = AnyRefineEntity.bridgeJSLiftParameter(entity) + let ret = describeRefinedEntity(_: entity) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_describeTaggedEntity") +@_cdecl("bjs_describeTaggedEntity") +public func _bjs_describeTaggedEntity(_ entity: Int32) -> Void { + #if arch(wasm32) + let entity = AnyRefineTagged.bridgeJSLiftParameter(entity) + let ret = describeTaggedEntity(_: entity) + 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 { @@ -15910,6 +16201,14 @@ extension APIOptionalResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIOptionalResult.bridgeJSMakeTypeHandle() } +extension AnyGenericRTPosition: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyGenericRTPosition.bridgeJSMakeTypeHandle() +} + +extension AnyGenericRTNode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyGenericRTNode.bridgeJSMakeTypeHandle() +} + @JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) #if arch(wasm32) @@ -19464,6 +19763,47 @@ func _$jsGenericThrowOrRoundTrip(_ shouldThrow return T.bridgeJSStackPop() } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericNodeRoundTrip") +fileprivate func bjs_jsGenericNodeRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericNodeRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericNodeRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericNodeRoundTrip_extern(_generic0TypeId) +} + +func _$jsGenericNodeRoundTrip(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_jsGenericNodeRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericMakeNode") +fileprivate func bjs_jsGenericMakeNode_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericMakeNode_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericMakeNode(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericMakeNode_extern(_generic0TypeId) +} + +func _$jsGenericMakeNode() throws(JSException) -> T { + bjs_jsGenericMakeNode(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 @@ -21026,6 +21366,8 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { GenericRTOutcome.bridgeJSTypeID, OptionalAllTypesResult.bridgeJSTypeID, APIOptionalResult.bridgeJSTypeID, + AnyGenericRTPosition.bridgeJSTypeID, + AnyGenericRTNode.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in _bjs_BridgeJSRuntimeTests_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 0084d9f6a..4749c6eb3 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -17671,6 +17671,56 @@ } } }, + { + "abiName" : "bjs_describeRefinedEntity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeRefinedEntity", + "parameters" : [ + { + "label" : "_", + "name" : "entity", + "type" : { + "swiftProtocol" : { + "_0" : "RefineEntity" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_describeTaggedEntity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeTaggedEntity", + "parameters" : [ + { + "label" : "_", + "name" : "entity", + "type" : { + "swiftProtocol" : { + "_0" : "RefineTagged" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_renamedEcho", "effects" : { @@ -18984,6 +19034,181 @@ } ] }, + { + "isGenericBridgeable" : true, + "methods" : [ + { + "abiName" : "bjs_GenericRTPosition_sum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sum", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "GenericRTPosition", + "properties" : [ + { + "isReadonly" : true, + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "GenericRTPosition" + ], + "isGenericBridgeable" : true, + "methods" : [ + + ], + "name" : "GenericRTNode", + "properties" : [ + { + "isReadonly" : true, + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + { + "methods" : [ + + ], + "name" : "RefineIdentified", + "properties" : [ + { + "isReadonly" : true, + "name" : "id", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "name" : "score", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + { + "methods" : [ + { + "abiName" : "bjs_RefineNamed_label", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "label", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "RefineNamed", + "properties" : [ + { + "isReadonly" : true, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "RefineIdentified", + "RefineNamed" + ], + "methods" : [ + { + "abiName" : "bjs_RefineEntity_label", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "label", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "RefineEntity", + "properties" : [ + { + "isReadonly" : true, + "name" : "id", + "type" : { + "string" : { + + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "RefineEntity" + ], + "methods" : [ + + ], + "name" : "RefineTagged", + "properties" : [ + + ] + }, { "jsName" : "CounterTransform", "methods" : [ @@ -19377,7 +19602,26 @@ }, { "methods" : [ + { + "abiName" : "bjs_GenericRTPoint_sum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sum", + "parameters" : [ + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } ], "name" : "GenericRTPoint", "properties" : [ @@ -25257,7 +25501,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericRoundTrip", "parameters" : [ @@ -25284,7 +25530,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericRoundTripClass", "parameters" : [ @@ -25311,7 +25559,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericParsePoint", "parameters" : [ @@ -25338,7 +25588,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsImportPickFirst", "parameters" : [ @@ -25373,7 +25625,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsImportMakeInt", "parameters" : [ @@ -25393,8 +25647,12 @@ "isThrows" : true }, "genericParameters" : [ - "T", - "U" + { + "name" : "T" + }, + { + "name" : "U" + } ], "name" : "jsImportCombineSecond", "parameters" : [ @@ -25429,7 +25687,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericArrayRoundTrip", "parameters" : [ @@ -25464,7 +25724,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericOptionalRoundTrip", "parameters" : [ @@ -25501,7 +25763,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericDictRoundTrip", "parameters" : [ @@ -25536,7 +25800,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericAfterOptionalArray", "parameters" : [ @@ -25583,7 +25849,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "jsGenericThrowOrRoundTrip", "parameters" : [ @@ -25609,6 +25877,64 @@ "_0" : "T" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericRTNode" + ], + "name" : "T" + } + ], + "name" : "jsGenericNodeRoundTrip", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "constraints" : [ + "GenericRTPosition", + "GenericRTNode" + ], + "name" : "T" + } + ], + "name" : "jsGenericMakeNode", + "parameters" : [ + + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } } ], "types" : [ @@ -25632,7 +25958,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "identity", "parameters" : [ @@ -25665,7 +25993,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "box", "parameters" : [ @@ -25691,7 +26021,9 @@ "constructor" : { "accessLevel" : "internal", "genericParameters" : [ - "T" + { + "name" : "T" + } ], "parameters" : [ { @@ -25716,7 +26048,9 @@ "isThrows" : true }, "genericParameters" : [ - "T" + { + "name" : "T" + } ], "name" : "unwrap", "parameters" : [ diff --git a/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift index bfd63839f..c5484edc6 100644 --- a/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift @@ -79,7 +79,34 @@ import JavaScriptKit @JSFunction func unwrap() throws(JSException) -> T } +@JS protocol GenericRTPosition: BridgedSwiftGenericBridgeable { + var x: Int { get } + func sum() -> Int +} + +@JS protocol GenericRTNode: GenericRTPosition { + var y: Int { get } +} + +extension GenericRTPoint: GenericRTNode { + @JS func sum() -> Int { x + y } +} + +@JSFunction func jsGenericNodeRoundTrip(_ value: T) throws(JSException) -> T +@JSFunction func jsGenericMakeNode() + throws(JSException) -> T + @Suite struct ImportGenericAPITests { + @Test func constrainedProtocolRoundTrip() throws { + let point = try jsGenericNodeRoundTrip(GenericRTPoint(x: 1, y: 2)) + #expect(point.sum() == 3) + let node: AnyGenericRTNode = try jsGenericMakeNode() + #expect(node.x == 3) + #expect(node.y == 4) + #expect(node.sum() == 7) + #expect(try jsGenericNodeRoundTrip(node).jsObject == node.jsObject) + } + @Test func genericRoundTripScalars() throws { #expect(try jsGenericRoundTrip(42) == 42) #expect(try jsGenericRoundTrip(-7) == -7) @@ -278,3 +305,30 @@ import JavaScriptKit #expect(color == .green) } } + +@JS protocol RefineIdentified { + var id: String { get } + var score: Int { get set } +} + +@JS protocol RefineNamed { + var name: String { get } + func label() -> String +} + +@JS protocol RefineEntity: RefineIdentified, RefineNamed { + var id: String { get } + func label() -> String +} + +@JS func describeRefinedEntity(_ entity: RefineEntity) -> String { + var identified: any RefineIdentified = entity + identified.score = entity.score + 1 + return "\(entity.id):\(entity.name):\(entity.label()):\(identified.score)" +} + +@JS protocol RefineTagged: RefineEntity {} + +@JS func describeTaggedEntity(_ entity: RefineTagged) -> String { + "\(entity.id)/\(entity.name)/\(entity.score)" +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 977a1f386..5287df791 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -178,6 +178,11 @@ export async function setupOptions(options, context) { jsGenericOptionalRoundTrip: (v) => v, jsGenericDictRoundTrip: (v) => v, jsGenericAfterOptionalArray: (a, b) => `${JSON.stringify(a)}|${JSON.stringify(b)}`, + jsGenericNodeRoundTrip: (value) => { + if (value.sum() !== value.x + value.y) throw new Error("Invalid protocol method result"); + return value; + }, + jsGenericMakeNode: () => ({ x: 3, y: 4, sum() { return this.x + this.y; } }), ImportGenericConsumer: class { identity(value) { return value; @@ -296,6 +301,10 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { const optDict = { hello: "world" }; assert.deepEqual(exports.roundTripOptionalDictionaryExport(optDict), optDict); assert.equal(exports.roundTripOptionalDictionaryExport(null), null); + const entity = { id: "e1", name: "Main", score: 10, label() { return "L" + this.score; } }; + assert.equal(exports.describeRefinedEntity(entity), "e1:Main:L11:11"); + assert.equal(entity.score, 11); + assert.equal(exports.describeTaggedEntity(entity), "e1/Main/11"); const arrayStruct = { ints: [1, 2, 3], optStrings: ["a", "b"] }; const arrayStructRoundTrip = exports.roundTripArrayMembers(arrayStruct); assert.deepEqual(arrayStructRoundTrip.ints, [1, 2, 3]); From 299008330714094ba52f955695ce47faaf868ca8 Mon Sep 17 00:00:00 2001 From: Simon Leeb <52261246+sliemeobn@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:39:24 +0200 Subject: [PATCH 124/140] Optimized String bridging (Swift -> JS) (#816) --- Benchmarks/Sources/Generated/BridgeJS.swift | 12 +- .../PlayBridgeJS/Generated/BridgeJS.swift | 12 +- Plugins/BridgeJS/README.md | 5 +- .../Sources/BridgeJSCore/ExportSwift.swift | 4 +- .../Sources/BridgeJSCore/ImportTS.swift | 2 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 194 +++- .../Sources/BridgeJSLink/JSGlueGen.swift | 13 +- .../Inputs/StringDecoderTests.mjs | 98 ++ .../StringDecoderTests.swift | 44 + .../BridgeJSCodegenTests/Alias.swift | 36 +- .../BridgeJSCodegenTests/Async.swift | 36 +- .../BridgeJSCodegenTests/AsyncImport.swift | 24 +- .../BridgeJSCodegenTests/EnumRawType.swift | 12 +- .../BridgeJSCodegenTests/GenericImports.swift | 24 +- .../BridgeJSCodegenTests/GlobalGetter.swift | 12 +- .../GlobalThisImports.swift | 36 +- .../BridgeJSCodegenTests/ImportArray.swift | 12 +- .../InvalidPropertyNames.swift | 60 +- .../BridgeJSCodegenTests/JSClass.swift | 36 +- .../JSImportBareModule.swift | 24 +- .../JSImportBareModuleFallback.swift | 14 +- .../BridgeJSCodegenTests/Optionals.swift | 62 +- .../BridgeJSCodegenTests/Protocol.swift | 62 +- .../StringParameter.swift | 24 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 132 +-- .../SwiftClosureImports.swift | 48 +- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 183 +++- .../BridgeJSLinkTests/AliasInClosure.js | 173 +++- .../BridgeJSLinkTests/ArrayTypes.js | 171 +++- .../__Snapshots__/BridgeJSLinkTests/Async.js | 183 +++- .../AsyncAssociatedValueEnum.js | 171 +++- .../BridgeJSLinkTests/AsyncImport.js | 181 +++- .../BridgeJSLinkTests/AsyncStaticImport.js | 173 +++- .../BridgeJSLinkTests/ClassWithNestedTypes.js | 171 +++- .../BridgeJSLinkTests/DefaultParameters.js | 171 +++- .../BridgeJSLinkTests/DictionaryTypes.js | 171 +++- .../BridgeJSLinkTests/DocComments.js | 171 +++- .../BridgeJSLinkTests/EnumAlias.js | 171 +++- .../BridgeJSLinkTests/EnumAssociatedValue.js | 171 +++- .../EnumAssociatedValueImport.js | 171 +++- .../BridgeJSLinkTests/EnumCase.js | 171 +++- .../BridgeJSLinkTests/EnumCaseImport.js | 171 +++- .../BridgeJSLinkTests/EnumNamespace.Global.js | 171 +++- .../BridgeJSLinkTests/EnumNamespace.js | 171 +++- .../BridgeJSLinkTests/EnumRawType.js | 175 +++- .../BridgeJSLinkTests/ExtensionNestedTypes.js | 171 +++- .../ExtensionOrderIndependence.js | 171 +++- .../BridgeJSLinkTests/ExtensionScopeParity.js | 171 +++- .../BridgeJSLinkTests/FixedWidthIntegers.js | 171 +++- .../BridgeJSLinkTests/GenericImports.js | 179 +++- .../BridgeJSLinkTests/GlobalGetter.js | 175 +++- .../BridgeJSLinkTests/GlobalThisImports.js | 183 +++- .../IdentityModeClass.ConfigPointer.js | 171 +++- .../IdentityModeClass.PerClass.js | 171 +++- .../BridgeJSLinkTests/IdentityModeClass.js | 171 +++- .../BridgeJSLinkTests/ImportArray.js | 175 +++- .../ImportedTypeInExportedInterface.js | 171 +++- .../BridgeJSLinkTests/InvalidPropertyNames.js | 191 +++- .../BridgeJSLinkTests/JSClass.js | 183 +++- .../JSClassStaticFunctions.js | 171 +++- .../BridgeJSLinkTests/JSImportBareModule.js | 179 +++- .../JSImportBareModuleFallback.js | 177 +++- .../BridgeJSLinkTests/JSImportModule.js | 171 +++- .../BridgeJSLinkTests/JSNameOverride.js | 171 +++- .../BridgeJSLinkTests/JSNameTypes.js | 171 +++- .../BridgeJSLinkTests/JSTypedArrayTypes.js | 171 +++- .../BridgeJSLinkTests/JSValue.js | 171 +++- .../BridgeJSLinkTests/MixedGlobal.js | 171 +++- .../BridgeJSLinkTests/MixedModules.js | 171 +++- .../BridgeJSLinkTests/MixedPrivate.js | 171 +++- .../NamespacedClassSignature.js | 173 +++- .../BridgeJSLinkTests/Namespaces.Global.js | 171 +++- .../BridgeJSLinkTests/Namespaces.js | 171 +++- .../BridgeJSLinkTests/NestedType.js | 171 +++- .../NestedTypeNameCollision.js | 171 +++- .../BridgeJSLinkTests/Optionals.js | 193 +++- .../BridgeJSLinkTests/PrimitiveParameters.js | 171 +++- .../BridgeJSLinkTests/PrimitiveReturn.js | 171 +++- .../BridgeJSLinkTests/PropertyTypes.js | 171 +++- .../BridgeJSLinkTests/Protocol.js | 193 +++- .../BridgeJSLinkTests/ProtocolInClosure.js | 173 +++- .../RelativeQualifiedTypes.js | 171 +++- .../StaticFunctions.Global.js | 171 +++- .../BridgeJSLinkTests/StaticFunctions.js | 171 +++- .../StaticProperties.Global.js | 171 +++- .../BridgeJSLinkTests/StaticProperties.js | 171 +++- .../BridgeJSLinkTests/StringParameter.js | 179 +++- .../BridgeJSLinkTests/StringReturn.js | 171 +++- .../StructWithNestedTypes.js | 171 +++- .../BridgeJSLinkTests/SwiftClass.js | 171 +++- .../BridgeJSLinkTests/SwiftClosure.js | 217 ++++- .../BridgeJSLinkTests/SwiftClosureImports.js | 189 +++- .../BridgeJSLinkTests/SwiftStruct.js | 171 +++- .../BridgeJSLinkTests/SwiftStructImports.js | 171 +++- .../SwiftTypedClosureAccess.js | 173 +++- .../__Snapshots__/BridgeJSLinkTests/Throws.js | 171 +++- .../BridgeJSLinkTests/UnsafePointer.js | 171 +++- .../VoidParameterVoidReturn.js | 171 +++- .../JavaScriptKit/BridgeJSIntrinsics.swift | 97 +- .../Generated/BridgeJS.swift | 836 ++++++++++++------ .../Generated/JavaScript/BridgeJS.json | 570 ++++++++++++ .../JavaScript/StringABITests.mjs | 53 ++ .../BridgeJSRuntimeTests/StringABITests.swift | 81 ++ Tests/prelude.mjs | 8 + 104 files changed, 13775 insertions(+), 1458 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/StringDecoderTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs create mode 100644 Tests/BridgeJSRuntimeTests/StringABITests.swift diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 86f2516e6..fc46623f2 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -2429,20 +2429,20 @@ func _$benchmarkHelperNoopWithNumber(_ n: Double) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkRunner") -fileprivate func bjs_benchmarkRunner_extern(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void +fileprivate func bjs_benchmarkRunner_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ body: Int32) -> Void #else -fileprivate func bjs_benchmarkRunner_extern(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void { +fileprivate func bjs_benchmarkRunner_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ body: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_benchmarkRunner(_ nameBytes: Int32, _ nameLength: Int32, _ body: Int32) -> Void { - return bjs_benchmarkRunner_extern(nameBytes, nameLength, body) +@inline(never) fileprivate func bjs_benchmarkRunner(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ body: Int32) -> Void { + return bjs_benchmarkRunner_extern(nameWord0, nameWord1, nameWord2, body) } func _$benchmarkRunner(_ name: String, _ body: JSObject) throws(JSException) -> Void { - name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in let bodyValue = body.bridgeJSLowerParameter() - bjs_benchmarkRunner(nameBytes, nameLength, bodyValue) + bjs_benchmarkRunner(nameWord0, nameWord1, nameWord2, bodyValue) } if let error = _swift_js_take_exception() { throw error diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index eed55bdea..ee8b1f436 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -268,20 +268,20 @@ func _$createTS2Swift() throws(JSException) -> TS2Swift { #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_TS2Swift_convert") -fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsWord0: Int32, _ tsWord1: Int32, _ tsWord2: Int32) -> Int32 #else -fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 { +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsWord0: Int32, _ tsWord1: Int32, _ tsWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ tsBytes: Int32, _ tsLength: Int32) -> Int32 { - return bjs_TS2Swift_convert_extern(self, tsBytes, tsLength) +@inline(never) fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ tsWord0: Int32, _ tsWord1: Int32, _ tsWord2: Int32) -> Int32 { + return bjs_TS2Swift_convert_extern(self, tsWord0, tsWord1, tsWord2) } func _$TS2Swift_convert(_ self: JSObject, _ ts: String) throws(JSException) -> String { - let ret0 = ts.bridgeJSWithLoweredParameter { (tsBytes, tsLength) in + let ret0 = ts.bridgeJSWithLoweredParameter { (tsWord0, tsWord1, tsWord2) in let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_TS2Swift_convert(selfValue, tsBytes, tsLength) + let ret = bjs_TS2Swift_convert(selfValue, tsWord0, tsWord1, tsWord2) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/README.md b/Plugins/BridgeJS/README.md index 0905695c5..4d93dc875 100644 --- a/Plugins/BridgeJS/README.md +++ b/Plugins/BridgeJS/README.md @@ -139,7 +139,8 @@ The ABI will not be stable, and not meant to be interposed by other tools. Parameter passing follows Wasm calling conventions, with custom handling for complex types: - **Primitives**: Passed directly as Wasm arguments (`i32`, `i64`, `f32`, `f64`) -- **Strings**: UTF-8 bytes stored in `swift.memory`, ID + length passed as Wasm arguments +- **Strings (JS → Swift)**: UTF-8 bytes stored in `swift.memory`, ID + length passed as Wasm arguments +- **Strings (Swift → JS)**: the wasm32 12-byte `String` layout passed as three `i32` words. JS fast-decodes small strings, caches large immortals by a 53-bit `ptr + len` pack when `len < 2**21`, and otherwise reads UTF-8 at `word1 + 20` (`nativeBias`). This layout is a Swift stdlib implementation detail and can change with the toolchain. - **Swift Classes**: Raw Swift heap pointer passed as `i32` - **JSObjects**: Object stored in `swift.memory.heap`, object ID passed as `i32` - **Structs/Arrays**: Fields/elements pushed to type-specific stacks, Swift pops in reverse order @@ -150,7 +151,7 @@ Parameter passing follows Wasm calling conventions, with custom handling for com Return values use direct Wasm returns for primitives, and imported intrinsic functions for complex types: - **Primitives**: Returned directly via Wasm return value -- **Strings**: Swift writes UTF-8 bytes to shared memory, JS decodes +- **Strings**: Swift passes the 12-byte `String` layout; JS decodes (small / immortal-cached / UTF-8) - **Swift Classes**: Pointer returned directly, JS wraps in `SwiftHeapObject` with `FinalizationRegistry` - **Structs/Arrays**: Swift pushes fields/elements to type-specific stacks, JS reconstructs diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 6b5d3ef76..df8c589ea 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -744,9 +744,7 @@ public class ExportSwift { /// public func _bjs_Greeter_greet(pointer: UnsafeMutableRawPointer) -> Void { /// let _self = Unmanaged.fromOpaque(pointer).takeUnretainedValue() /// var ret = _self.greet() - /// return ret.withUTF8 { ptr in - /// _swift_js_return_string(ptr.baseAddress, Int32(ptr.count)) - /// } + /// return ret.bridgeJSLowerReturn() /// } /// @_expose(wasm, "bjs_Greeter_deinit") /// @_cdecl("bjs_Greeter_deinit") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 378fe2012..841c0409c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -927,7 +927,7 @@ extension BridgeType { static let float = LoweringParameterInfo(loweredParameters: [("value", .f32)]) static let double = LoweringParameterInfo(loweredParameters: [("value", .f64)]) static let string = LoweringParameterInfo( - loweredParameters: [("bytes", .i32), ("length", .i32)], + loweredParameters: [("word0", .i32), ("word1", .i32), ("word2", .i32)], useBorrowing: true ) static let jsObject = LoweringParameterInfo(loweredParameters: [("value", .i32)]) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 40b1c13c3..7f4ecab03 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -313,12 +313,180 @@ public struct BridgeJSLink { return data } + /// Emits `decodeString`, including small-string helpers used only by it. + /// + /// The wasm32 12-byte Swift `String` layout is a standard-library + /// implementation detail, not a stable ABI. Small strings (`word2 & 0x2000`) + /// store up to 8 UTF-8 bytes inline. Large strings store the UTF-8 count in + /// `word0` and a variant/object pointer in `word1`; UTF-8 starts at + /// `word1 + nativeBias` (20 on 32-bit). Immortal large strings + /// (`word2 & 0x8000`) are cached by a 53-bit `ptr + len * 2**32` key when + /// `len < 2**21`; longer immortals skip the cache. + private func emitDecodeString(_ printer: CodeFragmentPrinter) { + printer.write( + multilineString: """ + \(JSGlueVariableScope.reservedDecodeString) = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return \(JSGlueVariableScope.reservedDecodeUTF8)(ptr, len); + const key = ptr + len * 0x100000000; + const cached = \(JSGlueVariableScope.reservedImmortalStrings).get(key); + if (cached !== undefined) return cached; + const value = \(JSGlueVariableScope.reservedDecodeUTF8)(ptr, len); + \(JSGlueVariableScope.reservedImmortalStrings).set(key, value); + return value; + }; + })(); + """ + ) + } + private func generateVariableDeclarations() -> [String] { var declarations: [String] = [ "let \(JSGlueVariableScope.reservedInstance);", "let \(JSGlueVariableScope.reservedMemory);", "let \(JSGlueVariableScope.reservedSetException);", "let \(JSGlueVariableScope.reservedDecodeString);", + "let \(JSGlueVariableScope.reservedDecodeUTF8);", + "const \(JSGlueVariableScope.reservedImmortalStrings) = new Map();", "const \(JSGlueVariableScope.reservedTextDecoder) = new TextDecoder(\"utf-8\");", "const \(JSGlueVariableScope.reservedTextEncoder) = new TextEncoder(\"utf-8\");", "let \(JSGlueVariableScope.reservedStorageToReturnString);", @@ -495,10 +663,10 @@ public struct BridgeJSLink { "const imports = options.getImports(importsContext);" ]) } - printer.write("bjs[\"swift_js_return_string\"] = function(ptr, len) {") + printer.write("bjs[\"swift_js_return_string\"] = function(word0, word1, word2) {") printer.indent { printer.write( - "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);" + "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(word0, word1, word2);" ) } printer.write("}") @@ -516,10 +684,10 @@ public struct BridgeJSLink { printer.write("bytes.set(source);") } printer.write("}") - printer.write("bjs[\"swift_js_make_js_string\"] = function(ptr, len) {") + printer.write("bjs[\"swift_js_make_js_string\"] = function(word0, word1, word2) {") printer.indent { printer.write( - "return \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).retain(\(JSGlueVariableScope.reservedDecodeString)(ptr, len));" + "return \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).retain(\(JSGlueVariableScope.reservedDecodeString)(word0, word1, word2));" ) } printer.write("}") @@ -566,9 +734,11 @@ public struct BridgeJSLink { printer.write("\(JSGlueVariableScope.reservedF64Stack).push(v);") } printer.write("}") - printer.write("bjs[\"swift_js_push_string\"] = function(ptr, len) {") + printer.write("bjs[\"swift_js_push_string\"] = function(word0, word1, word2) {") printer.indent { - printer.write("const value = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);") + printer.write( + "const value = \(JSGlueVariableScope.reservedDecodeString)(word0, word1, word2);" + ) printer.write("\(JSGlueVariableScope.reservedStringStack).push(value);") } printer.write("}") @@ -732,7 +902,7 @@ public struct BridgeJSLink { printer.write("}") } printer.write("}") - printer.write("bjs[\"swift_js_return_optional_string\"] = function(isSome, ptr, len) {") + printer.write("bjs[\"swift_js_return_optional_string\"] = function(isSome, word0, word1, word2) {") printer.indent { printer.write("if (isSome === 0) {") printer.indent { @@ -741,7 +911,7 @@ public struct BridgeJSLink { printer.write("} else {") printer.indent { printer.write(lines: [ - "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(ptr, len);" + "\(JSGlueVariableScope.reservedStorageToReturnString) = \(JSGlueVariableScope.reservedDecodeString)(word0, word1, word2);" ]) } printer.write("}") @@ -879,7 +1049,7 @@ public struct BridgeJSLink { helperPrinter.write("let length = 0;") helperPrinter.write("while (bytes[length] !== 0) { length += 1; }") helperPrinter.write( - "const fileID = \(JSGlueVariableScope.reservedDecodeString)(state.file, length);" + "const fileID = \(JSGlueVariableScope.reservedDecodeUTF8)(state.file, length);" ) helperPrinter.write( "throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`);" @@ -1289,19 +1459,21 @@ public struct BridgeJSLink { printer.write("setInstance: (i) => {") printer.indent { printer.write(lines: [ + "if (\(JSGlueVariableScope.reservedMemory) !== i.exports.memory) \(JSGlueVariableScope.reservedImmortalStrings).clear();", "\(JSGlueVariableScope.reservedInstance) = i;", "\(JSGlueVariableScope.reservedMemory) = \(JSGlueVariableScope.reservedInstance).exports.memory;", ]) printer.nextLine() if sharedMemory { printer.write( - "\(JSGlueVariableScope.reservedDecodeString) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0).slice(); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" + "\(JSGlueVariableScope.reservedDecodeUTF8) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0).slice(); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" ) } else { printer.write( - "\(JSGlueVariableScope.reservedDecodeString) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" + "\(JSGlueVariableScope.reservedDecodeUTF8) = (ptr, len) => { const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0); return \(JSGlueVariableScope.reservedTextDecoder).decode(bytes); }" ) } + emitDecodeString(printer) printer.nextLine() // Error handling printer.write("\(JSGlueVariableScope.reservedSetException) = (error) => {") diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 747c9f532..2da07f2be 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -14,6 +14,8 @@ final class JSGlueVariableScope { static let reservedMemory = "memory" static let reservedSetException = "setException" static let reservedDecodeString = "decodeString" + static let reservedDecodeUTF8 = "decodeUTF8" + static let reservedImmortalStrings = "immortalStrings" static let reservedStorageToReturnString = "tmpRetString" static let reservedStorageToReturnBytes = "tmpRetBytes" static let reservedStorageToReturnException = "tmpRetException" @@ -49,6 +51,8 @@ final class JSGlueVariableScope { reservedMemory, reservedSetException, reservedDecodeString, + reservedDecodeUTF8, + reservedImmortalStrings, reservedStorageToReturnString, reservedStorageToReturnBytes, reservedStorageToReturnException, @@ -678,14 +682,15 @@ struct IntrinsicJSFragment: Sendable { } ) static let stringLiftParameter = IntrinsicJSFragment( - parameters: ["bytes", "count"], + parameters: ["word0", "word1", "word2"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) - let bytesExpr = arguments[0] - let countExpr = arguments[1] + let word0Expr = arguments[0] + let word1Expr = arguments[1] + let word2Expr = arguments[2] let stringLabel = scope.variable("string") printer.write( - "const \(stringLabel) = \(JSGlueVariableScope.reservedDecodeString)(\(bytesExpr), \(countExpr));" + "const \(stringLabel) = \(JSGlueVariableScope.reservedDecodeString)(\(word0Expr), \(word1Expr), \(word2Expr));" ) return [stringLabel] } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs new file mode 100644 index 000000000..2aa88cf5d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +// Execute generated glue rather than a duplicate of the decoder implementation. +const source = await readFile(process.argv[2] ?? new URL('../__Snapshots__/BridgeJSLinkTests/StringReturn.js', import.meta.url), 'utf8'); +const shared = process.argv[3] === 'shared'; +const { createInstantiator } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const swift = { memory: { heap: [], retain: (value) => value } }; +const bridge = await createInstantiator({ getImports: () => ({}) }, swift); +const imports = {}; +bridge.addImports(imports, {}); +let words; +function instance(memory) { + return { exports: { memory, bjs_checkString: () => imports.bjs.swift_js_return_string(...words) } }; +} +let memory = new WebAssembly.Memory({ initial: 40, maximum: 41, shared }); +let wasm = instance(memory); +bridge.setInstance(wasm); +let exports = bridge.createExports(wasm); +function small(value) { + const bytes = encoder.encode(value); + assert.ok(bytes.length <= 8); + const storage = new Uint8Array(12); + storage.set(bytes.subarray(0, 8)); + storage[9] = (bytes.every((b) => b < 128) ? 0xe0 : 0xa0) | bytes.length; + const view = new DataView(storage.buffer); + return [0, 4, 8].map((offset) => view.getInt32(offset, true)); +} +function large(value, immortal = false, ptr = 64) { + const bytes = encoder.encode(value); + new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes); + return [bytes.length, ptr - 20, immortal ? 0x8000 : 0]; +} +const values = ['', 'div', 'abcdefgh', 'abcdefghi', 'abcdefghij', 'abcdefé', 'abcdefgé', + 'abcdefghé', 'abcdefghié', 'abc€', 'abcdefg€', 'abc😄', 'abcdef😄', 'abcdefg😄', + 'a\0b', '\ufeff', '\ufeffx', 'x\ufeff', '\ufeff\ufeffx', '\ufeffabcdefghijk', + 'abc\ufeffdefghijk', '\ufeff\ufeffabcdefghijk']; +for (const value of values) { + const expected = decoder.decode(encoder.encode(value)); + if (encoder.encode(value).length <= 8) { + words = small(value); + assert.equal(exports.checkString(), expected); + } + words = large(value); + assert.equal(exports.checkString(), expected); +} +// Alternate full and short inputs: bytes outside count must never leak into the result. +for (const value of ['abcd😄', 'é', 'abcde€', '\ufeff', 'abcdefgh', '', 'x\0', '€', '\ufeff\ufeff']) { + words = small(value); + assert.equal(exports.checkString(), decoder.decode(encoder.encode(value))); +} +// Every ASCII byte, including NUL, at every small-string length. +for (let byte = 0; byte < 128; byte++) { + for (let count = 0; count <= 8; count++) { + const value = String.fromCharCode(byte).repeat(count); + words = small(value); + assert.equal(exports.checkString(), value); + } +} +// Unexpected inline lengths must fail for both ASCII and Unicode discriminators. +for (const count of [9, 10]) { + for (const discriminator of [0xe0, 0xa0]) { + words = [0, 0, (discriminator | count) << 8]; + assert.throws(() => exports.checkString(), { + name: 'Error', + message: `Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`, + }); + } +} +words = large('first literal', true); +assert.equal(exports.checkString(), 'first literal'); +// A new instance using the same memory must preserve valid cache entries. +wasm = instance(memory); +bridge.setInstance(wasm); +exports = bridge.createExports(wasm); +assert.equal(exports.checkString(), 'first literal'); +// A different memory may reuse the same pointer/length for different contents. +memory = new WebAssembly.Memory({ initial: 40, maximum: 41, shared }); +wasm = instance(memory); +bridge.setInstance(wasm); +exports = bridge.createExports(wasm); +words = large('other literal', true); +assert.equal(exports.checkString(), 'other literal'); +// Same pointer with a different length must have a distinct key. +words = large('other', true); +assert.equal(exports.checkString(), 'other'); +// Values at the numeric-key cutoff bypass the cache. +const huge = 'x'.repeat(2 ** 21); +words = large(huge, true); +assert.equal(exports.checkString(), huge); +new Uint8Array(memory.buffer)[64] = 121; +assert.equal(exports.checkString(), 'y' + huge.slice(1)); +memory.grow(1); +words = large('after memory growth'); +assert.equal(exports.checkString(), 'after memory growth'); +console.log('String decoder regressions passed'); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/StringDecoderTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/StringDecoderTests.swift new file mode 100644 index 000000000..96449b4de --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/StringDecoderTests.swift @@ -0,0 +1,44 @@ +import Foundation +import SwiftParser +import Testing +@testable import BridgeJSCore +@testable import BridgeJSLink +@testable import TS2Swift + +@Suite struct StringDecoderTests { + @Test(arguments: [false, true]) + func generatedStringDecoder(sharedMemory: Bool) throws { + let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + let fixture = directory.appendingPathComponent("Inputs/MacroSwift/StringReturn.swift") + let collector = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + collector.addSourceFile( + Parser.parse(source: try String(contentsOf: fixture, encoding: .utf8)), + inputFilePath: fixture.path + ) + var linker = BridgeJSLink() + try linker.addSkeletonFile(data: JSONEncoder().encode(collector.finalize())) + let output = try linker.link(sharedMemory: sharedMemory) + guard let node = which("node") else { + Issue.record("Node.js is required for string decoder regression tests") + return + } + try withTemporaryDirectory { temporaryDirectory, _ in + let glue = temporaryDirectory.appendingPathComponent("bridge.js") + try output.outputJs.write(to: glue, atomically: true, encoding: .utf8) + let process = Process() + process.executableURL = node + process.arguments = [ + directory.appendingPathComponent("Inputs/StringDecoderTests.mjs").path, + glue.path, sharedMemory ? "shared" : "unshared", + ] + try process.run() + process.waitUntilExit() + #expect(process.terminationStatus == 0) + } + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index 2529f22d3..7f8b3750d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -297,19 +297,19 @@ extension UserId: _BridgedSwiftAlias, _BridgedSwiftStackType {} #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_acceptTagged") -fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void +fileprivate func bjs_acceptTagged_extern(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Void #else -fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void { +fileprivate func bjs_acceptTagged_extern(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: 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) +@inline(never) fileprivate func bjs_acceptTagged(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Void { + return bjs_acceptTagged_extern(taggedWord0, taggedWord1, taggedWord2) } func _$acceptTagged(_ tagged: Tagged) throws(JSException) -> Void { - tagged.bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in - bjs_acceptTagged(taggedBytes, taggedLength) + tagged.bridgeJSWithLoweredParameter { (taggedWord0, taggedWord1, taggedWord2) in + bjs_acceptTagged(taggedWord0, taggedWord1, taggedWord2) } if let error = _swift_js_take_exception() { throw error @@ -318,19 +318,19 @@ func _$acceptTagged(_ tagged: Tagged) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_acceptOptionalTagged") -fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedBytes: Int32, _ taggedLength: Int32) -> Void +fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Void #else -fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedBytes: Int32, _ taggedLength: Int32) -> Void { +fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: 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) +@inline(never) fileprivate func bjs_acceptOptionalTagged(_ taggedIsSome: Int32, _ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Void { + return bjs_acceptOptionalTagged_extern(taggedIsSome, taggedWord0, taggedWord1, taggedWord2) } func _$acceptOptionalTagged(_ tagged: Optional) throws(JSException) -> Void { - tagged.bridgeJSWithLoweredParameter { (taggedIsSome, taggedBytes, taggedLength) in - bjs_acceptOptionalTagged(taggedIsSome, taggedBytes, taggedLength) + tagged.bridgeJSWithLoweredParameter { (taggedIsSome, taggedWord0, taggedWord1, taggedWord2) in + bjs_acceptOptionalTagged(taggedIsSome, taggedWord0, taggedWord1, taggedWord2) } if let error = _swift_js_take_exception() { throw error @@ -339,19 +339,19 @@ func _$acceptOptionalTagged(_ tagged: Optional) throws(JSException) -> V #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_roundtripTagged") -fileprivate func bjs_roundtripTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Int32 +fileprivate func bjs_roundtripTagged_extern(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Int32 #else -fileprivate func bjs_roundtripTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Int32 { +fileprivate func bjs_roundtripTagged_extern(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: 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) +@inline(never) fileprivate func bjs_roundtripTagged(_ taggedWord0: Int32, _ taggedWord1: Int32, _ taggedWord2: Int32) -> Int32 { + return bjs_roundtripTagged_extern(taggedWord0, taggedWord1, taggedWord2) } func _$roundtripTagged(_ tagged: Tagged) throws(JSException) -> Tagged { - let ret0 = tagged.bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in - let ret = bjs_roundtripTagged(taggedBytes, taggedLength) + let ret0 = tagged.bridgeJSWithLoweredParameter { (taggedWord0, taggedWord1, taggedWord2) in + let ret = bjs_roundtripTagged(taggedWord0, taggedWord1, taggedWord2) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index ae03fc475..2d0143ea9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -423,20 +423,20 @@ func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) 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 +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + promise_resolve_TestModule_SS(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } @@ -571,20 +571,20 @@ func _$Promise_resolve_14AsyncDirectionO(_ promise: JSObject, _ value: AsyncDire #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 +fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_TestModule_10AsyncThemeO(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_10AsyncThemeO_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_10AsyncThemeO(_ promise: JSObject, _ value: AsyncTheme) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_10AsyncThemeO(promiseValue, valueBytes, valueLength) + promise_resolve_TestModule_10AsyncThemeO(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } @@ -614,20 +614,20 @@ func _$Promise_resolve_Sq14AsyncDirectionO(_ promise: JSObject, _ value: Optiona #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 +fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_Sq10AsyncThemeO_extern(promise, valueIsSome, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_Sq10AsyncThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_Sq10AsyncThemeO(promiseValue, valueIsSome, valueBytes, valueLength) + promise_resolve_TestModule_Sq10AsyncThemeO(promiseValue, valueIsSome, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift index 509f79578..42cb4f52b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift @@ -124,14 +124,14 @@ public func _invoke_swift_closure_TestModule_10TestModules8JSObjectC_y(_ boxPtr: #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 +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -151,9 +151,9 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -479,14 +479,14 @@ func _$asyncRoundTripInt(_ v: Int) async throws(JSException) -> Int { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_asyncRoundTripString") -fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void #else -fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { +fileprivate func bjs_asyncRoundTripString_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_asyncRoundTripString(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - return bjs_asyncRoundTripString_extern(resolveRef, rejectRef, vBytes, vLength) +@inline(never) fileprivate func bjs_asyncRoundTripString(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { + return bjs_asyncRoundTripString_extern(resolveRef, rejectRef, vWord0, vWord1, vWord2) } func _$asyncRoundTripString(_ v: String) async throws(JSException) -> String { @@ -495,8 +495,8 @@ func _$asyncRoundTripString(_ v: String) async throws(JSException) -> String { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - v.bridgeJSWithLoweredParameter { (vBytes, vLength) in - bjs_asyncRoundTripString(resolveRef, rejectRef, vBytes, vLength) + v.bridgeJSWithLoweredParameter { (vWord0, vWord1, vWord2) in + bjs_asyncRoundTripString(resolveRef, rejectRef, vWord0, vWord1, vWord2) } } return resolved diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index 2cee26721..da2e3916f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -528,19 +528,19 @@ extension Ratio: BridgedSwiftGenericBridgeable { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_takesFeatureFlag") -fileprivate func bjs_takesFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Void +fileprivate func bjs_takesFeatureFlag_extern(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Void #else -fileprivate func bjs_takesFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Void { +fileprivate func bjs_takesFeatureFlag_extern(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_takesFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Void { - return bjs_takesFeatureFlag_extern(flagBytes, flagLength) +@inline(never) fileprivate func bjs_takesFeatureFlag(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Void { + return bjs_takesFeatureFlag_extern(flagWord0, flagWord1, flagWord2) } func _$takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void { - flag.bridgeJSWithLoweredParameter { (flagBytes, flagLength) in - bjs_takesFeatureFlag(flagBytes, flagLength) + flag.bridgeJSWithLoweredParameter { (flagWord0, flagWord1, flagWord2) in + bjs_takesFeatureFlag(flagWord0, flagWord1, flagWord2) } 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 ecb1512cf..8a9a11197 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -321,19 +321,19 @@ func _$genericRoundTrip(_ value: T) throws(JSE #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_genericParse") -fileprivate func bjs_genericParse_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void +fileprivate func bjs_genericParse_extern(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: Int32, _ _generic0TypeId: Int32) -> Void #else -fileprivate func bjs_genericParse_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { +fileprivate func bjs_genericParse_extern(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: 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) +@inline(never) fileprivate func bjs_genericParse(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_genericParse_extern(jsonWord0, jsonWord1, jsonWord2, _generic0TypeId) } func _$genericParse(_ json: String) throws(JSException) -> T { - json.bridgeJSWithLoweredParameter { (jsonBytes, jsonLength) in - bjs_genericParse(jsonBytes, jsonLength, T.bridgeJSTypeID) + json.bridgeJSWithLoweredParameter { (jsonWord0, jsonWord1, jsonWord2) in + bjs_genericParse(jsonWord0, jsonWord1, jsonWord2, T.bridgeJSTypeID) } if let error = _swift_js_take_exception() { throw error @@ -514,21 +514,21 @@ func _$constrainedComposition Int32 +fileprivate func bjs_GenericPairFactory_init_extern(_ tagWord0: Int32, _ tagWord1: Int32, _ tagWord2: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 #else -fileprivate func bjs_GenericPairFactory_init_extern(_ tagBytes: Int32, _ tagLength: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { +fileprivate func bjs_GenericPairFactory_init_extern(_ tagWord0: Int32, _ tagWord1: Int32, _ tagWord2: 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) +@inline(never) fileprivate func bjs_GenericPairFactory_init(_ tagWord0: Int32, _ tagWord1: Int32, _ tagWord2: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + return bjs_GenericPairFactory_init_extern(tagWord0, tagWord1, tagWord2, _generic0TypeId, _generic1TypeId) } func _$GenericPairFactory_init(_ tag: String, _ first: T, _ second: U) throws(JSException) -> JSObject { - let ret0 = tag.bridgeJSWithLoweredParameter { (tagBytes, tagLength) in + let ret0 = tag.bridgeJSWithLoweredParameter { (tagWord0, tagWord1, tagWord2) in second.bridgeJSStackPush() first.bridgeJSStackPush() - let ret = bjs_GenericPairFactory_init(tagBytes, tagLength, T.bridgeJSTypeID, U.bridgeJSTypeID) + let ret = bjs_GenericPairFactory_init(tagWord0, tagWord1, tagWord2, T.bridgeJSTypeID, U.bridgeJSTypeID) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift index 68afce080..14d4b1907 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift @@ -20,20 +20,20 @@ func _$console_get() throws(JSException) -> JSConsole { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void #else -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { - return bjs_JSConsole_log_extern(self, messageBytes, messageLength) +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { + return bjs_JSConsole_log_extern(self, messageWord0, messageWord1, messageWord2) } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { - message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + message.bridgeJSWithLoweredParameter { (messageWord0, messageWord1, messageWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_JSConsole_log(selfValue, messageBytes, messageLength) + bjs_JSConsole_log(selfValue, messageWord0, messageWord1, messageWord2) } if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift index 4ba7a26fe..896c4e36d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift @@ -20,19 +20,19 @@ func _$console_get() throws(JSException) -> JSConsole { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_parseInt") -fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 +fileprivate func bjs_parseInt_extern(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 #else -fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { +fileprivate func bjs_parseInt_extern(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_parseInt(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { - return bjs_parseInt_extern(stringBytes, stringLength) +@inline(never) fileprivate func bjs_parseInt(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 { + return bjs_parseInt_extern(stringWord0, stringWord1, stringWord2) } func _$parseInt(_ string: String) throws(JSException) -> Double { - let ret0 = string.bridgeJSWithLoweredParameter { (stringBytes, stringLength) in - let ret = bjs_parseInt(stringBytes, stringLength) + let ret0 = string.bridgeJSWithLoweredParameter { (stringWord0, stringWord1, stringWord2) in + let ret = bjs_parseInt(stringWord0, stringWord1, stringWord2) return ret } let ret = ret0 @@ -44,20 +44,20 @@ func _$parseInt(_ string: String) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void #else -fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { - return bjs_JSConsole_log_extern(self, messageBytes, messageLength) +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { + return bjs_JSConsole_log_extern(self, messageWord0, messageWord1, messageWord2) } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { - message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + message.bridgeJSWithLoweredParameter { (messageWord0, messageWord1, messageWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_JSConsole_log(selfValue, messageBytes, messageLength) + bjs_JSConsole_log(selfValue, messageWord0, messageWord1, messageWord2) } if let error = _swift_js_take_exception() { throw error @@ -66,14 +66,14 @@ func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WebSocket_init") -fileprivate func bjs_WebSocket_init_extern(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 +fileprivate func bjs_WebSocket_init_extern(_ urlWord0: Int32, _ urlWord1: Int32, _ urlWord2: Int32) -> Int32 #else -fileprivate func bjs_WebSocket_init_extern(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 { +fileprivate func bjs_WebSocket_init_extern(_ urlWord0: Int32, _ urlWord1: Int32, _ urlWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WebSocket_init(_ urlBytes: Int32, _ urlLength: Int32) -> Int32 { - return bjs_WebSocket_init_extern(urlBytes, urlLength) +@inline(never) fileprivate func bjs_WebSocket_init(_ urlWord0: Int32, _ urlWord1: Int32, _ urlWord2: Int32) -> Int32 { + return bjs_WebSocket_init_extern(urlWord0, urlWord1, urlWord2) } #if arch(wasm32) @@ -89,8 +89,8 @@ fileprivate func bjs_WebSocket_close_extern(_ self: Int32) -> Void { } func _$WebSocket_init(_ url: String) throws(JSException) -> JSObject { - let ret0 = url.bridgeJSWithLoweredParameter { (urlBytes, urlLength) in - let ret = bjs_WebSocket_init(urlBytes, urlLength) + let ret0 = url.bridgeJSWithLoweredParameter { (urlWord0, urlWord1, urlWord2) in + let ret = bjs_WebSocket_init(urlWord0, urlWord1, urlWord2) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift index 12abbd1e6..a501dd2f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift @@ -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) -> Int32 +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 #else -fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 { +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_borrowedStringAroundStackParams(_ sBytes: Int32, _ sLength: Int32) -> Int32 { - return bjs_borrowedStringAroundStackParams_extern(sBytes, sLength) +@inline(never) fileprivate func bjs_borrowedStringAroundStackParams(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 { + return bjs_borrowedStringAroundStackParams_extern(sWord0, sWord1, sWord2) } func _$borrowedStringAroundStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> Int { - let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in + let ret0 = s.bridgeJSWithLoweredParameter { (sWord0, sWord1, sWord2) in let _ = b.bridgeJSLowerParameter() let _ = a.bridgeJSLowerParameter() - let ret = bjs_borrowedStringAroundStackParams(sBytes, sLength) + let ret = bjs_borrowedStringAroundStackParams(sWord0, sWord1, sWord2) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift index f82632737..3adaeb88f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift @@ -136,14 +136,14 @@ fileprivate func bjs_WeirdNaming_Any_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_normalProperty_set") -fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeirdNaming_normalProperty_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeirdNaming_normalProperty_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -172,14 +172,14 @@ fileprivate func bjs_WeirdNaming__123invalidStart_set_extern(_ self: Int32, _ ne #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_spaces_set") -fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeirdNaming_property_with_spaces_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeirdNaming_property_with_spaces_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -196,38 +196,38 @@ fileprivate func bjs_WeirdNaming__specialChar_set_extern(_ self: Int32, _ newVal #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_constructor_set") -fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeirdNaming_constructor_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeirdNaming_constructor_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_for_set") -fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeirdNaming_for_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeirdNaming_for_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_any_set") -fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeirdNaming_any_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeirdNaming_any_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -327,9 +327,9 @@ func _$WeirdNaming_Any_get(_ self: JSObject) throws(JSException) -> String { } func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_normalProperty_set(selfValue, newValueBytes, newValueLength) + bjs_WeirdNaming_normalProperty_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -355,9 +355,9 @@ func _$WeirdNaming__123invalidStart_set(_ self: JSObject, _ newValue: Bool) thro } func _$WeirdNaming_property_with_spaces_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueBytes, newValueLength) + bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -374,9 +374,9 @@ func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws } func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_constructor_set(selfValue, newValueBytes, newValueLength) + bjs_WeirdNaming_constructor_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -384,9 +384,9 @@ func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws( } func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_for_set(selfValue, newValueBytes, newValueLength) + bjs_WeirdNaming_for_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -394,9 +394,9 @@ func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSExcept } func _$WeirdNaming_any_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_any_set(selfValue, newValueBytes, newValueLength) + bjs_WeirdNaming_any_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift index 37009f318..95e020b23 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift @@ -20,14 +20,14 @@ func _$returnAnimatable() throws(JSException) -> Animatable { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_init") -fileprivate func bjs_Greeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 +fileprivate func bjs_Greeter_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Int32 #else -fileprivate func bjs_Greeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 { +fileprivate func bjs_Greeter_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> Int32 { - return bjs_Greeter_init_extern(nameBytes, nameLength) +@inline(never) fileprivate func bjs_Greeter_init(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Int32 { + return bjs_Greeter_init_extern(nameWord0, nameWord1, nameWord2) } #if arch(wasm32) @@ -56,14 +56,14 @@ fileprivate func bjs_Greeter_age_get_extern(_ self: Int32) -> Float64 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_name_set") -fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_Greeter_name_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_Greeter_name_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -80,19 +80,19 @@ fileprivate func bjs_Greeter_greet_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_changeName") -fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void #else -fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Greeter_changeName(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - return bjs_Greeter_changeName_extern(self, nameBytes, nameLength) +@inline(never) fileprivate func bjs_Greeter_changeName(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { + return bjs_Greeter_changeName_extern(self, nameWord0, nameWord1, nameWord2) } func _$Greeter_init(_ name: String) throws(JSException) -> JSObject { - let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in - let ret = bjs_Greeter_init(nameBytes, nameLength) + let ret0 = name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in + let ret = bjs_Greeter_init(nameWord0, nameWord1, nameWord2) return ret } let ret = ret0 @@ -121,9 +121,9 @@ func _$Greeter_age_get(_ self: JSObject) throws(JSException) -> Double { } func _$Greeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_Greeter_name_set(selfValue, newValueBytes, newValueLength) + bjs_Greeter_name_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -140,9 +140,9 @@ func _$Greeter_greet(_ self: JSObject) throws(JSException) -> String { } func _$Greeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { - name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_Greeter_changeName(selfValue, nameBytes, nameLength) + bjs_Greeter_changeName(selfValue, nameWord0, nameWord1, nameWord2) } if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift index 4baf8d0f0..69de3b2ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift @@ -40,19 +40,19 @@ func _$localDefaultExport_get() throws(JSException) -> JSObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_nodeBasename") -fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +fileprivate func bjs_nodeBasename_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 #else -fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { +fileprivate func bjs_nodeBasename_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: 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) +@inline(never) fileprivate func bjs_nodeBasename(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 { + return bjs_nodeBasename_extern(pathWord0, pathWord1, pathWord2) } func _$nodeBasename(_ path: String) throws(JSException) -> String { - let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in - let ret = bjs_nodeBasename(pathBytes, pathLength) + let ret0 = path.bridgeJSWithLoweredParameter { (pathWord0, pathWord1, pathWord2) in + let ret = bjs_nodeBasename(pathWord0, pathWord1, pathWord2) return ret } let ret = ret0 @@ -64,19 +64,19 @@ func _$nodeBasename(_ path: String) throws(JSException) -> String { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_nodeDirname") -fileprivate func bjs_nodeDirname_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +fileprivate func bjs_nodeDirname_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 #else -fileprivate func bjs_nodeDirname_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { +fileprivate func bjs_nodeDirname_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: 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) +@inline(never) fileprivate func bjs_nodeDirname(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 { + return bjs_nodeDirname_extern(pathWord0, pathWord1, pathWord2) } func _$nodeDirname(_ path: String) throws(JSException) -> String { - let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in - let ret = bjs_nodeDirname(pathBytes, pathLength) + let ret0 = path.bridgeJSWithLoweredParameter { (pathWord0, pathWord1, pathWord2) in + let ret = bjs_nodeDirname(pathWord0, pathWord1, pathWord2) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift index 7780b5eb0..459130153 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift @@ -40,20 +40,20 @@ func _$kebabCaseFunction() throws(JSException) -> Int { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_joinPaths") -fileprivate func bjs_joinPaths_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 +fileprivate func bjs_joinPaths_extern(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: Int32) -> Int32 #else -fileprivate func bjs_joinPaths_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { +fileprivate func bjs_joinPaths_extern(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: 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) +@inline(never) fileprivate func bjs_joinPaths(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: Int32) -> Int32 { + return bjs_joinPaths_extern(lhsWord0, lhsWord1, lhsWord2, rhsWord0, rhsWord1, rhsWord2) } 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) + let ret0 = lhs.bridgeJSWithLoweredParameter { (lhsWord0, lhsWord1, lhsWord2) in + let ret1 = rhs.bridgeJSWithLoweredParameter { (rhsWord0, rhsWord1, rhsWord2) in + let ret = bjs_joinPaths(lhsWord0, lhsWord1, lhsWord2, rhsWord0, rhsWord1, rhsWord2) return ret } return ret1 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index f45a0bb1e..c35ea24e6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -484,14 +484,14 @@ fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutabl #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_init") -fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullWord0: Int32, _ valueOrNullWord1: Int32, _ valueOrNullWord2: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedWord0: Int32, _ valueOrUndefinedWord1: Int32, _ valueOrUndefinedWord2: Int32) -> Int32 #else -fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 { +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullWord0: Int32, _ valueOrNullWord1: Int32, _ valueOrNullWord2: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedWord0: Int32, _ valueOrUndefinedWord1: Int32, _ valueOrUndefinedWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_init(_ valueOrNullIsSome: Int32, _ valueOrNullBytes: Int32, _ valueOrNullLength: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedBytes: Int32, _ valueOrUndefinedLength: Int32) -> Int32 { - return bjs_WithOptionalJSClass_init_extern(valueOrNullIsSome, valueOrNullBytes, valueOrNullLength, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) +@inline(never) fileprivate func bjs_WithOptionalJSClass_init(_ valueOrNullIsSome: Int32, _ valueOrNullWord0: Int32, _ valueOrNullWord1: Int32, _ valueOrNullWord2: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedWord0: Int32, _ valueOrUndefinedWord1: Int32, _ valueOrUndefinedWord2: Int32) -> Int32 { + return bjs_WithOptionalJSClass_init_extern(valueOrNullIsSome, valueOrNullWord0, valueOrNullWord1, valueOrNullWord2, valueOrUndefinedIsSome, valueOrUndefinedWord0, valueOrUndefinedWord1, valueOrUndefinedWord2) } #if arch(wasm32) @@ -604,26 +604,26 @@ fileprivate func bjs_WithOptionalJSClass_childOrNull_get_extern(_ self: Int32) - #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrNull_set") -fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WithOptionalJSClass_stringOrNull_set_extern(self, newValueIsSome, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrNull_set_extern(self, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrUndefined_set") -fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WithOptionalJSClass_stringOrUndefined_set_extern(self, newValueIsSome, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrUndefined_set_extern(self, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -712,26 +712,26 @@ fileprivate func bjs_WithOptionalJSClass_childOrNull_set_extern(_ self: Int32, _ #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrNull") -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return bjs_WithOptionalJSClass_roundTripStringOrNull_extern(self, valueIsSome, valueBytes, valueLength) +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrNull_extern(self, valueIsSome, valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrUndefined") -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(self, valueIsSome, valueBytes, valueLength) +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(self, valueIsSome, valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @@ -819,9 +819,9 @@ fileprivate func bjs_WithOptionalJSClass_roundTripChildOrNull_extern(_ self: Int } func _$WithOptionalJSClass_init(_ valueOrNull: Optional, _ valueOrUndefined: JSUndefinedOr) throws(JSException) -> JSObject { - let ret0 = valueOrNull.bridgeJSWithLoweredParameter { (valueOrNullIsSome, valueOrNullBytes, valueOrNullLength) in - let ret1 = valueOrUndefined.bridgeJSWithLoweredParameter { (valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) in - let ret = bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullBytes, valueOrNullLength, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedLength) + let ret0 = valueOrNull.bridgeJSWithLoweredParameter { (valueOrNullIsSome, valueOrNullWord0, valueOrNullWord1, valueOrNullWord2) in + let ret1 = valueOrUndefined.bridgeJSWithLoweredParameter { (valueOrUndefinedIsSome, valueOrUndefinedWord0, valueOrUndefinedWord1, valueOrUndefinedWord2) in + let ret = bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullWord0, valueOrNullWord1, valueOrNullWord2, valueOrUndefinedIsSome, valueOrUndefinedWord0, valueOrUndefinedWord1, valueOrUndefinedWord2) return ret } return ret1 @@ -915,9 +915,9 @@ func _$WithOptionalJSClass_childOrNull_get(_ self: JSObject) throws(JSException) } func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueBytes, newValueLength) + bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -925,9 +925,9 @@ func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Option } func _$WithOptionalJSClass_stringOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueBytes, newValueLength) + bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -998,9 +998,9 @@ func _$WithOptionalJSClass_childOrNull_set(_ self: JSObject, _ newValue: Optiona } func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueBytes, valueLength) + bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error @@ -1009,9 +1009,9 @@ func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Opti } func _$WithOptionalJSClass_roundTripStringOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueBytes, valueLength) + bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueWord0, valueWord1, valueWord2) } 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 ec3d2f65a..a91524da5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -5,9 +5,9 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { } func onValueChanged(_ value: String) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_onValueChanged(jsObjectValue, valueBytes, valueLength) + bjs_MyViewControllerDelegate_onValueChanged(jsObjectValue, valueWord0, valueWord1, valueWord2) } } @@ -19,10 +19,10 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { } func onLabelUpdated(_ prefix: String, _ suffix: String) -> Void { - prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in - suffix.bridgeJSWithLoweredParameter { (suffixBytes, suffixLength) in + prefix.bridgeJSWithLoweredParameter { (prefixWord0, prefixWord1, prefixWord2) in + suffix.bridgeJSWithLoweredParameter { (suffixWord0, suffixWord1, suffixWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_onLabelUpdated(jsObjectValue, prefixBytes, prefixLength, suffixBytes, suffixLength) + bjs_MyViewControllerDelegate_onLabelUpdated(jsObjectValue, prefixWord0, prefixWord1, prefixWord2, suffixWord0, suffixWord1, suffixWord2) } } } @@ -103,9 +103,9 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_optionalName_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + bjs_MyViewControllerDelegate_optionalName_set(jsObjectValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } } } @@ -117,9 +117,9 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_optionalRawEnum_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + bjs_MyViewControllerDelegate_optionalRawEnum_set(jsObjectValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } } } @@ -131,9 +131,9 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { return ExampleEnum.bridgeJSLiftReturn(ret) } set { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_MyViewControllerDelegate_rawStringEnum_set(jsObjectValue, newValueBytes, newValueLength) + bjs_MyViewControllerDelegate_rawStringEnum_set(jsObjectValue, newValueWord0, newValueWord1, newValueWord2) } } } @@ -239,14 +239,14 @@ fileprivate func bjs_MyViewControllerDelegate_onSomethingHappened_extern(_ jsObj #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onValueChanged") -fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onValueChanged_extern(_ jsObject: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_onValueChanged(_ jsObject: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return bjs_MyViewControllerDelegate_onValueChanged_extern(jsObject, valueBytes, valueLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onValueChanged(_ jsObject: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_onValueChanged_extern(jsObject, valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @@ -263,14 +263,14 @@ fileprivate func bjs_MyViewControllerDelegate_onCountUpdated_extern(_ jsObject: #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onLabelUpdated") -fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32, _ suffixWord0: Int32, _ suffixWord1: Int32, _ suffixWord2: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated_extern(_ jsObject: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32, _ suffixWord0: Int32, _ suffixWord1: Int32, _ suffixWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated(_ jsObject: Int32, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { - return bjs_MyViewControllerDelegate_onLabelUpdated_extern(jsObject, prefixBytes, prefixLength, suffixBytes, suffixLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_onLabelUpdated(_ jsObject: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32, _ suffixWord0: Int32, _ suffixWord1: Int32, _ suffixWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_onLabelUpdated_extern(jsObject, prefixWord0, prefixWord1, prefixWord2, suffixWord0, suffixWord1, suffixWord2) } #if arch(wasm32) @@ -419,14 +419,14 @@ fileprivate func bjs_MyViewControllerDelegate_optionalName_get_extern(_ jsObject #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalName_set") -fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_MyViewControllerDelegate_optionalName_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalName_set_extern(jsObject, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -443,14 +443,14 @@ fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get_extern(_ jsObj #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalRawEnum_set") -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(jsObject, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -467,14 +467,14 @@ fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get_extern(_ jsObjec #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_rawStringEnum_set") -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_MyViewControllerDelegate_rawStringEnum_set_extern(jsObject, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_rawStringEnum_set_extern(jsObject, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift index f519c3306..f00cbd49c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift @@ -23,19 +23,19 @@ public func _bjs_roundtripString(_ aBytes: Int32, _ aLength: Int32) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_checkString") -fileprivate func bjs_checkString_extern(_ aBytes: Int32, _ aLength: Int32) -> Void +fileprivate func bjs_checkString_extern(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32) -> Void #else -fileprivate func bjs_checkString_extern(_ aBytes: Int32, _ aLength: Int32) -> Void { +fileprivate func bjs_checkString_extern(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { - return bjs_checkString_extern(aBytes, aLength) +@inline(never) fileprivate func bjs_checkString(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32) -> Void { + return bjs_checkString_extern(aWord0, aWord1, aWord2) } func _$checkString(_ a: String) throws(JSException) -> Void { - a.bridgeJSWithLoweredParameter { (aBytes, aLength) in - bjs_checkString(aBytes, aLength) + a.bridgeJSWithLoweredParameter { (aWord0, aWord1, aWord2) in + bjs_checkString(aWord0, aWord1, aWord2) } if let error = _swift_js_take_exception() { throw error @@ -44,20 +44,20 @@ func _$checkString(_ a: String) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_checkStringWithLength") -fileprivate func bjs_checkStringWithLength_extern(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void +fileprivate func bjs_checkStringWithLength_extern(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32, _ b: Float64) -> Void #else -fileprivate func bjs_checkStringWithLength_extern(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void { +fileprivate func bjs_checkStringWithLength_extern(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32, _ b: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_checkStringWithLength(_ aBytes: Int32, _ aLength: Int32, _ b: Float64) -> Void { - return bjs_checkStringWithLength_extern(aBytes, aLength, b) +@inline(never) fileprivate func bjs_checkStringWithLength(_ aWord0: Int32, _ aWord1: Int32, _ aWord2: Int32, _ b: Float64) -> Void { + return bjs_checkStringWithLength_extern(aWord0, aWord1, aWord2, b) } func _$checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void { - a.bridgeJSWithLoweredParameter { (aBytes, aLength) in + a.bridgeJSWithLoweredParameter { (aWord0, aWord1, aWord2) in let bValue = b.bridgeJSLowerParameter() - bjs_checkStringWithLength(aBytes, aLength, bValue) + bjs_checkStringWithLength(aWord0, aWord1, aWord2, bValue) } 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 af740495c..152b41102 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -64,14 +64,14 @@ public func _invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpSta #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO") -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -91,9 +91,9 @@ private enum _BJS_Closure_10TestModule5ThemeO_5ThemeO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -387,14 +387,14 @@ public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -414,9 +414,9 @@ private enum _BJS_Closure_10TestModuleKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -471,14 +471,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleKSS_Sb(_ boxPtr: Unsafe #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -498,9 +498,9 @@ private enum _BJS_Closure_10TestModuleKSS_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Int in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleKSS_Si(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Si(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -555,14 +555,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleKSS_Si(_ boxPtr: Unsafe #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_TestModule_10TestModuleSS_SS_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSS_SS_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -582,9 +582,9 @@ private enum _BJS_Closure_10TestModuleSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -942,14 +942,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10Htt #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(callback, param0IsSome, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(callback, param0IsSome, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -969,9 +969,9 @@ private enum _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Word0, param0Word1, param0Word2) } return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -1263,14 +1263,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9Direct #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSS_SqSS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(callback, param0IsSome, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(callback, param0IsSome, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1290,9 +1290,9 @@ private enum _BJS_Closure_10TestModuleSqSS_SqSS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Word0, param0Word1, param0Word2) } return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -1584,14 +1584,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi(_ boxPtr: Uns #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1616,9 +1616,9 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -1727,14 +1727,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO(_ box #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1759,9 +1759,9 @@ private enum _BJS_Closure_10TestModuleYaSS_6AnimalV { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -1799,14 +1799,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleYaSS_6AnimalV(_ boxPtr: #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1831,9 +1831,9 @@ private enum _BJS_Closure_10TestModuleYaSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleYaSS_SS(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -2057,14 +2057,14 @@ public func _invoke_swift_closure_TestModule_10TestModules9APIResultO_y(_ boxPtr #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 +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2084,9 +2084,9 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -2741,20 +2741,20 @@ func _$Promise_reject(_ promise: JSObject, _ value: JSValue) 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 +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + promise_resolve_TestModule_SS(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift index 3634ad491..5c22db7f2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift @@ -1,13 +1,13 @@ #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -27,9 +27,9 @@ private enum _BJS_Closure_10TestModuleKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -148,14 +148,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeM #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 +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -180,9 +180,9 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -282,14 +282,14 @@ public func _invoke_swift_closure_TestModule_10TestModules7JSValueV_y(_ boxPtr: #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 +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -309,9 +309,9 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -390,20 +390,20 @@ func _$Promise_reject(_ promise: JSObject, _ value: JSValue) 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 +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + promise_resolve_TestModule_SS(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index b1cfb68aa..422e26dd9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -15,6 +15,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -432,8 +434,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -441,8 +443,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -467,8 +469,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -536,11 +538,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -611,19 +613,19 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(obj); }; const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_acceptTagged"] = function bjs_acceptTagged(taggedBytes, taggedCount) { + TestModule["bjs_acceptTagged"] = function bjs_acceptTagged(taggedWord0, taggedWord1, taggedWord2) { try { - const string = decodeString(taggedBytes, taggedCount); + const string = decodeString(taggedWord0, taggedWord1, taggedWord2); imports.acceptTagged(string); } catch (error) { setException(error); } } - TestModule["bjs_acceptOptionalTagged"] = function bjs_acceptOptionalTagged(taggedIsSome, taggedBytes, taggedCount) { + TestModule["bjs_acceptOptionalTagged"] = function bjs_acceptOptionalTagged(taggedIsSome, taggedWord0, taggedWord1, taggedWord2) { try { let optResult; if (taggedIsSome) { - const string = decodeString(taggedBytes, taggedCount); + const string = decodeString(taggedWord0, taggedWord1, taggedWord2); optResult = string; } else { optResult = null; @@ -633,9 +635,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_roundtripTagged"] = function bjs_roundtripTagged(taggedBytes, taggedCount) { + TestModule["bjs_roundtripTagged"] = function bjs_roundtripTagged(taggedWord0, taggedWord1, taggedWord2) { try { - const string = decodeString(taggedBytes, taggedCount); + const string = decodeString(taggedWord0, taggedWord1, taggedWord2); let ret = imports.roundtripTagged(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -678,10 +680,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index fa9095cd8..5a7dc255e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,7 +44,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -168,11 +170,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -290,10 +292,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 6d3992ce5..bb61c4fb5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -22,6 +22,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -495,8 +497,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -504,8 +506,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -530,8 +532,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -606,11 +608,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -740,10 +742,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index c025cf4f0..b657a2188 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -19,6 +19,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -407,8 +409,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -416,8 +418,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -442,8 +444,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -504,9 +506,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_SS"] = function(promise, valueBytes, valueCount) { + bjs["promise_resolve_TestModule_SS"] = function(promise, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); } catch (error) { setException(error); @@ -555,9 +557,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_10AsyncThemeO"] = function(promise, valueBytes, valueCount) { + bjs["promise_resolve_TestModule_10AsyncThemeO"] = function(promise, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); } catch (error) { setException(error); @@ -570,11 +572,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_Sq10AsyncThemeO"] = function(promise, valueIsSome, valueBytes, valueCount) { + bjs["promise_resolve_TestModule_Sq10AsyncThemeO"] = function(promise, valueIsSome, valueWord0, valueWord1, valueWord2) { try { let optResult; if (valueIsSome) { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); optResult = string; } else { optResult = null; @@ -660,11 +662,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -724,10 +726,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 49b2ff88b..d16d071b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -16,6 +16,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -172,8 +174,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -181,8 +183,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -207,8 +209,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -306,11 +308,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -370,10 +372,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index 96c0d11e8..cc7b29f42 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -131,7 +133,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -154,8 +156,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -163,8 +165,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -189,8 +191,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -257,11 +259,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -365,10 +367,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules8JSObjectC_y); } - bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string); } catch (error) { setException(error); @@ -479,10 +481,10 @@ export async function createInstantiator(options, swift) { const reject = swift.memory.getObject(rejectRef); imports.asyncRoundTripInt(v).then(resolve, reject); } - TestModule["bjs_asyncRoundTripString"] = function bjs_asyncRoundTripString(resolveRef, rejectRef, vBytes, vCount) { + TestModule["bjs_asyncRoundTripString"] = function bjs_asyncRoundTripString(resolveRef, rejectRef, vWord0, vWord1, vWord2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const string = decodeString(vBytes, vCount); + const string = decodeString(vWord0, vWord1, vWord2); imports.asyncRoundTripString(string).then(resolve, reject); } TestModule["bjs_asyncRoundTripBool"] = function bjs_asyncRoundTripBool(resolveRef, rejectRef, v) { @@ -502,10 +504,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index eea340c35..406c5da24 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -131,7 +133,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -154,8 +156,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -163,8 +165,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -189,8 +191,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -257,11 +259,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -398,10 +400,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index ecdb0b059..3d0a66cc3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -56,8 +58,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -65,8 +67,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -91,8 +93,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -239,10 +241,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 9fda637df..35417c66b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -15,6 +15,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -419,8 +421,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -428,8 +430,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -454,8 +456,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -537,11 +539,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -617,10 +619,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 8ccda3c19..1b796f0de 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -399,8 +401,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -408,8 +410,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -434,8 +436,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -510,11 +512,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -592,10 +594,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 6d23d394f..0dae550a8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -15,6 +15,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -56,8 +58,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -65,8 +67,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -91,8 +93,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -256,10 +258,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index d8bc06fcf..897f9e772 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -215,10 +217,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 66f85760c..afe2e8ac7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -90,6 +90,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -994,8 +996,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -1003,8 +1005,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -1029,8 +1031,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -1105,11 +1107,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -1177,10 +1179,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index 2b36953bb..4b71ac219 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -16,6 +16,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -84,8 +86,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -93,8 +95,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -119,8 +121,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -188,11 +190,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -301,10 +303,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 838e3062b..e87881f55 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -33,6 +33,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -63,8 +65,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -72,8 +74,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -98,8 +100,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -231,10 +233,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index bde5fc31f..c816b3bf0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -45,8 +47,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -54,8 +56,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -80,8 +82,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -149,11 +151,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -239,10 +241,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 0a691374b..f744a43f3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -53,6 +53,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -83,8 +85,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -92,8 +94,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -118,8 +120,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -187,11 +189,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -271,10 +273,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 03f0a8d9a..e43b2bcb9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -34,6 +34,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -168,11 +170,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -252,10 +254,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 09e03e44a..fd3640162 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -84,6 +84,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -459,8 +461,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -468,8 +470,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -494,8 +496,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -563,11 +565,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -626,9 +628,9 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flagBytes, flagCount) { + TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flagWord0, flagWord1, flagWord2) { try { - const string = decodeString(flagBytes, flagCount); + const string = decodeString(flagWord0, flagWord1, flagWord2); imports.takesFeatureFlag(string); } catch (error) { setException(error); @@ -645,10 +647,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js index 85cdb44d4..53690ed6a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js @@ -25,6 +25,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -110,8 +112,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -119,8 +121,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -145,8 +147,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -228,11 +230,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -300,10 +302,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js index a9091e925..e5a43fdc2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -59,8 +61,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -68,8 +70,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -94,8 +96,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -170,11 +172,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -242,10 +244,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js index 6b8ae44b1..5312f0fbd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js @@ -13,6 +13,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -55,8 +57,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -90,8 +92,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -166,11 +168,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -242,10 +244,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 56a31b784..af7fa150c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -280,10 +282,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index 529f1772e..e2f71f878 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -25,6 +25,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -506,8 +508,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -515,8 +517,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -541,8 +543,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -653,11 +655,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -734,10 +736,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_genericParse"] = function bjs_genericParse(jsonBytes, jsonCount, tTypeId) { + TestModule["bjs_genericParse"] = function bjs_genericParse(jsonWord0, jsonWord1, jsonWord2, tTypeId) { try { const codecT = __bjs_codecForTypeId(tTypeId); - const string = decodeString(jsonBytes, jsonCount); + const string = decodeString(jsonWord0, jsonWord1, jsonWord2); let ret = imports.genericParse(string); codecT.lower(ret); } catch (error) { @@ -829,11 +831,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_GenericPairFactory_init"] = function bjs_GenericPairFactory_init(tagBytes, tagCount, tTypeId, uTypeId) { + TestModule["bjs_GenericPairFactory_init"] = function bjs_GenericPairFactory_init(tagWord0, tagWord1, tagWord2, tTypeId, uTypeId) { try { const codecT = __bjs_codecForTypeId(tTypeId); const codecU = __bjs_codecForTypeId(uTypeId); - const string = decodeString(tagBytes, tagCount); + const string = decodeString(tagWord0, tagWord1, tagWord2); const first = codecT.lift(); const second = codecU.lift(); return swift.memory.retain(new imports.GenericPairFactory(string, first, second)); @@ -938,10 +940,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index adb70913c..77dcf0f7a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -215,9 +217,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageBytes, messageCount) { + TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageWord0, messageWord1, messageWord2) { try { - const string = decodeString(messageBytes, messageCount); + const string = decodeString(messageWord0, messageWord1, messageWord2); swift.memory.getObject(self).log(string); } catch (error) { setException(error); @@ -225,10 +227,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 760a6b50c..c5c7221d0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -214,9 +216,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_parseInt"] = function bjs_parseInt(stringBytes, stringCount) { + TestModule["bjs_parseInt"] = function bjs_parseInt(stringWord0, stringWord1, stringWord2) { try { - const string = decodeString(stringBytes, stringCount); + const string = decodeString(stringWord0, stringWord1, stringWord2); let ret = globalThis.parseInt(string); return ret; } catch (error) { @@ -224,17 +226,17 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageBytes, messageCount) { + TestModule["bjs_JSConsole_log"] = function bjs_JSConsole_log(self, messageWord0, messageWord1, messageWord2) { try { - const string = decodeString(messageBytes, messageCount); + const string = decodeString(messageWord0, messageWord1, messageWord2); swift.memory.getObject(self).log(string); } catch (error) { setException(error); } } - TestModule["bjs_WebSocket_init"] = function bjs_WebSocket_init(urlBytes, urlCount) { + TestModule["bjs_WebSocket_init"] = function bjs_WebSocket_init(urlWord0, urlWord1, urlWord2) { try { - const string = decodeString(urlBytes, urlCount); + const string = decodeString(urlWord0, urlWord1, urlWord2); return swift.memory.retain(new globalThis.WebSocket(string)); } catch (error) { setException(error); @@ -250,10 +252,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index 1e1d14696..f33437e89 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -222,10 +224,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index c85aee3af..43901d4a2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -222,10 +224,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index c85aee3af..43901d4a2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -222,10 +224,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index c92ea6ad3..893402b07 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -367,8 +369,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -376,8 +378,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -402,8 +404,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -470,11 +472,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -561,9 +563,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_borrowedStringAroundStackParams"] = function bjs_borrowedStringAroundStackParams(sBytes, sCount) { + TestModule["bjs_borrowedStringAroundStackParams"] = function bjs_borrowedStringAroundStackParams(sWord0, sWord1, sWord2) { try { - const string = decodeString(sBytes, sCount); + const string = decodeString(sWord0, sWord1, sWord2); const optValue = __bjs_codec_Optional_Array_Int.lift(); const arrayResult = __bjs_codec_Array_Int.lift(); let ret = imports.borrowedStringAroundStackParams(string, optValue, arrayResult); @@ -575,10 +577,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 363f6c595..69a851251 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -403,8 +405,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -412,8 +414,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -438,8 +440,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -514,11 +516,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -587,10 +589,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index e8fe5ec10..8909352ce 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -296,9 +298,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_normalProperty_set"] = function bjs_WeirdNaming_normalProperty_set(self, newValueBytes, newValueCount) { + TestModule["bjs_WeirdNaming_normalProperty_set"] = function bjs_WeirdNaming_normalProperty_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self).normalProperty = string; } catch (error) { setException(error); @@ -318,9 +320,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_property_with_spaces_set"] = function bjs_WeirdNaming_property_with_spaces_set(self, newValueBytes, newValueCount) { + TestModule["bjs_WeirdNaming_property_with_spaces_set"] = function bjs_WeirdNaming_property_with_spaces_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self)["property with spaces"] = string; } catch (error) { setException(error); @@ -333,25 +335,25 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WeirdNaming_constructor_set"] = function bjs_WeirdNaming_constructor_set(self, newValueBytes, newValueCount) { + TestModule["bjs_WeirdNaming_constructor_set"] = function bjs_WeirdNaming_constructor_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self).constructor = string; } catch (error) { setException(error); } } - TestModule["bjs_WeirdNaming_for_set"] = function bjs_WeirdNaming_for_set(self, newValueBytes, newValueCount) { + TestModule["bjs_WeirdNaming_for_set"] = function bjs_WeirdNaming_for_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self).for = string; } catch (error) { setException(error); } } - TestModule["bjs_WeirdNaming_any_set"] = function bjs_WeirdNaming_any_set(self, newValueBytes, newValueCount) { + TestModule["bjs_WeirdNaming_any_set"] = function bjs_WeirdNaming_any_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self).Any = string; } catch (error) { setException(error); @@ -388,10 +390,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index 15b48d4b9..0c0f030f7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -215,9 +217,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_Greeter_init"] = function bjs_Greeter_init(nameBytes, nameCount) { + TestModule["bjs_Greeter_init"] = function bjs_Greeter_init(nameWord0, nameWord1, nameWord2) { try { - const string = decodeString(nameBytes, nameCount); + const string = decodeString(nameWord0, nameWord1, nameWord2); return swift.memory.retain(new imports.Greeter(string)); } catch (error) { setException(error); @@ -242,9 +244,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_Greeter_name_set"] = function bjs_Greeter_name_set(self, newValueBytes, newValueCount) { + TestModule["bjs_Greeter_name_set"] = function bjs_Greeter_name_set(self, newValueWord0, newValueWord1, newValueWord2) { try { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); swift.memory.getObject(self).name = string; } catch (error) { setException(error); @@ -259,9 +261,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_Greeter_changeName"] = function bjs_Greeter_changeName(self, nameBytes, nameCount) { + TestModule["bjs_Greeter_changeName"] = function bjs_Greeter_changeName(self, nameWord0, nameWord1, nameWord2) { try { - const string = decodeString(nameBytes, nameCount); + const string = decodeString(nameWord0, nameWord1, nameWord2); swift.memory.getObject(self).changeName(string); } catch (error) { setException(error); @@ -287,10 +289,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index 5eaba3c8f..f730efb98 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -270,10 +272,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js index 6d1b1b6fb..23a5b1635 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js @@ -15,6 +15,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -45,8 +47,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -54,8 +56,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -80,8 +82,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -148,11 +150,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -229,9 +231,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_nodeBasename"] = function bjs_nodeBasename(pathBytes, pathCount) { + TestModule["bjs_nodeBasename"] = function bjs_nodeBasename(pathWord0, pathWord1, pathWord2) { try { - const string = decodeString(pathBytes, pathCount); + const string = decodeString(pathWord0, pathWord1, pathWord2); let ret = __bjs_import_3_basename(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -239,9 +241,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_nodeDirname"] = function bjs_nodeDirname(pathBytes, pathCount) { + TestModule["bjs_nodeDirname"] = function bjs_nodeDirname(pathWord0, pathWord1, pathWord2) { try { - const string = decodeString(pathBytes, pathCount); + const string = decodeString(pathWord0, pathWord1, pathWord2); let ret = __bjs_import_3_dirname(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -295,10 +297,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js index 9428698be..55ef14aa6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js @@ -12,6 +12,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,8 +44,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -51,8 +53,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -77,8 +79,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -145,11 +147,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -226,10 +228,10 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_joinPaths"] = function bjs_joinPaths(lhsBytes, lhsCount, rhsBytes, rhsCount) { + TestModule["bjs_joinPaths"] = function bjs_joinPaths(lhsWord0, lhsWord1, lhsWord2, rhsWord0, rhsWord1, rhsWord2) { try { - const string = decodeString(lhsBytes, lhsCount); - const string1 = decodeString(rhsBytes, rhsCount); + const string = decodeString(lhsWord0, lhsWord1, lhsWord2); + const string1 = decodeString(rhsWord0, rhsWord1, rhsWord2); let ret = __bjs_import_0_join(string, string1); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -239,10 +241,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js index aacf5e61a..589f570cf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -12,6 +12,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,8 +44,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -51,8 +53,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -77,8 +79,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -145,11 +147,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -279,10 +281,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 68ac11976..16219c83c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -61,8 +63,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -70,8 +72,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -96,8 +98,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -172,11 +174,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -244,10 +246,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js index fb061d342..ad3e9096e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -44,8 +46,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -53,8 +55,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -79,8 +81,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -148,11 +150,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -220,10 +222,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index f02f6bcf2..f1ffa766f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -206,10 +208,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 9fe12ff47..99742f97b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -366,8 +368,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -375,8 +377,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -401,8 +403,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -469,11 +471,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -563,10 +565,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 5db38dde5..bed72152c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -214,10 +216,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 66818952b..75697b834 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -222,10 +224,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index a732808a6..c6f2fdffa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -214,10 +216,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js index 082d85f65..79519e8f1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,7 +44,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -266,10 +268,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index ea49220de..2e2667caa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -374,8 +376,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -383,8 +385,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -409,8 +411,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -477,11 +479,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -561,10 +563,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 25bd44d05..33d18909a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -374,8 +376,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -383,8 +385,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -409,8 +411,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -477,11 +479,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -561,10 +563,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index f57c4007b..f46e610cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -182,11 +184,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -258,10 +260,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js index 1f4400ce9..332fc4e42 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -60,8 +62,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -69,8 +71,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -95,8 +97,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -178,11 +180,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -242,10 +244,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index b63f360e9..57c49fd4c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -390,8 +392,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -399,8 +401,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -425,8 +427,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -493,11 +495,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -568,18 +570,18 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(obj); }; const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_WithOptionalJSClass_init"] = function bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullBytes, valueOrNullCount, valueOrUndefinedIsSome, valueOrUndefinedBytes, valueOrUndefinedCount) { + TestModule["bjs_WithOptionalJSClass_init"] = function bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullWord0, valueOrNullWord1, valueOrNullWord2, valueOrUndefinedIsSome, valueOrUndefinedWord0, valueOrUndefinedWord1, valueOrUndefinedWord2) { try { let optResult; if (valueOrNullIsSome) { - const string = decodeString(valueOrNullBytes, valueOrNullCount); + const string = decodeString(valueOrNullWord0, valueOrNullWord1, valueOrNullWord2); optResult = string; } else { optResult = null; } let optResult1; if (valueOrUndefinedIsSome) { - const string1 = decodeString(valueOrUndefinedBytes, valueOrUndefinedCount); + const string1 = decodeString(valueOrUndefinedWord0, valueOrUndefinedWord1, valueOrUndefinedWord2); optResult1 = string1; } else { optResult1 = undefined; @@ -670,11 +672,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueBytes, newValueCount) { + TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) { try { let optResult; if (newValueIsSome) { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); optResult = string; } else { optResult = null; @@ -684,11 +686,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_stringOrUndefined_set"] = function bjs_WithOptionalJSClass_stringOrUndefined_set(self, newValueIsSome, newValueBytes, newValueCount) { + TestModule["bjs_WithOptionalJSClass_stringOrUndefined_set"] = function bjs_WithOptionalJSClass_stringOrUndefined_set(self, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) { try { let optResult; if (newValueIsSome) { - const string = decodeString(newValueBytes, newValueCount); + const string = decodeString(newValueWord0, newValueWord1, newValueWord2); optResult = string; } else { optResult = undefined; @@ -747,11 +749,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueBytes, valueCount) { + TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueWord0, valueWord1, valueWord2) { try { let optResult; if (valueIsSome) { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); optResult = string; } else { optResult = null; @@ -763,11 +765,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_roundTripStringOrUndefined"] = function bjs_WithOptionalJSClass_roundTripStringOrUndefined(self, valueIsSome, valueBytes, valueCount) { + TestModule["bjs_WithOptionalJSClass_roundTripStringOrUndefined"] = function bjs_WithOptionalJSClass_roundTripStringOrUndefined(self, valueIsSome, valueWord0, valueWord1, valueWord2) { try { let optResult; if (valueIsSome) { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); optResult = string; } else { optResult = undefined; @@ -843,10 +845,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index d4480a65c..a25de5e29 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -215,10 +217,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index e9b298fb2..2a92af613 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -226,10 +228,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index beb9417df..39677e821 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -214,10 +216,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index f0c2d3fae..192e93d8e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -33,6 +33,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -434,8 +436,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -443,8 +445,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -469,8 +471,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -538,11 +540,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -650,11 +652,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueBytes, valueCount) { + TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueWord0, valueWord1, valueWord2) { try { let optResult; if (valueIsSome) { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); optResult = string; } else { optResult = null; @@ -672,11 +674,11 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueBytes, valueCount) { + TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueWord0, valueWord1, valueWord2) { try { let optResult; if (valueIsSome) { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); optResult = string; } else { optResult = null; @@ -695,9 +697,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_rawStringEnum_set"] = function bjs_MyViewControllerDelegate_rawStringEnum_set(self, valueBytes, valueCount) { + TestModule["bjs_MyViewControllerDelegate_rawStringEnum_set"] = function bjs_MyViewControllerDelegate_rawStringEnum_set(self, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(self).rawStringEnum = string; } catch (error) { setException(error); @@ -818,9 +820,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_onValueChanged"] = function bjs_MyViewControllerDelegate_onValueChanged(self, valueBytes, valueCount) { + TestModule["bjs_MyViewControllerDelegate_onValueChanged"] = function bjs_MyViewControllerDelegate_onValueChanged(self, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(self).onValueChanged(string); } catch (error) { setException(error); @@ -835,10 +837,10 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_MyViewControllerDelegate_onLabelUpdated"] = function bjs_MyViewControllerDelegate_onLabelUpdated(self, prefixBytes, prefixCount, suffixBytes, suffixCount) { + TestModule["bjs_MyViewControllerDelegate_onLabelUpdated"] = function bjs_MyViewControllerDelegate_onLabelUpdated(self, prefixWord0, prefixWord1, prefixWord2, suffixWord0, suffixWord1, suffixWord2) { try { - const string = decodeString(prefixBytes, prefixCount); - const string1 = decodeString(suffixBytes, suffixCount); + const string = decodeString(prefixWord0, prefixWord1, prefixWord2); + const string1 = decodeString(suffixWord0, suffixWord1, suffixWord2); swift.memory.getObject(self).onLabelUpdated(string, string1); } catch (error) { setException(error); @@ -913,10 +915,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index eed26c581..aab8103f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,7 +44,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -360,10 +362,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js index 2765d709f..a1b8f290c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -82,8 +84,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -91,8 +93,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -117,8 +119,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -221,11 +223,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -297,10 +299,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index f46f42d10..338cf237d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -20,6 +20,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -83,8 +85,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -92,8 +94,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -118,8 +120,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -187,11 +189,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -259,10 +261,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 37d3415a4..e474c82a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -20,6 +20,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -83,8 +85,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -92,8 +94,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -118,8 +120,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -187,11 +189,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -259,10 +261,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index e2a9093b6..eb1b2d2ef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -44,8 +46,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -53,8 +55,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -79,8 +81,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -148,11 +150,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -220,10 +222,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index f442745e5..95470ed56 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -44,8 +46,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -53,8 +55,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -79,8 +81,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -148,11 +150,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -220,10 +222,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index ebddbefd2..c76381468 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -206,17 +208,17 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_checkString"] = function bjs_checkString(aBytes, aCount) { + TestModule["bjs_checkString"] = function bjs_checkString(aWord0, aWord1, aWord2) { try { - const string = decodeString(aBytes, aCount); + const string = decodeString(aWord0, aWord1, aWord2); imports.checkString(string); } catch (error) { setException(error); } } - TestModule["bjs_checkStringWithLength"] = function bjs_checkStringWithLength(aBytes, aCount, b) { + TestModule["bjs_checkStringWithLength"] = function bjs_checkStringWithLength(aWord0, aWord1, aWord2, b) { try { - const string = decodeString(aBytes, aCount); + const string = decodeString(aWord0, aWord1, aWord2); imports.checkStringWithLength(string, b); } catch (error) { setException(error); @@ -224,10 +226,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index d2dfa204f..0a0fc1650 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -217,10 +219,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index 9104e2084..7c189df7e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -24,6 +24,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -98,8 +100,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -107,8 +109,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -133,8 +135,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -230,11 +232,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -294,10 +296,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 92ef435fb..293ea56da 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -242,10 +244,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 279a9d3c6..dabb7595f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -39,6 +39,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -395,7 +397,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -501,8 +503,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -510,8 +512,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -536,8 +538,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -584,9 +586,9 @@ 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) { + bjs["promise_resolve_TestModule_SS"] = function(promise, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); } catch (error) { setException(error); @@ -644,11 +646,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -733,10 +735,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO); } - bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); let ret = callback(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -858,10 +860,10 @@ 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) { + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Sb"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); let ret = callback(string); return ret ? 1 : 0; } catch (error) { @@ -884,10 +886,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleKSS_Sb); } - bjs["invoke_js_callback_TestModule_10TestModuleKSS_Si"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Si"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); let ret = callback(string); return ret; } catch (error) { @@ -910,10 +912,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleKSS_Si); } - bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); let ret = callback(string); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; @@ -1056,12 +1058,12 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO); } - bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(callbackId, param0IsSome, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(callbackId, param0IsSome, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); let optResult; if (param0IsSome) { - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); optResult = string; } else { optResult = null; @@ -1228,12 +1230,12 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO); } - bjs["invoke_js_callback_TestModule_10TestModuleSqSS_SqSS"] = function(callbackId, param0IsSome, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleSqSS_SqSS"] = function(callbackId, param0IsSome, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); let optResult; if (param0IsSome) { - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); optResult = string; } else { optResult = null; @@ -1375,11 +1377,11 @@ 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) { + bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string).then(resolve, reject); } bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { @@ -1420,11 +1422,11 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSb_9APIResultO); } - bjs["invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string).then(resolve, reject); } bjs["make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV"] = function(boxPtr, file, line) { @@ -1438,11 +1440,11 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaSS_6AnimalV); } - bjs["invoke_js_callback_TestModule_10TestModuleYaSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModuleYaSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string).then(resolve, reject); } bjs["make_swift_closure_TestModule_10TestModuleYaSS_SS"] = function(boxPtr, file, line) { @@ -1522,10 +1524,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules9APIResultO_y); } - bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string); } catch (error) { setException(error); @@ -1559,10 +1561,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 96c78dd22..0a6690be9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -131,7 +133,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -154,8 +156,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -163,8 +165,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -189,8 +191,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -229,9 +231,9 @@ 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) { + bjs["promise_resolve_TestModule_SS"] = function(promise, valueWord0, valueWord1, valueWord2) { try { - const string = decodeString(valueBytes, valueCount); + const string = decodeString(valueWord0, valueWord1, valueWord2); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); } catch (error) { setException(error); @@ -273,11 +275,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -339,10 +341,10 @@ 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) { + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Sb"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); let ret = callback(string); return ret ? 1 : 0; } catch (error) { @@ -388,11 +390,11 @@ 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) { + bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string).then(resolve, reject); } bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { @@ -434,10 +436,10 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules7JSValueV_y); } - bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Bytes, param0Count) { + bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Word0, param0Word1, param0Word2) { try { const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Bytes, param0Count); + const string = decodeString(param0Word0, param0Word1, param0Word2); callback(string); } catch (error) { setException(error); @@ -481,10 +483,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 0bfd7c2e2..e336f8911 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -14,6 +14,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -544,8 +546,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -553,8 +555,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -579,8 +581,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -704,11 +706,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -776,10 +778,161 @@ export async function createInstantiator(options, swift) { }; }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 134d7c28e..ff953c9a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -385,8 +387,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -394,8 +396,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -420,8 +422,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -496,11 +498,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -579,10 +581,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 500a005a3..8cec87d6e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -42,7 +44,7 @@ export async function createInstantiator(options, swift) { const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } - const fileID = decodeString(state.file, length); + const fileID = decodeUTF8(state.file, length); throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); } return func(...args); @@ -64,8 +66,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -73,8 +75,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -99,8 +101,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -324,10 +326,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 58ff6a85a..40bf7e8c2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -39,8 +41,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -48,8 +50,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -74,8 +76,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -142,11 +144,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -206,10 +208,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 416e5c281..435415b0f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -56,8 +58,8 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -65,8 +67,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -91,8 +93,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -167,11 +169,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -231,10 +233,161 @@ export async function createInstantiator(options, swift) { bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 81b09eaf4..ce27ff522 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -9,6 +9,8 @@ export async function createInstantiator(options, swift) { let memory; let setException; let decodeString; + let decodeUTF8; + const immortalStrings = new Map(); const textDecoder = new TextDecoder("utf-8"); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; @@ -40,8 +42,8 @@ export async function createInstantiator(options, swift) { bjs = {}; importObject["bjs"] = bjs; const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - tmpRetString = decodeString(ptr, len); + bjs["swift_js_return_string"] = function(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); @@ -49,8 +51,8 @@ export async function createInstantiator(options, swift) { 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_make_js_string"] = function(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); @@ -75,8 +77,8 @@ export async function createInstantiator(options, swift) { bjs["swift_js_push_f64"] = function(v) { f64Stack.push(v); } - bjs["swift_js_push_string"] = function(ptr, len) { - const value = decodeString(ptr, len); + bjs["swift_js_push_string"] = function(word0, word1, word2) { + const value = decodeString(word0, word1, word2); strStack.push(value); } bjs["swift_js_pop_i32"] = function() { @@ -143,11 +145,11 @@ export async function createInstantiator(options, swift) { tmpRetOptionalDouble = value; } } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + bjs["swift_js_return_optional_string"] = function(isSome, word0, word1, word2) { if (isSome === 0) { tmpRetString = null; } else { - tmpRetString = decodeString(ptr, len); + tmpRetString = decodeString(word0, word1, word2); } } bjs["swift_js_return_optional_object"] = function(isSome, objectId) { @@ -215,10 +217,161 @@ export async function createInstantiator(options, swift) { } }, setInstance: (i) => { + if (memory !== i.exports.memory) immortalStrings.clear(); instance = i; memory = instance.exports.memory; - decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const start = byteIndex; + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + // Match TextDecoder: consume exactly one leading UTF-8 BOM. + if (start === 0 && codePoint === 0xfeff) continue; + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 6946d6a59..dd5e1e970 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -452,7 +452,7 @@ extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftAssociatedValu extension _BridgedSwiftAlias where JSRepresentation == String { // MARK: ImportTS - @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32, Int32) -> T) -> T { bridgeToJS().bridgeJSWithLoweredParameter(body) } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ bytesCount: Int32) -> Self { @@ -476,7 +476,7 @@ extension _BridgedSwiftAlias where JSRepresentation == String { extension _BridgedAsOptional where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation == String { @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter( - _ body: (Int32, Int32, Int32) -> T + _ body: (Int32, Int32, Int32, Int32) -> T ) -> T { asOptional.map { $0.bridgeToJS() }.bridgeJSWithLoweredParameter(body) } @@ -798,12 +798,29 @@ extension Double: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftS extension String: _BridgedSwiftStackType { public typealias StackLiftResult = String + /// Lends the three wasm32 `String` words to `body` for the duration of a synchronous JS call. + /// + /// The 12-byte layout is a Swift stdlib implementation detail. JS interprets small-string + /// flags in `word2` and, for large strings, UTF-8 at `word1 + 20` (`nativeBias` on 32-bit). + @inline(__always) + fileprivate consuming func withBridgeJSRawWords(_ body: (Int32, Int32, Int32) -> Result) -> Result { + #if arch(wasm32) + return withUnsafeBytes(of: self) { bytes in + precondition(bytes.count == 12, "BridgeJS expects the 12-byte wasm32 String layout") + let word0 = bytes.load(fromByteOffset: 0, as: Int32.self) + let word1 = bytes.load(fromByteOffset: 4, as: Int32.self) + let word2 = bytes.load(fromByteOffset: 8, as: Int32.self) + return body(word0, word1, word2) + } + #else + _onlyAvailableOnWasm() + #endif + } + // MARK: ImportTS - @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { - return self.withUTF8 { b in - body(Int32(bitPattern: UInt32(UInt(bitPattern: b.baseAddress))), Int32(b.count)) - } + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32, Int32) -> T) -> T { + withBridgeJSRawWords(body) } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ bytesCount: Int32) -> String { @@ -835,14 +852,14 @@ extension String: _BridgedSwiftStackType { } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - return self.withUTF8 { ptr in - _swift_js_return_string(ptr.baseAddress, Int32(ptr.count)) + withBridgeJSRawWords { word0, word1, word2 in + _swift_js_return_string(word0, word1, word2) } } @_spi(BridgeJS) public consuming func bridgeJSStackPush() { - self.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) + withBridgeJSRawWords { word0, word1, word2 in + _swift_js_push_string(word0, word1, word2) } } } @@ -1290,7 +1307,7 @@ extension _BridgedSwiftStruct { extension _BridgedSwiftEnumNoPayload where Self: RawRepresentable, RawValue == String { // MARK: ImportTS - @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32, Int32) -> T) -> T { rawValue.bridgeJSWithLoweredParameter(body) } @@ -1348,15 +1365,15 @@ private func _swift_js_init_memory_extern(_ sourceId: Int32, _ ptr: UnsafeMutabl #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_string") -private func _swift_js_push_string_extern(_ ptr: UnsafePointer?, _ len: Int32) +private func _swift_js_push_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) #else -private func _swift_js_push_string_extern(_ ptr: UnsafePointer?, _ len: Int32) { +private func _swift_js_push_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) { _onlyAvailableOnWasm() } #endif -@_spi(BridgeJS) @inline(never) public func _swift_js_push_string(_ ptr: UnsafePointer?, _ len: Int32) { - _swift_js_push_string_extern(ptr, len) +@_spi(BridgeJS) @inline(never) public func _swift_js_push_string(_ word0: Int32, _ word1: Int32, _ word2: Int32) { + _swift_js_push_string_extern(word0, word1, word2) } #if arch(wasm32) @@ -1542,15 +1559,15 @@ extension UInt: _BridgedNumericArray { #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_make_js_string") -private func _swift_js_make_js_string_extern(_ ptr: UnsafePointer?, _ len: Int32) -> Int32 +private func _swift_js_make_js_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) -> Int32 #else -/// Creates a JavaScript string from UTF-8 data in WebAssembly memory -private func _swift_js_make_js_string_extern(_ ptr: UnsafePointer?, _ len: Int32) -> Int32 { +/// Creates a JavaScript string from the wasm32 Swift `String` layout words +private func _swift_js_make_js_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) -> Int32 { _onlyAvailableOnWasm() } #endif -@inline(never) func _swift_js_make_js_string(_ ptr: UnsafePointer?, _ len: Int32) -> Int32 { - _swift_js_make_js_string_extern(ptr, len) +@inline(never) func _swift_js_make_js_string(_ word0: Int32, _ word1: Int32, _ word2: Int32) -> Int32 { + _swift_js_make_js_string_extern(word0, word1, word2) } #if arch(wasm32) @@ -1568,15 +1585,15 @@ private func _swift_js_init_memory_with_result_extern(_ ptr: UnsafePointer?, _ len: Int32) +private func _swift_js_return_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) #else /// Write a string to reserved string storage to be returned to JavaScript -private func _swift_js_return_string_extern(_ ptr: UnsafePointer?, _ len: Int32) { +private func _swift_js_return_string_extern(_ word0: Int32, _ word1: Int32, _ word2: Int32) { _onlyAvailableOnWasm() } #endif -@inline(never) func _swift_js_return_string(_ ptr: UnsafePointer?, _ len: Int32) { - _swift_js_return_string_extern(ptr, len) +@inline(never) func _swift_js_return_string(_ word0: Int32, _ word1: Int32, _ word2: Int32) { + _swift_js_return_string_extern(word0, word1, word2) } #if arch(wasm32) @@ -1657,15 +1674,15 @@ private func _swift_js_get_optional_string_extern() -> Int32 { #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_return_optional_string") -private func _swift_js_return_optional_string_extern(_ isSome: Int32, _ ptr: UnsafePointer?, _ len: Int32) +private func _swift_js_return_optional_string_extern(_ isSome: Int32, _ word0: Int32, _ word1: Int32, _ word2: Int32) #else /// Write an optional string to reserved string storage to be returned to JavaScript -private func _swift_js_return_optional_string_extern(_ isSome: Int32, _ ptr: UnsafePointer?, _ len: Int32) { +private func _swift_js_return_optional_string_extern(_ isSome: Int32, _ word0: Int32, _ word1: Int32, _ word2: Int32) { _onlyAvailableOnWasm() } #endif -@inline(never) func _swift_js_return_optional_string(_ isSome: Int32, _ ptr: UnsafePointer?, _ len: Int32) { - _swift_js_return_optional_string_extern(isSome, ptr, len) +@inline(never) func _swift_js_return_optional_string(_ isSome: Int32, _ word0: Int32, _ word1: Int32, _ word2: Int32) { + _swift_js_return_optional_string_extern(isSome, word0, word1, word2) } #if arch(wasm32) @@ -2156,14 +2173,14 @@ extension _BridgedAsOptional where Wrapped == Bool { extension _BridgedAsOptional where Wrapped == String { @_spi(BridgeJS) @_transparent public consuming func bridgeJSWithLoweredParameter( - _ body: (Int32, Int32, Int32) -> T + _ body: (Int32, Int32, Int32, Int32) -> T ) -> T { switch asOptional { case .none: - return body(0, 0, 0) + return body(0, 0, 0, 0) case .some(let value): - return value.bridgeJSWithLoweredParameter { bytes, count in - return body(1, bytes, count) + return value.bridgeJSWithLoweredParameter { word0, word1, word2 in + return body(1, word0, word1, word2) } } } @@ -2194,10 +2211,10 @@ extension _BridgedAsOptional where Wrapped == String { @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { switch asOptional { case .none: - _swift_js_return_optional_string(0, nil, 0) - case .some(var value): - value.withUTF8 { ptr in - _swift_js_return_optional_string(1, ptr.baseAddress, Int32(ptr.count)) + _swift_js_return_optional_string(0, 0, 0, 0) + case .some(let value): + value.withBridgeJSRawWords { word0, word1, word2 in + _swift_js_return_optional_string(1, word0, word1, word2) } } } @@ -2358,14 +2375,14 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { extension _BridgedAsOptional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { @_spi(BridgeJS) @_transparent public consuming func bridgeJSWithLoweredParameter( - _ body: (Int32, Int32, Int32) -> T + _ body: (Int32, Int32, Int32, Int32) -> T ) -> T { switch asOptional { case .none: - return body(0, 0, 0) + return body(0, 0, 0, 0) case .some(let wrapped): - return wrapped.bridgeJSWithLoweredParameter { bytes, count in - return body(1, bytes, count) + return wrapped.bridgeJSWithLoweredParameter { word0, word1, word2 in + return body(1, word0, word1, word2) } } } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index acb3e23f1..52799fa7c 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -202,14 +202,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13D #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -229,9 +229,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -269,14 +269,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5Th #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -296,9 +296,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -846,14 +846,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7 #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -873,9 +873,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -930,14 +930,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -957,9 +957,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Int in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -1014,14 +1014,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1041,9 +1041,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -1081,14 +1081,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -1108,9 +1108,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(callbackValue, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(callbackValue, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -1726,14 +1726,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Word0: Int32, _ param1Word1: Int32, _ param1Word2: Int32, _ param2: Float64) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1Word0: Int32, _ param1Word1: Int32, _ param1Word2: Int32, _ param2: Float64) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(callback, param0, param1Bytes, param1Length, param2) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1Word0: Int32, _ param1Word1: Int32, _ param1Word2: Int32, _ param2: Float64) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(callback, param0, param1Word0, param1Word1, param1Word2, param2) } #if arch(wasm32) @@ -1753,11 +1753,11 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0, param1, param2) in #if arch(wasm32) - let ret0 = param1.bridgeJSWithLoweredParameter { (param1Bytes, param1Length) in + let ret0 = param1.bridgeJSWithLoweredParameter { (param1Word0, param1Word1, param1Word2) 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) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Word0, param1Word1, param1Word2, param2Value) return ret } let ret = ret0 @@ -2126,14 +2126,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq1 #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(callback, param0IsSome, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(callback, param0IsSome, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2153,9 +2153,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -2449,14 +2449,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9 #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(callback, param0IsSome, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(callback, param0IsSome, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2476,9 +2476,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Bytes, param0Length) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Word0, param0Word1, param0Word2) return ret } let ret = ret0 @@ -2580,14 +2580,14 @@ 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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2612,9 +2612,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -2652,14 +2652,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaKSS_y(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2684,9 +2684,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } #else @@ -2794,14 +2794,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestsYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(resolveRef, rejectRef, callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -2826,9 +2826,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Word0, param0Word1, param0Word2) } } return resolved @@ -3008,14 +3008,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaS #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -3035,9 +3035,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -3381,14 +3381,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9D #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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_20BridgeJSRuntimeTestssSS_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(callback, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -3408,9 +3408,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -3878,14 +3878,14 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq #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 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> 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_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: 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) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(callback, param0IsSome, param0Word0, param0Word1, param0Word2) } #if arch(wasm32) @@ -3905,9 +3905,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Word0, param0Word1, param0Word2) in let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Word0, param0Word1, param0Word2) } #else fatalError("Only available on WebAssembly") @@ -4308,10 +4308,10 @@ extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { } func setLabelElements(_ labelPrefix: String, _ labelSuffix: String) -> Void { - labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in - labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in + labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixWord0, labelPrefixWord1, labelPrefixWord2) in + labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixWord0, labelSuffixWord1, labelSuffixWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) + bjs_DataProcessor_setLabelElements(jsObjectValue, labelPrefixWord0, labelPrefixWord1, labelPrefixWord2, labelSuffixWord0, labelSuffixWord1, labelSuffixWord2) } } } @@ -4394,9 +4394,9 @@ extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } } } @@ -4434,9 +4434,9 @@ extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueWord0, newValueWord1, newValueWord2) in let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } } } @@ -4528,14 +4528,14 @@ fileprivate func bjs_DataProcessor_getValue_extern(_ jsObject: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_setLabelElements") -fileprivate func bjs_DataProcessor_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void +fileprivate func bjs_DataProcessor_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixWord0: Int32, _ labelPrefixWord1: Int32, _ labelPrefixWord2: Int32, _ labelSuffixWord0: Int32, _ labelSuffixWord1: Int32, _ labelSuffixWord2: Int32) -> Void #else -fileprivate func bjs_DataProcessor_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { +fileprivate func bjs_DataProcessor_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixWord0: Int32, _ labelPrefixWord1: Int32, _ labelPrefixWord2: Int32, _ labelSuffixWord0: Int32, _ labelSuffixWord1: Int32, _ labelSuffixWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_setLabelElements(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { - return bjs_DataProcessor_setLabelElements_extern(jsObject, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) +@inline(never) fileprivate func bjs_DataProcessor_setLabelElements(_ jsObject: Int32, _ labelPrefixWord0: Int32, _ labelPrefixWord1: Int32, _ labelPrefixWord2: Int32, _ labelSuffixWord0: Int32, _ labelSuffixWord1: Int32, _ labelSuffixWord2: Int32) -> Void { + return bjs_DataProcessor_setLabelElements_extern(jsObject, labelPrefixWord0, labelPrefixWord1, labelPrefixWord2, labelSuffixWord0, labelSuffixWord1, labelSuffixWord2) } #if arch(wasm32) @@ -4684,14 +4684,14 @@ fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> #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 +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: 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) +@inline(never) fileprivate func bjs_DataProcessor_optionalTag_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_DataProcessor_optionalTag_set_extern(jsObject, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -4756,14 +4756,14 @@ fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) - #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 +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: 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) +@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_DataProcessor_optionalTheme_set_extern(jsObject, newValueIsSome, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -7672,6 +7672,174 @@ extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { } } +@_expose(wasm, "bjs_StringABIExports_static_echo") +@_cdecl("bjs_StringABIExports_static_echo") +public func _bjs_StringABIExports_static_echo(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + let value = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = StringABIExports.echo(_: value) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_echoOptional") +@_cdecl("bjs_StringABIExports_static_echoOptional") +public func _bjs_StringABIExports_static_echoOptional(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + let value = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let ret = StringABIExports.echoOptional(_: value) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_echoArray") +@_cdecl("bjs_StringABIExports_static_echoArray") +public func _bjs_StringABIExports_static_echoArray() -> Void { + #if arch(wasm32) + let value = [String].bridgeJSStackPop() + let ret = StringABIExports.echoArray(_: value) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallEmpty") +@_cdecl("bjs_StringABIExports_static_smallEmpty") +public func _bjs_StringABIExports_static_smallEmpty() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallEmpty() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallASCII") +@_cdecl("bjs_StringABIExports_static_smallASCII") +public func _bjs_StringABIExports_static_smallASCII() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallASCII() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallEight") +@_cdecl("bjs_StringABIExports_static_smallEight") +public func _bjs_StringABIExports_static_smallEight() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallEight() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallNine") +@_cdecl("bjs_StringABIExports_static_smallNine") +public func _bjs_StringABIExports_static_smallNine() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallNine() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallTen") +@_cdecl("bjs_StringABIExports_static_smallTen") +public func _bjs_StringABIExports_static_smallTen() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallTen() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_smallUTF8") +@_cdecl("bjs_StringABIExports_static_smallUTF8") +public func _bjs_StringABIExports_static_smallUTF8() -> Void { + #if arch(wasm32) + let ret = StringABIExports.smallUTF8() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_largeImmortal") +@_cdecl("bjs_StringABIExports_static_largeImmortal") +public func _bjs_StringABIExports_static_largeImmortal() -> Void { + #if arch(wasm32) + let ret = StringABIExports.largeImmortal() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_largeImmortalAgain") +@_cdecl("bjs_StringABIExports_static_largeImmortalAgain") +public func _bjs_StringABIExports_static_largeImmortalAgain() -> Void { + #if arch(wasm32) + let ret = StringABIExports.largeImmortalAgain() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_largeDynamic") +@_cdecl("bjs_StringABIExports_static_largeDynamic") +public func _bjs_StringABIExports_static_largeDynamic() -> Void { + #if arch(wasm32) + let ret = StringABIExports.largeDynamic() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_immortalSubstring") +@_cdecl("bjs_StringABIExports_static_immortalSubstring") +public func _bjs_StringABIExports_static_immortalSubstring() -> Void { + #if arch(wasm32) + let ret = StringABIExports.immortalSubstring() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_optionalNone") +@_cdecl("bjs_StringABIExports_static_optionalNone") +public func _bjs_StringABIExports_static_optionalNone() -> Void { + #if arch(wasm32) + let ret = StringABIExports.optionalNone() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StringABIExports_static_optionalSome") +@_cdecl("bjs_StringABIExports_static_optionalSome") +public func _bjs_StringABIExports_static_optionalSome() -> Void { + #if arch(wasm32) + let ret = StringABIExports.optionalSome() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension JSCoordinate: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSCoordinate { let longitude = Double.bridgeJSStackPop() @@ -16234,20 +16402,20 @@ func _$Promise_reject(_ promise: JSObject, _ value: JSValue) 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 +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) + promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } @@ -16402,20 +16570,20 @@ func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws #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 +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(promise, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueBytes, valueLength) + promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } @@ -16445,20 +16613,20 @@ func _$Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) thro #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 +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: 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) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(promise, valueIsSome, valueWord0, valueWord1, valueWord2) } func _$Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueBytes, valueLength) + promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error } } @@ -16802,14 +16970,14 @@ 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 +fileprivate func bjs_Surface_init_extern(_ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Int32 #else -fileprivate func bjs_Surface_init_extern(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { +fileprivate func bjs_Surface_init_extern(_ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Surface_init(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { - return bjs_Surface_init_extern(labelBytes, labelLength) +@inline(never) fileprivate func bjs_Surface_init(_ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Int32 { + return bjs_Surface_init_extern(labelWord0, labelWord1, labelWord2) } #if arch(wasm32) @@ -16825,8 +16993,8 @@ fileprivate func bjs_Surface_label_get_extern(_ self: Int32) -> Int32 { } func _$Surface_init(_ label: String) throws(JSException) -> JSObject { - let ret0 = label.bridgeJSWithLoweredParameter { (labelBytes, labelLength) in - let ret = bjs_Surface_init(labelBytes, labelLength) + let ret0 = label.bridgeJSWithLoweredParameter { (labelWord0, labelWord1, labelWord2) in + let ret = bjs_Surface_init(labelWord0, labelWord1, labelWord2) return ret } let ret = ret0 @@ -16847,38 +17015,38 @@ func _$Surface_label_get(_ self: JSObject) throws(JSException) -> String { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripTagged_static") -fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 +fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 #else -fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { +fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AliasImports_jsRoundTripTagged_static(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { - return bjs_AliasImports_jsRoundTripTagged_static_extern(valueBytes, valueLength) +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripTagged_static(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { + return bjs_AliasImports_jsRoundTripTagged_static_extern(valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripOptionalTagged_static") -fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void #else -fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(valueIsSome, valueBytes, valueLength) +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(valueIsSome, valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsProduceOptionalCanvas_static") -fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void +fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Void #else -fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void { +fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void { - return bjs_AliasImports_jsProduceOptionalCanvas_static_extern(labelIsSome, labelBytes, labelLength) +@inline(never) fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static(_ labelIsSome: Int32, _ labelWord0: Int32, _ labelWord1: Int32, _ labelWord2: Int32) -> Void { + return bjs_AliasImports_jsProduceOptionalCanvas_static_extern(labelIsSome, labelWord0, labelWord1, labelWord2) } #if arch(wasm32) @@ -16942,8 +17110,8 @@ fileprivate func bjs_AliasImports_jsRoundTripOptionalUserId_static_extern(_ valu } func _$AliasImports_jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Tagged { - let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in - let ret = bjs_AliasImports_jsRoundTripTagged_static(valueBytes, valueLength) + let ret0 = value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in + let ret = bjs_AliasImports_jsRoundTripTagged_static(valueWord0, valueWord1, valueWord2) return ret } let ret = ret0 @@ -16954,8 +17122,8 @@ func _$AliasImports_jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Ta } func _$AliasImports_jsRoundTripOptionalTagged(_ value: Optional) throws(JSException) -> Optional { - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in - bjs_AliasImports_jsRoundTripOptionalTagged_static(valueIsSome, valueBytes, valueLength) + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in + bjs_AliasImports_jsRoundTripOptionalTagged_static(valueIsSome, valueWord0, valueWord1, valueWord2) } if let error = _swift_js_take_exception() { throw error @@ -16964,8 +17132,8 @@ func _$AliasImports_jsRoundTripOptionalTagged(_ value: Optional) throws( } func _$AliasImports_jsProduceOptionalCanvas(_ label: Optional) throws(JSException) -> Optional { - label.bridgeJSWithLoweredParameter { (labelIsSome, labelBytes, labelLength) in - bjs_AliasImports_jsProduceOptionalCanvas_static(labelIsSome, labelBytes, labelLength) + label.bridgeJSWithLoweredParameter { (labelIsSome, labelWord0, labelWord1, labelWord2) in + bjs_AliasImports_jsProduceOptionalCanvas_static(labelIsSome, labelWord0, labelWord1, labelWord2) } if let error = _swift_js_take_exception() { throw error @@ -17020,14 +17188,14 @@ func _$AliasImports_jsRoundTripOptionalUserId(_ value: Optional) throws( #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementObject_init") -fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 +fileprivate func bjs_ArrayElementObject_init_extern(_ idWord0: Int32, _ idWord1: Int32, _ idWord2: Int32) -> Int32 #else -fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 { +fileprivate func bjs_ArrayElementObject_init_extern(_ idWord0: Int32, _ idWord1: Int32, _ idWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ArrayElementObject_init(_ idBytes: Int32, _ idLength: Int32) -> Int32 { - return bjs_ArrayElementObject_init_extern(idBytes, idLength) +@inline(never) fileprivate func bjs_ArrayElementObject_init(_ idWord0: Int32, _ idWord1: Int32, _ idWord2: Int32) -> Int32 { + return bjs_ArrayElementObject_init_extern(idWord0, idWord1, idWord2) } #if arch(wasm32) @@ -17043,8 +17211,8 @@ fileprivate func bjs_ArrayElementObject_id_get_extern(_ self: Int32) -> Int32 { } func _$ArrayElementObject_init(_ id: String) throws(JSException) -> JSObject { - let ret0 = id.bridgeJSWithLoweredParameter { (idBytes, idLength) in - let ret = bjs_ArrayElementObject_init(idBytes, idLength) + let ret0 = id.bridgeJSWithLoweredParameter { (idWord0, idWord1, idWord2) in + let ret = bjs_ArrayElementObject_init(idWord0, idWord1, idWord2) return ret } let ret = ret0 @@ -17455,26 +17623,26 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripBool_static_extern(_ res #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripString_static") -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void #else -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - return bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(resolveRef, rejectRef, vBytes, vLength) +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripString_static_extern(resolveRef, rejectRef, vWord0, vWord1, vWord2) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static") -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void #else -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - return bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(resolveRef, rejectRef, vIsSome, vBytes, vLength) +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static_extern(resolveRef, rejectRef, vIsSome, vWord0, vWord1, vWord2) } #if arch(wasm32) @@ -17527,14 +17695,14 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripStringArray_static_exter #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static") -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void #else -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vBytes, vLength) +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vWord0, vWord1, vWord2) } #if arch(wasm32) @@ -17601,8 +17769,8 @@ func _$AsyncImportImports_jsAsyncRoundTripString(_ v: String) async throws(JSExc }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - v.bridgeJSWithLoweredParameter { (vBytes, vLength) in - bjs_AsyncImportImports_jsAsyncRoundTripString_static(resolveRef, rejectRef, vBytes, vLength) + v.bridgeJSWithLoweredParameter { (vWord0, vWord1, vWord2) in + bjs_AsyncImportImports_jsAsyncRoundTripString_static(resolveRef, rejectRef, vWord0, vWord1, vWord2) } } return resolved @@ -17614,8 +17782,8 @@ func _$AsyncImportImports_jsAsyncRoundTripOptionalString(_ v: Optional) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - v.bridgeJSWithLoweredParameter { (vIsSome, vBytes, vLength) in - bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(resolveRef, rejectRef, vIsSome, vBytes, vLength) + v.bridgeJSWithLoweredParameter { (vIsSome, vWord0, vWord1, vWord2) in + bjs_AsyncImportImports_jsAsyncRoundTripOptionalString_static(resolveRef, rejectRef, vIsSome, vWord0, vWord1, vWord2) } } return resolved @@ -17675,8 +17843,8 @@ func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async th }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - v.bridgeJSWithLoweredParameter { (vBytes, vLength) in - bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(resolveRef, rejectRef, vBytes, vLength) + v.bridgeJSWithLoweredParameter { (vWord0, vWord1, vWord2) in + bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static(resolveRef, rejectRef, vWord0, vWord1, vWord2) } } return resolved @@ -17778,14 +17946,14 @@ fileprivate func bjs_ClosureSupportImports_jsApplyDouble_static_extern(_ value: #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyString_static") -fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32, _ transform: Int32) -> Int32 #else -fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 { +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32, _ transform: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyString_static(_ valueBytes: Int32, _ valueLength: Int32, _ transform: Int32) -> Int32 { - return bjs_ClosureSupportImports_jsApplyString_static_extern(valueBytes, valueLength, transform) +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyString_static(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32, _ transform: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyString_static_extern(valueWord0, valueWord1, valueWord2, transform) } #if arch(wasm32) @@ -17886,14 +18054,14 @@ fileprivate func bjs_ClosureSupportImports_jsMakeDoubleToDouble_static_extern(_ #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeStringToString_static") -fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 #else -fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { - return bjs_ClosureSupportImports_jsMakeStringToString_static_extern(prefixBytes, prefixLength) +@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static(_ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsMakeStringToString_static_extern(prefixWord0, prefixWord1, prefixWord2) } #if arch(wasm32) @@ -18042,9 +18210,9 @@ func _$ClosureSupportImports_jsApplyDouble(_ value: Double, _ transform: JSTyped } func _$ClosureSupportImports_jsApplyString(_ value: String, _ transform: JSTypedClosure<(String) -> String>) throws(JSException) -> String { - let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let ret0 = value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in let transformFuncRef = transform.bridgeJSLowerParameter() - let ret = bjs_ClosureSupportImports_jsApplyString_static(valueBytes, valueLength, transformFuncRef) + let ret = bjs_ClosureSupportImports_jsApplyString_static(valueWord0, valueWord1, valueWord2, transformFuncRef) return ret } let ret = ret0 @@ -18133,8 +18301,8 @@ func _$ClosureSupportImports_jsMakeDoubleToDouble(_ base: Double) throws(JSExcep } func _$ClosureSupportImports_jsMakeStringToString(_ prefix: String) throws(JSException) -> (String) -> String { - let ret0 = prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in - let ret = bjs_ClosureSupportImports_jsMakeStringToString_static(prefixBytes, prefixLength) + let ret0 = prefix.bridgeJSWithLoweredParameter { (prefixWord0, prefixWord1, prefixWord2) in + let ret = bjs_ClosureSupportImports_jsMakeStringToString_static(prefixWord0, prefixWord1, prefixWord2) return ret } let ret = ret0 @@ -18386,14 +18554,14 @@ func _$DictionarySupportImports_jsRoundTripDictionaryDoubleArray(_ values: [Stri #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_init") -fileprivate func bjs_Foo_init_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 +fileprivate func bjs_Foo_init_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 #else -fileprivate func bjs_Foo_init_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { +fileprivate func bjs_Foo_init_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Foo_init(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { - return bjs_Foo_init_extern(valueBytes, valueLength) +@inline(never) fileprivate func bjs_Foo_init(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { + return bjs_Foo_init_extern(valueWord0, valueWord1, valueWord2) } #if arch(wasm32) @@ -18409,8 +18577,8 @@ fileprivate func bjs_Foo_value_get_extern(_ self: Int32) -> Int32 { } func _$Foo_init(_ value: String) throws(JSException) -> JSObject { - let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in - let ret = bjs_Foo_init(valueBytes, valueLength) + let ret0 = value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in + let ret = bjs_Foo_init(valueWord0, valueWord1, valueWord2) return ret } let ret = ret0 @@ -18512,19 +18680,19 @@ func _$jsRoundTripBool(_ v: Bool) throws(JSException) -> Bool { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripString") -fileprivate func bjs_jsRoundTripString_extern(_ vBytes: Int32, _ vLength: Int32) -> Int32 +fileprivate func bjs_jsRoundTripString_extern(_ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Int32 #else -fileprivate func bjs_jsRoundTripString_extern(_ vBytes: Int32, _ vLength: Int32) -> Int32 { +fileprivate func bjs_jsRoundTripString_extern(_ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { - return bjs_jsRoundTripString_extern(vBytes, vLength) +@inline(never) fileprivate func bjs_jsRoundTripString(_ vWord0: Int32, _ vWord1: Int32, _ vWord2: Int32) -> Int32 { + return bjs_jsRoundTripString_extern(vWord0, vWord1, vWord2) } func _$jsRoundTripString(_ v: String) throws(JSException) -> String { - let ret0 = v.bridgeJSWithLoweredParameter { (vBytes, vLength) in - let ret = bjs_jsRoundTripString(vBytes, vLength) + let ret0 = v.bridgeJSWithLoweredParameter { (vWord0, vWord1, vWord2) in + let ret = bjs_jsRoundTripString(vWord0, vWord1, vWord2) return ret } let ret = ret0 @@ -18640,19 +18808,19 @@ func _$jsThrowOrString(_ shouldThrow: Bool) throws(JSException) -> String { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripFeatureFlag") -fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Int32 #else -fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 { +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Int32 { - return bjs_jsRoundTripFeatureFlag_extern(flagBytes, flagLength) +@inline(never) fileprivate func bjs_jsRoundTripFeatureFlag(_ flagWord0: Int32, _ flagWord1: Int32, _ flagWord2: Int32) -> Int32 { + return bjs_jsRoundTripFeatureFlag_extern(flagWord0, flagWord1, flagWord2) } func _$jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> FeatureFlag { - let ret0 = flag.bridgeJSWithLoweredParameter { (flagBytes, flagLength) in - let ret = bjs_jsRoundTripFeatureFlag(flagBytes, flagLength) + let ret0 = flag.bridgeJSWithLoweredParameter { (flagWord0, flagWord1, flagWord2) in + let ret = bjs_jsRoundTripFeatureFlag(flagWord0, flagWord1, flagWord2) return ret } let ret = ret0 @@ -18686,14 +18854,14 @@ func _$runAsyncWorks() async throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_fetchWeatherData") -fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void +fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityWord0: Int32, _ cityWord1: Int32, _ cityWord2: Int32) -> Void #else -fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void { +fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityWord0: Int32, _ cityWord1: Int32, _ cityWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_fetchWeatherData(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void { - return bjs_fetchWeatherData_extern(resolveRef, rejectRef, cityBytes, cityLength) +@inline(never) fileprivate func bjs_fetchWeatherData(_ resolveRef: Int32, _ rejectRef: Int32, _ cityWord0: Int32, _ cityWord1: Int32, _ cityWord2: Int32) -> Void { + return bjs_fetchWeatherData_extern(resolveRef, rejectRef, cityWord0, cityWord1, cityWord2) } func _$fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData { @@ -18702,8 +18870,8 @@ func _$fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in - city.bridgeJSWithLoweredParameter { (cityBytes, cityLength) in - bjs_fetchWeatherData(resolveRef, rejectRef, cityBytes, cityLength) + city.bridgeJSWithLoweredParameter { (cityWord0, cityWord1, cityWord2) in + bjs_fetchWeatherData(resolveRef, rejectRef, cityWord0, cityWord1, cityWord2) } } return resolved @@ -18731,19 +18899,19 @@ func _$_jsWeirdFunction() throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_parseInt") -fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 +fileprivate func bjs_parseInt_extern(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 #else -fileprivate func bjs_parseInt_extern(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { +fileprivate func bjs_parseInt_extern(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_parseInt(_ stringBytes: Int32, _ stringLength: Int32) -> Float64 { - return bjs_parseInt_extern(stringBytes, stringLength) +@inline(never) fileprivate func bjs_parseInt(_ stringWord0: Int32, _ stringWord1: Int32, _ stringWord2: Int32) -> Float64 { + return bjs_parseInt_extern(stringWord0, stringWord1, stringWord2) } func _$parseInt(_ string: String) throws(JSException) -> Double { - let ret0 = string.bridgeJSWithLoweredParameter { (stringBytes, stringLength) in - let ret = bjs_parseInt(stringBytes, stringLength) + let ret0 = string.bridgeJSWithLoweredParameter { (stringWord0, stringWord1, stringWord2) in + let ret = bjs_parseInt(stringWord0, stringWord1, stringWord2) return ret } let ret = ret0 @@ -18755,14 +18923,14 @@ func _$parseInt(_ string: String) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_init") -fileprivate func bjs_JsGreeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 +fileprivate func bjs_JsGreeter_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 #else -fileprivate func bjs_JsGreeter_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +fileprivate func bjs_JsGreeter_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_init(_ nameBytes: Int32, _ nameLength: Int32, _ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { - return bjs_JsGreeter_init_extern(nameBytes, nameLength, prefixBytes, prefixLength) +@inline(never) fileprivate func bjs_JsGreeter_init(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ prefixWord0: Int32, _ prefixWord1: Int32, _ prefixWord2: Int32) -> Int32 { + return bjs_JsGreeter_init_extern(nameWord0, nameWord1, nameWord2, prefixWord0, prefixWord1, prefixWord2) } #if arch(wasm32) @@ -18791,14 +18959,14 @@ fileprivate func bjs_JsGreeter_prefix_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_set") -fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_JsGreeter_name_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_JsGreeter_name_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -18815,20 +18983,20 @@ fileprivate func bjs_JsGreeter_greet_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_changeName") -fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void #else -fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - return bjs_JsGreeter_changeName_extern(self, nameBytes, nameLength) +@inline(never) fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { + return bjs_JsGreeter_changeName_extern(self, nameWord0, nameWord1, nameWord2) } func _$JsGreeter_init(_ name: String, _ prefix: String) throws(JSException) -> JSObject { - let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in - let ret1 = prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in - let ret = bjs_JsGreeter_init(nameBytes, nameLength, prefixBytes, prefixLength) + let ret0 = name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in + let ret1 = prefix.bridgeJSWithLoweredParameter { (prefixWord0, prefixWord1, prefixWord2) in + let ret = bjs_JsGreeter_init(nameWord0, nameWord1, nameWord2, prefixWord0, prefixWord1, prefixWord2) return ret } return ret1 @@ -18859,9 +19027,9 @@ func _$JsGreeter_prefix_get(_ self: JSObject) throws(JSException) -> String { } func _$JsGreeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_JsGreeter_name_set(selfValue, newValueBytes, newValueLength) + bjs_JsGreeter_name_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -18878,9 +19046,9 @@ func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { } func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { - name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_JsGreeter_changeName(selfValue, nameBytes, nameLength) + bjs_JsGreeter_changeName(selfValue, nameWord0, nameWord1, nameWord2) } if let error = _swift_js_take_exception() { throw error @@ -18937,14 +19105,14 @@ fileprivate func bjs_WeatherData_temperature_set_extern(_ self: Int32, _ newValu #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WeatherData_description_set") -fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_WeatherData_description_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_WeatherData_description_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_WeatherData_description_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_WeatherData_description_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_WeatherData_description_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -18996,9 +19164,9 @@ func _$WeatherData_temperature_set(_ self: JSObject, _ newValue: Double) throws( } func _$WeatherData_description_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_WeatherData_description_set(selfValue, newValueBytes, newValueLength) + bjs_WeatherData_description_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -19180,14 +19348,14 @@ func _$StaticBox_value(_ self: JSObject) throws(JSException) -> Double { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_init") -fileprivate func bjs_Animal_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 +fileprivate func bjs_Animal_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ age: Float64, _ isCat: Int32) -> Int32 #else -fileprivate func bjs_Animal_init_extern(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { +fileprivate func bjs_Animal_init_extern(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Animal_init(_ nameBytes: Int32, _ nameLength: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { - return bjs_Animal_init_extern(nameBytes, nameLength, age, isCat) +@inline(never) fileprivate func bjs_Animal_init(_ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { + return bjs_Animal_init_extern(nameWord0, nameWord1, nameWord2, age, isCat) } #if arch(wasm32) @@ -19228,14 +19396,14 @@ fileprivate func bjs_Animal_isCat_get_extern(_ self: Int32) -> Int32 { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_set") -fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void #else -fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_Animal_name_set_extern(self, newValueBytes, newValueLength) +@inline(never) fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValueWord0: Int32, _ newValueWord1: Int32, _ newValueWord2: Int32) -> Void { + return bjs_Animal_name_set_extern(self, newValueWord0, newValueWord1, newValueWord2) } #if arch(wasm32) @@ -19287,10 +19455,10 @@ 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 ret0 = name.bridgeJSWithLoweredParameter { (nameWord0, nameWord1, nameWord2) in let isCatValue = isCat.bridgeJSLowerParameter() let ageValue = age.bridgeJSLowerParameter() - let ret = bjs_Animal_init(nameBytes, nameLength, ageValue, isCatValue) + let ret = bjs_Animal_init(nameWord0, nameWord1, nameWord2, ageValue, isCatValue) return ret } let ret = ret0 @@ -19328,9 +19496,9 @@ func _$Animal_isCat_get(_ self: JSObject) throws(JSException) -> Bool { } func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + newValue.bridgeJSWithLoweredParameter { (newValueWord0, newValueWord1, newValueWord2) in let selfValue = self.bridgeJSLowerParameter() - bjs_Animal_name_set(selfValue, newValueBytes, newValueLength) + bjs_Animal_name_set(selfValue, newValueWord0, newValueWord1, newValueWord2) } if let error = _swift_js_take_exception() { throw error @@ -19504,21 +19672,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) -> Int32 +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 #else -fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 { +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsJoinStringThenStackParams(_ sBytes: Int32, _ sLength: Int32) -> Int32 { - return bjs_jsJoinStringThenStackParams_extern(sBytes, sLength) +@inline(never) fileprivate func bjs_jsJoinStringThenStackParams(_ sWord0: Int32, _ sWord1: Int32, _ sWord2: Int32) -> Int32 { + return bjs_jsJoinStringThenStackParams_extern(sWord0, sWord1, sWord2) } func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> String { - let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in + let ret0 = s.bridgeJSWithLoweredParameter { (sWord0, sWord1, sWord2) in let _ = b.bridgeJSLowerParameter() let _ = a.bridgeJSLowerParameter() - let ret = bjs_jsJoinStringThenStackParams(sBytes, sLength) + let ret = bjs_jsJoinStringThenStackParams(sWord0, sWord1, sWord2) return ret } let ret = ret0 @@ -19572,19 +19740,19 @@ func _$jsGenericRoundTripClass(_ value: T) thr #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericParsePoint") -fileprivate func bjs_jsGenericParsePoint_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void +fileprivate func bjs_jsGenericParsePoint_extern(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: Int32, _ _generic0TypeId: Int32) -> Void #else -fileprivate func bjs_jsGenericParsePoint_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { +fileprivate func bjs_jsGenericParsePoint_extern(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: 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) +@inline(never) fileprivate func bjs_jsGenericParsePoint(_ jsonWord0: Int32, _ jsonWord1: Int32, _ jsonWord2: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericParsePoint_extern(jsonWord0, jsonWord1, jsonWord2, _generic0TypeId) } func _$jsGenericParsePoint(_ json: String) throws(JSException) -> T { - json.bridgeJSWithLoweredParameter { (jsonBytes, jsonLength) in - bjs_jsGenericParsePoint(jsonBytes, jsonLength, T.bridgeJSTypeID) + json.bridgeJSWithLoweredParameter { (jsonWord0, jsonWord1, jsonWord2) in + bjs_jsGenericParsePoint(jsonWord0, jsonWord1, jsonWord2, T.bridgeJSTypeID) } if let error = _swift_js_take_exception() { throw error @@ -20398,19 +20566,19 @@ func _$defaultExport_get() throws(JSException) -> JSObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_nodeBasename") -fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +fileprivate func bjs_nodeBasename_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 #else -fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { +fileprivate func bjs_nodeBasename_extern(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: 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) +@inline(never) fileprivate func bjs_nodeBasename(_ pathWord0: Int32, _ pathWord1: Int32, _ pathWord2: Int32) -> Int32 { + return bjs_nodeBasename_extern(pathWord0, pathWord1, pathWord2) } func _$nodeBasename(_ path: String) throws(JSException) -> String { - let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in - let ret = bjs_nodeBasename(pathBytes, pathLength) + let ret0 = path.bridgeJSWithLoweredParameter { (pathWord0, pathWord1, pathWord2) in + let ret = bjs_nodeBasename(pathWord0, pathWord1, pathWord2) return ret } let ret = ret0 @@ -20422,20 +20590,20 @@ func _$nodeBasename(_ path: String) throws(JSException) -> String { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_nodeJoin") -fileprivate func bjs_nodeJoin_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 +fileprivate func bjs_nodeJoin_extern(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: Int32) -> Int32 #else -fileprivate func bjs_nodeJoin_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { +fileprivate func bjs_nodeJoin_extern(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: 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) +@inline(never) fileprivate func bjs_nodeJoin(_ lhsWord0: Int32, _ lhsWord1: Int32, _ lhsWord2: Int32, _ rhsWord0: Int32, _ rhsWord1: Int32, _ rhsWord2: Int32) -> Int32 { + return bjs_nodeJoin_extern(lhsWord0, lhsWord1, lhsWord2, rhsWord0, rhsWord1, rhsWord2) } 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) + let ret0 = lhs.bridgeJSWithLoweredParameter { (lhsWord0, lhsWord1, lhsWord2) in + let ret1 = rhs.bridgeJSWithLoweredParameter { (rhsWord0, rhsWord1, rhsWord2) in + let ret = bjs_nodeJoin(lhsWord0, lhsWord1, lhsWord2, rhsWord0, rhsWord1, rhsWord2) return ret } return ret1 @@ -20979,26 +21147,26 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_s #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(nameIsSome, nameBytes, nameLength) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(nameIsSome, nameWord0, nameWord1, nameWord2) } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameBytes, nameLength) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(_ nameIsSome: Int32, _ nameWord0: Int32, _ nameWord1: Int32, _ nameWord2: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameWord0, nameWord1, nameWord2) } #if arch(wasm32) @@ -21092,8 +21260,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalNumberUndefined(_ value: JSUnde } func _$OptionalSupportImports_jsRoundTripOptionalStringNull(_ name: Optional) throws(JSException) -> Optional { - name.bridgeJSWithLoweredParameter { (nameIsSome, nameBytes, nameLength) in - bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(nameIsSome, nameBytes, nameLength) + name.bridgeJSWithLoweredParameter { (nameIsSome, nameWord0, nameWord1, nameWord2) in + bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(nameIsSome, nameWord0, nameWord1, nameWord2) } if let error = _swift_js_take_exception() { throw error @@ -21102,8 +21270,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringNull(_ name: Optional) throws(JSException) -> JSUndefinedOr { - name.bridgeJSWithLoweredParameter { (nameIsSome, nameBytes, nameLength) in - bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(nameIsSome, nameBytes, nameLength) + name.bridgeJSWithLoweredParameter { (nameIsSome, nameWord0, nameWord1, nameWord2) in + bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(nameIsSome, nameWord0, nameWord1, nameWord2) } if let error = _swift_js_take_exception() { throw error @@ -21163,6 +21331,92 @@ func _$OptionalSupportImports_runJsOptionalSupportTests() throws(JSException) -> } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StringABIImports_jsEcho_static") +fileprivate func bjs_StringABIImports_jsEcho_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 +#else +fileprivate func bjs_StringABIImports_jsEcho_static_extern(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StringABIImports_jsEcho_static(_ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Int32 { + return bjs_StringABIImports_jsEcho_static_extern(valueWord0, valueWord1, valueWord2) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StringABIImports_jsEchoOptional_static") +fileprivate func bjs_StringABIImports_jsEchoOptional_static_extern(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void +#else +fileprivate func bjs_StringABIImports_jsEchoOptional_static_extern(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StringABIImports_jsEchoOptional_static(_ valueIsSome: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return bjs_StringABIImports_jsEchoOptional_static_extern(valueIsSome, valueWord0, valueWord1, valueWord2) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StringABIImports_jsEchoArray_static") +fileprivate func bjs_StringABIImports_jsEchoArray_static_extern() -> Void +#else +fileprivate func bjs_StringABIImports_jsEchoArray_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StringABIImports_jsEchoArray_static() -> Void { + return bjs_StringABIImports_jsEchoArray_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StringABIImports_runJsStringABITests_static") +fileprivate func bjs_StringABIImports_runJsStringABITests_static_extern() -> Void +#else +fileprivate func bjs_StringABIImports_runJsStringABITests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StringABIImports_runJsStringABITests_static() -> Void { + return bjs_StringABIImports_runJsStringABITests_static_extern() +} + +func _$StringABIImports_jsEcho(_ value: String) throws(JSException) -> String { + let ret0 = value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in + let ret = bjs_StringABIImports_jsEcho_static(valueWord0, valueWord1, valueWord2) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$StringABIImports_jsEchoOptional(_ value: Optional) throws(JSException) -> Optional { + value.bridgeJSWithLoweredParameter { (valueIsSome, valueWord0, valueWord1, valueWord2) in + bjs_StringABIImports_jsEchoOptional_static(valueIsSome, valueWord0, valueWord1, valueWord2) + } + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$StringABIImports_jsEchoArray(_ value: [String]) throws(JSException) -> [String] { + let _ = value.bridgeJSLowerParameter() + bjs_StringABIImports_jsEchoArray_static() + if let error = _swift_js_take_exception() { + throw error + } + return [String].bridgeJSLiftReturn() +} + +func _$StringABIImports_runJsStringABITests() throws(JSException) -> Void { + bjs_StringABIImports_runJsStringABITests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_gc") fileprivate func bjs_gc_extern() -> Void diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 4749c6eb3..d649d4e76 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -13085,6 +13085,447 @@ ], "swiftCallName" : "APIOptionalResult", "tsFullPath" : "APIOptionalResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "StringABIExports", + "staticMethods" : [ + { + "abiName" : "bjs_StringABIExports_static_echo", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "echo", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_echoOptional", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "echoOptional", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_echoArray", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "echoArray", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallEmpty", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallEmpty", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallASCII", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallASCII", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallEight", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallEight", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallNine", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallNine", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallTen", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallTen", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_smallUTF8", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "smallUTF8", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_largeImmortal", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "largeImmortal", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_largeImmortalAgain", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "largeImmortalAgain", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_largeDynamic", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "largeDynamic", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_immortalSubstring", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "immortalSubstring", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_optionalNone", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "optionalNone", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + }, + { + "abiName" : "bjs_StringABIExports_static_optionalSome", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "optionalSome", + "namespace" : [ + "StringABIExports" + ], + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "StringABIExports" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "StringABIExports", + "tsFullPath" : "StringABIExports" } ], "exposeToGlobal" : false, @@ -27823,6 +28264,135 @@ } ] }, + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "StringABIImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsEcho", + "parameters" : [ + { + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsEchoOptional", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsEchoArray", + "parameters" : [ + { + "name" : "value", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsStringABITests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, { "functions" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs new file mode 100644 index 000000000..8468e1faf --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs @@ -0,0 +1,53 @@ +// @ts-check + +import assert from 'node:assert'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["StringABIImports"]} + */ +export function getImports(importsContext) { + return { + jsEcho: (value) => value, + jsEchoArray: (value) => value, + jsEchoOptional: (value) => value ?? null, + runJsStringABITests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsStringABITests(exports); + }, + }; +} + +/** + * Swift→JS string layout coverage: small, immortal, dynamic, substring, optional. + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} rootExports + */ +export function runJsStringABITests(rootExports) { + const exports = rootExports.StringABIExports; + const immortal = "this is a long immortal literal string"; + + assert.equal(exports.smallEmpty(), ""); + assert.equal(exports.smallASCII(), "div"); + assert.equal(exports.smallEight(), "abcdefgh"); + assert.equal(exports.smallNine(), "abcdefghi"); + assert.equal(exports.smallTen(), "abcdefghij"); + assert.equal(exports.smallUTF8(), "é"); + assert.equal(exports.largeImmortal(), immortal); + assert.equal(exports.largeImmortalAgain(), immortal); + assert.equal(exports.largeDynamic(), immortal); + assert.equal(exports.immortalSubstring(), immortal.slice(10)); + assert.equal(exports.optionalNone(), null); + assert.equal(exports.optionalSome(), immortal); + const expected = samples.map((s) => s.startsWith("\ufeff") ? s.slice(1) : s); + for (let i = 0; i < samples.length; i++) { + assert.equal(exports.echo(samples[i]), expected[i]); + assert.equal(exports.echoOptional(samples[i]), expected[i]); + } + assert.deepEqual(exports.echoArray(samples), expected); +} + +const samples = [ + "abcdefé", "abcdefgé", "abcdefghé", "abcdefghié", "abc€", "abcdefg€", + "abc😄", "abcdef😄", "abcdefg😄", "a\0b", "\ufeffx", "x\ufeff", + "\ufeff\ufeffx", "\ufeffabcdefghijk", "abc\ufeffdefghijk", "\ufeff\ufeffabcdefghijk", +]; diff --git a/Tests/BridgeJSRuntimeTests/StringABITests.swift b/Tests/BridgeJSRuntimeTests/StringABITests.swift new file mode 100644 index 000000000..c3f424011 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/StringABITests.swift @@ -0,0 +1,81 @@ +import XCTest +import JavaScriptKit +import JavaScriptEventLoop + +private let largeImmortalLiteral = "this is a long immortal literal string" + +@inline(never) +private func runtimeCopy(_ string: String) -> String { + String(decoding: Array(string.utf8), as: UTF8.self) +} + +@JSClass struct StringABIImports { + @JSFunction static func jsEcho(_ value: String) throws(JSException) -> String + @JSFunction static func jsEchoOptional(_ value: String?) throws(JSException) -> String? + @JSFunction static func jsEchoArray(_ value: [String]) throws(JSException) -> [String] + @JSFunction static func runJsStringABITests() throws(JSException) +} + +@JS enum StringABIExports { + @JS static func echo(_ value: String) -> String { value } + @JS static func echoOptional(_ value: String?) -> String? { value } + @JS static func echoArray(_ value: [String]) -> [String] { value } + @JS static func smallEmpty() -> String { "" } + @JS static func smallASCII() -> String { "div" } + @JS static func smallEight() -> String { "abcdefgh" } + @JS static func smallNine() -> String { "abcdefghi" } + @JS static func smallTen() -> String { "abcdefghij" } + @JS static func smallUTF8() -> String { "é" } + @JS static func largeImmortal() -> String { largeImmortalLiteral } + @JS static func largeImmortalAgain() -> String { largeImmortalLiteral } + @JS static func largeDynamic() -> String { runtimeCopy(largeImmortalLiteral) } + @JS static func immortalSubstring() -> String { String(largeImmortalLiteral.dropFirst(10)) } + @JS static func optionalNone() -> String? { nil } + @JS static func optionalSome() -> String? { largeImmortalLiteral } +} + +final class StringABITests: XCTestCase { + func testRunJsStringABITests() throws { + try StringABIImports.runJsStringABITests() + } + + func testUnicodeAndBOMParametersAndStacks() throws { + let samples = [ + "abcdefé", "abcdefgé", "abcdefghé", "abcdefghié", + "abc€", "abcdefg€", "abc😄", "abcdef😄", "abcdefg😄", "a\0b", + "\u{FEFF}x", "x\u{FEFF}", "\u{FEFF}\u{FEFF}x", + "\u{FEFF}abcdefghijk", "abc\u{FEFF}defghijk", "\u{FEFF}\u{FEFF}abcdefghijk", + ] + let expected = samples.map { $0.first == "\u{FEFF}" ? String($0.dropFirst()) : $0 } + for (input, output) in zip(samples, expected) { + try XCTAssertEqual(StringABIImports.jsEcho(input), output) + try XCTAssertEqual(StringABIImports.jsEchoOptional(input), output) + } + try XCTAssertEqual(StringABIImports.jsEchoArray(samples), expected) + } + + func testImportEchoesSmallStrings() throws { + try XCTAssertEqual(StringABIImports.jsEcho(""), "") + try XCTAssertEqual(StringABIImports.jsEcho("div"), "div") + try XCTAssertEqual(StringABIImports.jsEcho("abcdefgh"), "abcdefgh") + try XCTAssertEqual(StringABIImports.jsEcho("abcdefghi"), "abcdefghi") + try XCTAssertEqual(StringABIImports.jsEcho("abcdefghij"), "abcdefghij") + try XCTAssertEqual(StringABIImports.jsEcho("é"), "é") + } + + func testImportEchoesLargeImmortalAndDynamicStrings() throws { + try XCTAssertEqual(StringABIImports.jsEcho(largeImmortalLiteral), largeImmortalLiteral) + try XCTAssertEqual(StringABIImports.jsEcho(largeImmortalLiteral), largeImmortalLiteral) + try XCTAssertEqual(StringABIImports.jsEcho(runtimeCopy(largeImmortalLiteral)), largeImmortalLiteral) + try XCTAssertEqual( + StringABIImports.jsEcho(String(largeImmortalLiteral.dropFirst(10))), + String(largeImmortalLiteral.dropFirst(10)) + ) + } + + func testImportEchoesOptionalStrings() throws { + try XCTAssertNil(StringABIImports.jsEchoOptional(nil)) + try XCTAssertEqual(StringABIImports.jsEchoOptional("div"), "div") + try XCTAssertEqual(StringABIImports.jsEchoOptional(largeImmortalLiteral), largeImmortalLiteral) + } +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 5287df791..8a109bcb5 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -11,6 +11,7 @@ import { getImports as getClosureThrowsImports } from './BridgeJSRuntimeTests/Ja 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 getStringABIImports } from './BridgeJSRuntimeTests/JavaScript/StringABITests.mjs'; import { getImports as getArraySupportImports, ArrayElementObject } from './BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs'; import { getImports as getDictionarySupportImports } from './BridgeJSRuntimeTests/JavaScript/DictionarySupportTests.mjs'; import { getImports as getDefaultArgumentImports } from './BridgeJSRuntimeTests/JavaScript/DefaultArgumentTests.mjs'; @@ -212,6 +213,7 @@ export async function setupOptions(options, context) { ClosureAsyncImports: getClosureAsyncImports(importsContext), SwiftClassSupportImports: getSwiftClassSupportImports(importsContext), OptionalSupportImports: getOptionalSupportImports(importsContext), + StringABIImports: getStringABIImports(importsContext), ArraySupportImports: getArraySupportImports(importsContext), DictionarySupportImports: getDictionarySupportImports(importsContext), DefaultArgumentImports: getDefaultArgumentImports(importsContext), @@ -289,6 +291,12 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.roundTripBool(v), v); } for (const v of [ + "", + "div", + "abcdefgh", + "abcdefghi", + "abcdefghij", + "é", "Hello, world!", "😄", "こんにちは", From c68ee9bdebfa28176ebd648d3b51c1cfa1a92a99 Mon Sep 17 00:00:00 2001 From: Simon Leeb <52261246+sliemeobn@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:45:23 +0200 Subject: [PATCH 125/140] Preserve BOMs in decoded strings (#817) --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 5 +--- .../Inputs/StringDecoderTests.mjs | 23 +++++++++++-------- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 5 +--- .../BridgeJSLinkTests/AliasInClosure.js | 5 +--- .../BridgeJSLinkTests/ArrayTypes.js | 5 +--- .../__Snapshots__/BridgeJSLinkTests/Async.js | 5 +--- .../AsyncAssociatedValueEnum.js | 5 +--- .../BridgeJSLinkTests/AsyncImport.js | 5 +--- .../BridgeJSLinkTests/AsyncStaticImport.js | 5 +--- .../BridgeJSLinkTests/ClassWithNestedTypes.js | 5 +--- .../BridgeJSLinkTests/DefaultParameters.js | 5 +--- .../BridgeJSLinkTests/DictionaryTypes.js | 5 +--- .../BridgeJSLinkTests/DocComments.js | 5 +--- .../BridgeJSLinkTests/EnumAlias.js | 5 +--- .../BridgeJSLinkTests/EnumAssociatedValue.js | 5 +--- .../EnumAssociatedValueImport.js | 5 +--- .../BridgeJSLinkTests/EnumCase.js | 5 +--- .../BridgeJSLinkTests/EnumCaseImport.js | 5 +--- .../BridgeJSLinkTests/EnumNamespace.Global.js | 5 +--- .../BridgeJSLinkTests/EnumNamespace.js | 5 +--- .../BridgeJSLinkTests/EnumRawType.js | 5 +--- .../BridgeJSLinkTests/ExtensionNestedTypes.js | 5 +--- .../ExtensionOrderIndependence.js | 5 +--- .../BridgeJSLinkTests/ExtensionScopeParity.js | 5 +--- .../BridgeJSLinkTests/FixedWidthIntegers.js | 5 +--- .../BridgeJSLinkTests/GenericImports.js | 5 +--- .../BridgeJSLinkTests/GlobalGetter.js | 5 +--- .../BridgeJSLinkTests/GlobalThisImports.js | 5 +--- .../IdentityModeClass.ConfigPointer.js | 5 +--- .../IdentityModeClass.PerClass.js | 5 +--- .../BridgeJSLinkTests/IdentityModeClass.js | 5 +--- .../BridgeJSLinkTests/ImportArray.js | 5 +--- .../ImportedTypeInExportedInterface.js | 5 +--- .../BridgeJSLinkTests/InvalidPropertyNames.js | 5 +--- .../BridgeJSLinkTests/JSClass.js | 5 +--- .../JSClassStaticFunctions.js | 5 +--- .../BridgeJSLinkTests/JSImportBareModule.js | 5 +--- .../JSImportBareModuleFallback.js | 5 +--- .../BridgeJSLinkTests/JSImportModule.js | 5 +--- .../BridgeJSLinkTests/JSNameOverride.js | 5 +--- .../BridgeJSLinkTests/JSNameTypes.js | 5 +--- .../BridgeJSLinkTests/JSTypedArrayTypes.js | 5 +--- .../BridgeJSLinkTests/JSValue.js | 5 +--- .../BridgeJSLinkTests/MixedGlobal.js | 5 +--- .../BridgeJSLinkTests/MixedModules.js | 5 +--- .../BridgeJSLinkTests/MixedPrivate.js | 5 +--- .../NamespacedClassSignature.js | 5 +--- .../BridgeJSLinkTests/Namespaces.Global.js | 5 +--- .../BridgeJSLinkTests/Namespaces.js | 5 +--- .../BridgeJSLinkTests/NestedType.js | 5 +--- .../NestedTypeNameCollision.js | 5 +--- .../BridgeJSLinkTests/Optionals.js | 5 +--- .../BridgeJSLinkTests/PrimitiveParameters.js | 5 +--- .../BridgeJSLinkTests/PrimitiveReturn.js | 5 +--- .../BridgeJSLinkTests/PropertyTypes.js | 5 +--- .../BridgeJSLinkTests/Protocol.js | 5 +--- .../BridgeJSLinkTests/ProtocolInClosure.js | 5 +--- .../RelativeQualifiedTypes.js | 5 +--- .../StaticFunctions.Global.js | 5 +--- .../BridgeJSLinkTests/StaticFunctions.js | 5 +--- .../StaticProperties.Global.js | 5 +--- .../BridgeJSLinkTests/StaticProperties.js | 5 +--- .../BridgeJSLinkTests/StringParameter.js | 5 +--- .../BridgeJSLinkTests/StringReturn.js | 5 +--- .../StructWithNestedTypes.js | 5 +--- .../BridgeJSLinkTests/SwiftClass.js | 5 +--- .../BridgeJSLinkTests/SwiftClosure.js | 5 +--- .../BridgeJSLinkTests/SwiftClosureImports.js | 5 +--- .../BridgeJSLinkTests/SwiftStruct.js | 5 +--- .../BridgeJSLinkTests/SwiftStructImports.js | 5 +--- .../SwiftTypedClosureAccess.js | 5 +--- .../__Snapshots__/BridgeJSLinkTests/Throws.js | 5 +--- .../BridgeJSLinkTests/UnsafePointer.js | 5 +--- .../VoidParameterVoidReturn.js | 5 +--- .../JavaScript/StringABITests.mjs | 9 ++++---- .../BridgeJSRuntimeTests/StringABITests.swift | 11 ++++----- 76 files changed, 96 insertions(+), 312 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 7f4ecab03..8f1c84622 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -346,7 +346,6 @@ public struct BridgeJSLink { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -361,8 +360,6 @@ public struct BridgeJSLink { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) @@ -487,7 +484,7 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedDecodeString);", "let \(JSGlueVariableScope.reservedDecodeUTF8);", "const \(JSGlueVariableScope.reservedImmortalStrings) = new Map();", - "const \(JSGlueVariableScope.reservedTextDecoder) = new TextDecoder(\"utf-8\");", + "const \(JSGlueVariableScope.reservedTextDecoder) = new TextDecoder(\"utf-8\", { ignoreBOM: true });", "const \(JSGlueVariableScope.reservedTextEncoder) = new TextEncoder(\"utf-8\");", "let \(JSGlueVariableScope.reservedStorageToReturnString);", "let \(JSGlueVariableScope.reservedStorageToReturnBytes);", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs index 2aa88cf5d..73299ddc0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringDecoderTests.mjs @@ -6,7 +6,6 @@ const source = await readFile(process.argv[2] ?? new URL('../__Snapshots__/Bridg const shared = process.argv[3] === 'shared'; const { createInstantiator } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); const encoder = new TextEncoder(); -const decoder = new TextDecoder(); const swift = { memory: { heap: [], retain: (value) => value } }; const bridge = await createInstantiator({ getImports: () => ({}) }, swift); const imports = {}; @@ -35,21 +34,27 @@ function large(value, immortal = false, ptr = 64) { } const values = ['', 'div', 'abcdefgh', 'abcdefghi', 'abcdefghij', 'abcdefé', 'abcdefgé', 'abcdefghé', 'abcdefghié', 'abc€', 'abcdefg€', 'abc😄', 'abcdef😄', 'abcdefg😄', - 'a\0b', '\ufeff', '\ufeffx', 'x\ufeff', '\ufeff\ufeffx', '\ufeffabcdefghijk', - 'abc\ufeffdefghijk', '\ufeff\ufeffabcdefghijk']; -for (const value of values) { - const expected = decoder.decode(encoder.encode(value)); + '😄😄', 'éééé', 'a\0b', '\ufeff', '\ufeffx', '\ufeffabcde', '\ufeffabcdef', + 'x\ufeff', '\ufeff\ufeffx', '\ufeffabcdefghijk', + 'abc\ufeffdefghijk', '\ufeff\ufeffabcdefghijk', + // UTF-8 widths, the surrogate gap, and supplementary-plane boundaries. + '\u0080', '\u07ff', '\u0800', '\ud7ff', '\ue000', '\uffff', '\u{10000}', '\u{10ffff}']; +for (const [index, value] of values.entries()) { if (encoder.encode(value).length <= 8) { words = small(value); - assert.equal(exports.checkString(), expected); + assert.equal(exports.checkString(), value); + } + for (const immortal of [false, true]) { + // Distinct locations keep immortal cache entries faithful to Swift literals. + words = large(value, immortal, 64 + index * 64); + assert.equal(exports.checkString(), value); + assert.equal(exports.checkString(), value); } - words = large(value); - assert.equal(exports.checkString(), expected); } // Alternate full and short inputs: bytes outside count must never leak into the result. for (const value of ['abcd😄', 'é', 'abcde€', '\ufeff', 'abcdefgh', '', 'x\0', '€', '\ufeff\ufeff']) { words = small(value); - assert.equal(exports.checkString(), decoder.decode(encoder.encode(value))); + assert.equal(exports.checkString(), value); } // Every ASCII byte, including NUL, at every small-string length. for (let byte = 0; byte < 128; byte++) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index 422e26dd9..b434d4e5e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -17,7 +17,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -706,7 +706,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -721,8 +720,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index 5a7dc255e..d4174627e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -318,7 +318,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -333,8 +332,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index bb61c4fb5..f4c519fe9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -24,7 +24,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -768,7 +768,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -783,8 +782,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index b657a2188..33c4ff195 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -21,7 +21,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -752,7 +752,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -767,8 +766,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index d16d071b7..099a0756e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -18,7 +18,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -398,7 +398,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -413,8 +412,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index cc7b29f42..5b2a085ac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -530,7 +530,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -545,8 +544,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 406c5da24..7a265486b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -426,7 +426,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -441,8 +440,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index 3d0a66cc3..1d7ebeabf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -267,7 +267,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -282,8 +281,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 35417c66b..03afa8031 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -17,7 +17,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -645,7 +645,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -660,8 +659,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 1b796f0de..10f84209a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -620,7 +620,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -635,8 +634,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 0dae550a8..902f06ff9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -17,7 +17,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -284,7 +284,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -299,8 +298,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 897f9e772..3ff888129 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -243,7 +243,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -258,8 +257,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index afe2e8ac7..3f0c005f2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -92,7 +92,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -1205,7 +1205,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -1220,8 +1219,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index 4b71ac219..0d770ed41 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -18,7 +18,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -329,7 +329,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -344,8 +343,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index e87881f55..999d1847f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -35,7 +35,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -259,7 +259,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -274,8 +273,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index c816b3bf0..3a78dd143 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -267,7 +267,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -282,8 +281,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index f744a43f3..b838f4c96 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -55,7 +55,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -299,7 +299,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -314,8 +313,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index e43b2bcb9..929f55c86 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -36,7 +36,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -280,7 +280,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -295,8 +294,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index fd3640162..ce8d4ed42 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -86,7 +86,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -673,7 +673,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -688,8 +687,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js index 53690ed6a..1b54d416e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js @@ -27,7 +27,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -328,7 +328,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -343,8 +342,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js index e5a43fdc2..cda13ba4c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -270,7 +270,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -285,8 +284,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js index 5312f0fbd..d0d1ea8bd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js @@ -15,7 +15,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -270,7 +270,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -285,8 +284,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index af7fa150c..50d25d09b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -308,7 +308,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -323,8 +322,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index e2f71f878..49aaa5798 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -27,7 +27,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -966,7 +966,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -981,8 +980,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 77dcf0f7a..1d299cab4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -253,7 +253,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -268,8 +267,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index c5c7221d0..8c3f0b5b4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -278,7 +278,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -293,8 +292,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index f33437e89..cc70a978a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -250,7 +250,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -265,8 +264,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index 43901d4a2..b9b854e52 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -250,7 +250,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -265,8 +264,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index 43901d4a2..b9b854e52 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -250,7 +250,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -265,8 +264,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 893402b07..a3e0fd6d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -603,7 +603,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -618,8 +617,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 69a851251..4bfce3e14 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -615,7 +615,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -630,8 +629,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 8909352ce..edcedc1b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -416,7 +416,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -431,8 +430,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index 0c0f030f7..cbec50c8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -315,7 +315,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -330,8 +329,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index f730efb98..9cbaf2a3e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -298,7 +298,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -313,8 +312,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js index 23a5b1635..50ed98d9a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js @@ -17,7 +17,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -323,7 +323,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -338,8 +337,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js index 55ef14aa6..ca94e5a13 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js @@ -14,7 +14,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -267,7 +267,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -282,8 +281,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js index 589f570cf..af4273cc3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -14,7 +14,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -307,7 +307,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -322,8 +321,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 16219c83c..0190b9c65 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -272,7 +272,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -287,8 +286,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js index ad3e9096e..107f497fc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -248,7 +248,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -263,8 +262,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index f1ffa766f..9d03440f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -234,7 +234,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -249,8 +248,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 99742f97b..07d7ba167 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -591,7 +591,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -606,8 +605,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index bed72152c..964b97e3a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -242,7 +242,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -257,8 +256,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 75697b834..d8eee50de 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -250,7 +250,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -265,8 +264,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index c6f2fdffa..359f5ddd9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -242,7 +242,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -257,8 +256,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js index 79519e8f1..1d6b6c343 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -294,7 +294,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -309,8 +308,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 2e2667caa..a5f6d34f4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -589,7 +589,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -604,8 +603,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 33d18909a..b13010601 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -589,7 +589,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -604,8 +603,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index f46e610cd..82710d04b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -286,7 +286,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -301,8 +300,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js index 332fc4e42..541ad55df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -270,7 +270,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -285,8 +284,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 57c49fd4c..fb8018c44 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -871,7 +871,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -886,8 +885,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index a25de5e29..3b8c9adbc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -243,7 +243,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -258,8 +257,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index 2a92af613..1177dc82b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -254,7 +254,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -269,8 +268,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 39677e821..44eab0d15 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -242,7 +242,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -257,8 +256,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 192e93d8e..96f132fda 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -35,7 +35,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -941,7 +941,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -956,8 +955,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index aab8103f5..d6fa6f143 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -388,7 +388,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -403,8 +402,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js index a1b8f290c..06af75757 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -325,7 +325,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -340,8 +339,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 338cf237d..4cc10e4b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -22,7 +22,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -287,7 +287,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -302,8 +301,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index e474c82a6..b9c8414b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -22,7 +22,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -287,7 +287,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -302,8 +301,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index eb1b2d2ef..7eff82661 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -248,7 +248,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -263,8 +262,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index 95470ed56..f8aa35927 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -248,7 +248,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -263,8 +262,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index c76381468..6dc173b63 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -252,7 +252,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -267,8 +266,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index 0a0fc1650..eb4e4c37b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -245,7 +245,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -260,8 +259,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index 7c189df7e..f9b50f9f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -26,7 +26,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -322,7 +322,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -337,8 +336,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 293ea56da..e171064a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -270,7 +270,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -285,8 +284,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index dabb7595f..928cc44a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -41,7 +41,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -1587,7 +1587,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -1602,8 +1601,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 0a6690be9..c47a65b6b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -509,7 +509,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -524,8 +523,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index e336f8911..54aa63d69 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -16,7 +16,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -804,7 +804,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -819,8 +818,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index ff953c9a3..2ebef1501 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -607,7 +607,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -622,8 +621,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 8cec87d6e..80e2a1984 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -352,7 +352,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -367,8 +366,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 40bf7e8c2..5a575ffed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -234,7 +234,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -249,8 +248,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 435415b0f..ef00d53a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -259,7 +259,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -274,8 +273,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index ce27ff522..5abfccc3f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -11,7 +11,7 @@ export async function createInstantiator(options, swift) { let decodeString; let decodeUTF8; const immortalStrings = new Map(); - const textDecoder = new TextDecoder("utf-8"); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); const textEncoder = new TextEncoder("utf-8"); let tmpRetString; let tmpRetBytes; @@ -243,7 +243,6 @@ export async function createInstantiator(options, swift) { u6 = 0, u7 = 0; while (byteIndex < count) { - const start = byteIndex; const b0 = byteAt(word0, word1, byteIndex++); let codePoint; if (b0 < 128) codePoint = b0; @@ -258,8 +257,6 @@ export async function createInstantiator(options, swift) { b3 = byteAt(word0, word1, byteIndex++); codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); } - // Match TextDecoder: consume exactly one leading UTF-8 BOM. - if (start === 0 && codePoint === 0xfeff) continue; const supplementary = codePoint > 0xffff; const codeUnit = supplementary ? 0xd800 + ((codePoint - 0x10000) >>> 10) diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs index 8468e1faf..1ff321261 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/StringABITests.mjs @@ -38,16 +38,15 @@ export function runJsStringABITests(rootExports) { assert.equal(exports.immortalSubstring(), immortal.slice(10)); assert.equal(exports.optionalNone(), null); assert.equal(exports.optionalSome(), immortal); - const expected = samples.map((s) => s.startsWith("\ufeff") ? s.slice(1) : s); for (let i = 0; i < samples.length; i++) { - assert.equal(exports.echo(samples[i]), expected[i]); - assert.equal(exports.echoOptional(samples[i]), expected[i]); + assert.equal(exports.echo(samples[i]), samples[i]); + assert.equal(exports.echoOptional(samples[i]), samples[i]); } - assert.deepEqual(exports.echoArray(samples), expected); + assert.deepEqual(exports.echoArray(samples), samples); } const samples = [ "abcdefé", "abcdefgé", "abcdefghé", "abcdefghié", "abc€", "abcdefg€", - "abc😄", "abcdef😄", "abcdefg😄", "a\0b", "\ufeffx", "x\ufeff", + "abc😄", "abcdef😄", "abcdefg😄", "a\0b", "\ufeff", "\ufeffx", "\ufeffabcde", "\ufeffabcdef", "x\ufeff", "\ufeff\ufeffx", "\ufeffabcdefghijk", "abc\ufeffdefghijk", "\ufeff\ufeffabcdefghijk", ]; diff --git a/Tests/BridgeJSRuntimeTests/StringABITests.swift b/Tests/BridgeJSRuntimeTests/StringABITests.swift index c3f424011..5d2cae9b0 100644 --- a/Tests/BridgeJSRuntimeTests/StringABITests.swift +++ b/Tests/BridgeJSRuntimeTests/StringABITests.swift @@ -43,15 +43,14 @@ final class StringABITests: XCTestCase { let samples = [ "abcdefé", "abcdefgé", "abcdefghé", "abcdefghié", "abc€", "abcdefg€", "abc😄", "abcdef😄", "abcdefg😄", "a\0b", - "\u{FEFF}x", "x\u{FEFF}", "\u{FEFF}\u{FEFF}x", + "\u{FEFF}", "\u{FEFF}x", "\u{FEFF}abcde", "\u{FEFF}abcdef", "x\u{FEFF}", "\u{FEFF}\u{FEFF}x", "\u{FEFF}abcdefghijk", "abc\u{FEFF}defghijk", "\u{FEFF}\u{FEFF}abcdefghijk", ] - let expected = samples.map { $0.first == "\u{FEFF}" ? String($0.dropFirst()) : $0 } - for (input, output) in zip(samples, expected) { - try XCTAssertEqual(StringABIImports.jsEcho(input), output) - try XCTAssertEqual(StringABIImports.jsEchoOptional(input), output) + for input in samples { + try XCTAssertEqual(StringABIImports.jsEcho(input), input) + try XCTAssertEqual(StringABIImports.jsEchoOptional(input), input) } - try XCTAssertEqual(StringABIImports.jsEchoArray(samples), expected) + try XCTAssertEqual(StringABIImports.jsEchoArray(samples), samples) } func testImportEchoesSmallStrings() throws { From 67f3be5cc54fa8134cbccafd9c1a3026dd6b5750 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Wed, 14 Oct 2026 15:29:39 +1100 Subject: [PATCH 126/140] BridgeJS: Support `any T` and `(T)` (#819) --- .../Sources/BridgeJSCore/SwiftToSkeleton.swift | 15 +++++++++++++++ .../Inputs/MacroSwift/Protocol.swift | 8 ++++---- .../Inputs/MacroSwift/ProtocolInClosure.swift | 4 ++-- .../BridgeJSRuntimeTests/ArraySupportTests.swift | 2 +- Tests/BridgeJSRuntimeTests/ExportAPITests.swift | 16 ++++++++-------- 5 files changed, 30 insertions(+), 15 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 0f9f79c06..ad3722dac 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -436,6 +436,21 @@ public final class SwiftToSkeleton { return lookupType(for: attributedType.baseType, errors: &errors) } + // any P + if let existentialType = type.as(SomeOrAnyTypeSyntax.self), + existentialType.someOrAnySpecifier.tokenKind == .keyword(.any) + { + return lookupType(for: existentialType.constraint, errors: &errors) + } + + // (T) + if let tupleType = type.as(TupleTypeSyntax.self), + tupleType.elements.count == 1, + let element = tupleType.elements.first + { + return lookupType(for: element.type, errors: &errors) + } + // JSTypedArray if let identifierType = type.as(IdentifierTypeSyntax.self), identifierType.name.text == "JSTypedArray", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift index bdb700d69..0f65a4dcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift @@ -66,9 +66,9 @@ import JavaScriptKit var delegate: MyViewControllerDelegate @JS - var secondDelegate: MyViewControllerDelegate? + var secondDelegate: (any MyViewControllerDelegate)? - @JS init(delegate: MyViewControllerDelegate) { + @JS init(delegate: any MyViewControllerDelegate) { self.delegate = delegate } @@ -103,7 +103,7 @@ import JavaScriptKit var delegates: [MyViewControllerDelegate] @JS - var delegatesByName: [String: MyViewControllerDelegate] + var delegatesByName: [String: any MyViewControllerDelegate] @JS init(delegates: [MyViewControllerDelegate]) { self.delegates = delegates @@ -117,7 +117,7 @@ import JavaScriptKit } } -@JS func processDelegates(_ delegates: [MyViewControllerDelegate]) -> [MyViewControllerDelegate] +@JS func processDelegates(_ delegates: [any MyViewControllerDelegate]) -> [any MyViewControllerDelegate] @JS func processDelegatesByName( _ delegates: [String: MyViewControllerDelegate] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift index cb814adf2..660d1a834 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ProtocolInClosure.swift @@ -14,5 +14,5 @@ import JavaScriptKit @JS func processRenderable(_ item: Renderable, transform: (Renderable) -> String) -> String @JS func makeRenderableFactory(defaultName: String) -> () -> Renderable -@JS func roundtripRenderable(_ callback: (Renderable) -> Renderable) -> (Renderable) -> Renderable -@JS func processOptionalRenderable(_ callback: (Renderable?) -> String) -> String +@JS func roundtripRenderable(_ callback: (any Renderable) -> any Renderable) -> (any Renderable) -> any Renderable +@JS func processOptionalRenderable(_ callback: ((any Renderable)?) -> String) -> String diff --git a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift index 90c4b138e..3ff17cbfa 100644 --- a/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/ArraySupportTests.swift @@ -195,7 +195,7 @@ final class ArraySupportTests: XCTestCase { @JS static func roundTripStructArray(_ v: [DataPoint]) -> [DataPoint] { v } @JS static func roundTripSwiftClassArray(_ v: [Greeter]) -> [Greeter] { v } @JS static func roundTripNamespacedSwiftClassArray(_ v: [Utils.Converter]) -> [Utils.Converter] { v } - @JS static func roundTripProtocolArray(_ v: [ArrayElementProtocol]) -> [ArrayElementProtocol] { v } + @JS static func roundTripProtocolArray(_ v: [any ArrayElementProtocol]) -> [any ArrayElementProtocol] { v } @JS static func roundTripJSClassArray(_ v: [ArrayElementObject]) -> [ArrayElementObject] { v } @JS static func roundTripOptionalIntArray(_ v: [Int?]) -> [Int?] { v } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 8778c2c8e..142b2ae9b 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -966,9 +966,9 @@ enum GraphOperations { @JS class DataProcessorManager { @JS var processor: DataProcessor - @JS var backupProcessor: DataProcessor? + @JS var backupProcessor: (any DataProcessor)? - @JS init(processor: DataProcessor) { + @JS init(processor: any DataProcessor) { self.processor = processor self.backupProcessor = nil } @@ -1124,7 +1124,7 @@ enum GraphOperations { return SwiftDataProcessor() } - @JS static func createNativeProcessorOptional() -> DataProcessor? { + @JS static func createNativeProcessorOptional() -> (any DataProcessor)? { return SwiftDataProcessor() } @@ -1132,7 +1132,7 @@ enum GraphOperations { return nil } - @JS static func createNativeProcessorArray() -> [DataProcessor] { + @JS static func createNativeProcessorArray() -> [any DataProcessor] { let p1 = SwiftDataProcessor() p1.count = 10 let p2 = SwiftDataProcessor() @@ -1140,7 +1140,7 @@ enum GraphOperations { return [p1, p2] } - @JS static func createNativeProcessorDictionary() -> [String: DataProcessor] { + @JS static func createNativeProcessorDictionary() -> [String: any DataProcessor] { let p1 = SwiftDataProcessor() p1.count = 10 let p2 = SwiftDataProcessor() @@ -1317,12 +1317,12 @@ enum GraphOperations { } @JS func roundtripDataProcessor( - _ callback: @escaping (DataProcessor) -> DataProcessor - ) -> (DataProcessor) -> DataProcessor { + _ callback: @escaping (any DataProcessor) -> any DataProcessor + ) -> (any DataProcessor) -> any DataProcessor { return callback } - @JS func processOptionalDataProcessor(_ callback: (DataProcessor?) -> String) -> String { + @JS func processOptionalDataProcessor(_ callback: ((any DataProcessor)?) -> String) -> String { let processor = SwiftDataProcessor() processor.increment(by: 7) return callback(processor) + " | " + callback(nil) From 14c1336e758f7cc1567f353563f60d1d72a6834a Mon Sep 17 00:00:00 2001 From: William Taylor Date: Wed, 14 Oct 2026 15:49:47 +1100 Subject: [PATCH 127/140] BridgeJS: Support exporting protocol methods with async and throws --- .../Sources/BridgeJSCore/ExportSwift.swift | 2 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 22 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 9 + .../Inputs/MacroSwift/Protocol.swift | 12 + .../BridgeJSCodegenTests/Protocol.json | 149 +++++++ .../BridgeJSCodegenTests/Protocol.swift | 412 ++++++++++++++++++ .../BridgeJSLinkTests/AsyncImport.js | 38 +- .../BridgeJSLinkTests/AsyncStaticImport.js | 12 +- .../BridgeJSLinkTests/Protocol.d.ts | 6 + .../BridgeJSLinkTests/Protocol.js | 191 ++++++++ .../BridgeJSLinkTests/SwiftClosure.js | 38 +- .../BridgeJSLinkTests/SwiftClosureImports.js | 10 +- .../Exporting-Swift-Protocols.md | 2 + .../AsyncImportTests.swift | 15 + .../BridgeJSRuntimeTests/ExportAPITests.swift | 39 ++ .../Generated/BridgeJS.swift | 264 +++++++++++ .../Generated/JavaScript/BridgeJS.json | 327 ++++++++++++++ .../JavaScript/AsyncImportTests.mjs | 6 + .../JavaScript/ClosureAsyncTests.mjs | 8 + Tests/prelude.mjs | 130 +++++- 20 files changed, 1654 insertions(+), 38 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index df8c589ea..7d402aa9c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -1439,7 +1439,7 @@ struct ProtocolCodegen { let signature = SwiftSignatureBuilder.buildFunctionSignature( parameters: method.parameters, returnType: method.returnType, - effects: nil + effects: method.effects ) // Build extern declaration using helper function diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 8f1c84622..c97bdf293 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -2908,7 +2908,15 @@ extension BridgeJSLink { let s = JSGlueVariableScope.reservedSwift printer.write("const resolve = \(s).memory.getObject(resolveRef);") printer.write("const reject = \(s).memory.getObject(rejectRef);") - printer.write(contentsOf: body) + printer.write("try {") + printer.indent { + printer.write(contentsOf: body) + } + printer.write("} catch (error) {") + printer.indent { + printer.write("reject(error);") + } + printer.write("}") } printer.write("}") return printer.lines @@ -2930,7 +2938,7 @@ extension BridgeJSLink { private func call(callExpr: String) throws { if effects.isAsync { - body.write("\(callExpr).then(resolve, reject);") + body.write("Promise.resolve(\(callExpr)).then(resolve, reject);") return } if let name = returnType.referencedGenericName { @@ -2997,14 +3005,6 @@ extension BridgeJSLink { return try call(calleeExpr: calleeExpr) } - /// Generates an async method call with resolve/reject closure refs. - func callAsyncMethod(name: String) { - let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" - let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) - let callExpr = "\(calleeExpr)(\(parameterForwardings.joined(separator: ", ")))" - body.write("\(callExpr).then(resolve, reject);") - } - func callStaticMethod(on objectExpr: String, name: String) throws { let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) return try call(calleeExpr: calleeExpr) @@ -4235,7 +4235,7 @@ extension BridgeJSLink { method: ExportedFunction ) throws { let thunkBuilder = ImportedThunkBuilder( - effects: Effects(isAsync: false, isThrows: false), + effects: method.effects, returnType: method.returnType, context: .exportSwift, intrinsicRegistry: intrinsicRegistry diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 8da9f2e4e..d52e9122d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -607,6 +607,7 @@ public protocol BridgeSkeletonVisitor { accessLevel: BridgeJSAccessLevel ) mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) + mutating func visitProtocolMethod(_ method: ExportedFunction, accessLevel: BridgeJSAccessLevel) } public extension BridgeSkeletonVisitor { @@ -616,6 +617,7 @@ public extension BridgeSkeletonVisitor { accessLevel: BridgeJSAccessLevel ) {} mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) {} + mutating func visitProtocolMethod(_ method: ExportedFunction, accessLevel: BridgeJSAccessLevel) {} } public struct BridgeSkeletonWalker { @@ -681,6 +683,7 @@ public struct BridgeSkeletonWalker { } for proto in skeleton.protocols { for method in proto.methods { + visitor.visitProtocolMethod(method, accessLevel: currentAccessLevel) walk(method) } for property in proto.properties { @@ -1870,6 +1873,12 @@ public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { ) } + public mutating func visitProtocolMethod(_ method: ExportedFunction, accessLevel: BridgeJSAccessLevel) { + guard method.effects.isAsync else { return } + + recordInjectedSignatures(forReturnType: method.returnType, accessLevel: accessLevel) + } + private mutating func recordInjectedSignatures( forReturnType returnType: BridgeType, accessLevel: BridgeJSAccessLevel diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift index bdb700d69..8ddb3dfbd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift @@ -59,6 +59,10 @@ import JavaScriptKit func createEnum() -> ExampleEnum func handleResult(_ result: Result) func getResult() -> Result + func validate(_ value: Int) throws(JSException) -> Int + func loadLabel(_ key: String) async throws(JSException) -> String + func reset() async throws(JSException) + func fetchCount() async -> Int } @JS class MyViewController { @@ -95,6 +99,14 @@ import JavaScriptKit @JS func sendHelper(_ helper: Helper) { delegate.onHelperUpdated(helper) } + + @JS func validateValue(_ value: Int) throws(JSException) -> Int { + return try delegate.validate(value) + } + + @JS func loadLabel(_ key: String) async throws(JSException) -> String { + return try await delegate.loadLabel(key) + } } // Protocol array support diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index bc443c6c0..4fbec6b49 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -228,6 +228,62 @@ "returnType" : { "void" : { + } + } + }, + { + "abiName" : "bjs_MyViewController_validateValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validateValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_MyViewController_loadLabel", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "loadLabel", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + } } } @@ -831,6 +887,99 @@ "_0" : "Result" } } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_validate", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validate", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_loadLabel", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "loadLabel", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_reset", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "reset", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_fetchCount", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "fetchCount", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "name" : "MyViewControllerDelegate", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index a91524da5..3c4ba2a78 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1,3 +1,250 @@ +#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 (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") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending JSValue) -> Void { + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + Self( + 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 param0 = JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(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, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Word0: Int32, _ param0Word1: Int32, _ param0Word2: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Word0, param0Word1, param0Word2) +} + +#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) + param0.bridgeJSWithLoweredParameter { (param0Word0, param0Word1, param0Word2) in + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Word0, param0Word1, param0Word2) + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending String) -> Void { + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) -> Self { + Self( + 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 param0 = String.bridgeJSLiftParameter(param0Bytes, param0Length) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(param0) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModulesSi_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSi_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSi_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSi_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSi_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSi_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSi_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Int) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModulesSi_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending Int) -> Void { + static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Int) -> Void) -> Self { + Self( + makeClosure: make_swift_closure_TestModule_10TestModulesSi_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSi_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSi_y") +public func _invoke_swift_closure_TestModule_10TestModulesSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let param0 = Int.bridgeJSLiftParameter(param0) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(param0) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuley_y") +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_y(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuley_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_y") +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_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_TestModule_10TestModuley_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_y") +public func _invoke_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { func onSomethingHappened() -> Void { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -75,6 +322,39 @@ extension MyViewControllerDelegate where Self: _BridgedSwiftProtocolWrapper { return Result.bridgeJSLiftReturn(ret) } + func validate(_ value: Int) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_MyViewControllerDelegate_validate(jsObjectValue, valueValue) + if let error = _swift_js_take_exception() { throw error } + return Int.bridgeJSLiftReturn(ret) + } + + func loadLabel(_ key: String) async throws(JSException) -> String { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + key.bridgeJSWithLoweredParameter { (keyWord0, keyWord1, keyWord2) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_MyViewControllerDelegate_loadLabel(resolveRef, rejectRef, jsObjectValue, keyWord0, keyWord1, keyWord2) + } + } + return resolved + } + + func reset() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_MyViewControllerDelegate_reset(resolveRef, rejectRef, jsObjectValue) + } + } + + func fetchCount() async -> Int { + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<(sending Int) -> Void>.sending($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_MyViewControllerDelegate_fetchCount(resolveRef, rejectRef, jsObjectValue) + } + return resolved + } + var eventCount: Int { get { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -369,6 +649,54 @@ fileprivate func bjs_MyViewControllerDelegate_getResult_extern(_ jsObject: Int32 return bjs_MyViewControllerDelegate_getResult_extern(jsObject) } +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_validate") +fileprivate func bjs_MyViewControllerDelegate_validate_extern(_ jsObject: Int32, _ value: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_validate_extern(_ jsObject: Int32, _ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_validate(_ jsObject: Int32, _ value: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_validate_extern(jsObject, value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_loadLabel") +fileprivate func bjs_MyViewControllerDelegate_loadLabel_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_loadLabel_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_loadLabel(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void { + return bjs_MyViewControllerDelegate_loadLabel_extern(resolveRef, rejectRef, jsObject, keyWord0, keyWord1, keyWord2) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_reset") +fileprivate func bjs_MyViewControllerDelegate_reset_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_reset_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_reset(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_reset_extern(resolveRef, rejectRef, jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_fetchCount") +fileprivate func bjs_MyViewControllerDelegate_fetchCount_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_fetchCount_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_fetchCount(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_fetchCount_extern(resolveRef, rejectRef, jsObject) +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_eventCount_get") fileprivate func bjs_MyViewControllerDelegate_eventCount_get_extern(_ jsObject: Int32) -> Int32 @@ -888,6 +1216,47 @@ public func _bjs_MyViewController_sendHelper(_ _self: UnsafeMutableRawPointer, _ #endif } +@_expose(wasm, "bjs_MyViewController_validateValue") +@_cdecl("bjs_MyViewController_validateValue") +public func _bjs_MyViewController_validateValue(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let _self = MyViewController.bridgeJSLiftParameter(_self) + do { + let ret = try _self.validateValue(_: value) + 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_MyViewController_loadLabel") +@_cdecl("bjs_MyViewController_loadLabel") +public func _bjs_MyViewController_loadLabel(_ _self: UnsafeMutableRawPointer, _ keyBytes: Int32, _ keyLength: Int32) -> Int32 { + #if arch(wasm32) + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + let _self = MyViewController.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await _self.loadLabel(_: key) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_MyViewController_delegate_get") @_cdecl("bjs_MyViewController_delegate_get") public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) -> Int32 { @@ -1096,6 +1465,49 @@ extension Priority: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Priority.bridgeJSMakeTypeHandle() } +@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 (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 } +} + +@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, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueWord0: Int32, _ valueWord1: Int32, _ valueWord2: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueWord0, valueWord1, valueWord2) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + value.bridgeJSWithLoweredParameter { (valueWord0, valueWord1, valueWord2) in + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_TestModule_SS(promiseValue, valueWord0, valueWord1, valueWord2) + } + if let error = _swift_js_take_exception() { throw error } +} + #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) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index 5b2a085ac..856c42435 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -474,33 +474,57 @@ export async function createInstantiator(options, swift) { TestModule["bjs_asyncReturnVoid"] = function bjs_asyncReturnVoid(resolveRef, rejectRef) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.asyncReturnVoid().then(resolve, reject); + try { + Promise.resolve(imports.asyncReturnVoid()).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_asyncRoundTripInt"] = function bjs_asyncRoundTripInt(resolveRef, rejectRef, v) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.asyncRoundTripInt(v).then(resolve, reject); + try { + Promise.resolve(imports.asyncRoundTripInt(v)).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_asyncRoundTripString"] = function bjs_asyncRoundTripString(resolveRef, rejectRef, vWord0, vWord1, vWord2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const string = decodeString(vWord0, vWord1, vWord2); - imports.asyncRoundTripString(string).then(resolve, reject); + try { + const string = decodeString(vWord0, vWord1, vWord2); + Promise.resolve(imports.asyncRoundTripString(string)).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_asyncRoundTripBool"] = function bjs_asyncRoundTripBool(resolveRef, rejectRef, v) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.asyncRoundTripBool(v !== 0).then(resolve, reject); + try { + Promise.resolve(imports.asyncRoundTripBool(v !== 0)).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_asyncRoundTripDouble"] = function bjs_asyncRoundTripDouble(resolveRef, rejectRef, v) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.asyncRoundTripDouble(v).then(resolve, reject); + try { + Promise.resolve(imports.asyncRoundTripDouble(v)).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_asyncRoundTripJSObject"] = function bjs_asyncRoundTripJSObject(resolveRef, rejectRef, v) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.asyncRoundTripJSObject(swift.memory.getObject(v)).then(resolve, reject); + try { + Promise.resolve(imports.asyncRoundTripJSObject(swift.memory.getObject(v))).then(resolve, reject); + } catch (error) { + reject(error); + } } }, setInstance: (i) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 7a265486b..36d839ed9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -391,12 +391,20 @@ export async function createInstantiator(options, swift) { TestModule["bjs_AsyncBox_asyncStaticRoundTrip_static"] = function bjs_AsyncBox_asyncStaticRoundTrip_static(resolveRef, rejectRef, v) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.AsyncBox.asyncStaticRoundTrip(v).then(resolve, reject); + try { + Promise.resolve(imports.AsyncBox.asyncStaticRoundTrip(v)).then(resolve, reject); + } catch (error) { + reject(error); + } } TestModule["bjs_AsyncBox_asyncStaticVoid_static"] = function bjs_AsyncBox_asyncStaticVoid_static(resolveRef, rejectRef) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - imports.AsyncBox.asyncStaticVoid().then(resolve, reject); + try { + Promise.resolve(imports.AsyncBox.asyncStaticVoid()).then(resolve, reject); + } catch (error) { + reject(error); + } } }, setInstance: (i) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts index a413fa500..e9b099f70 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -17,6 +17,10 @@ export interface MyViewControllerDelegate { createEnum(): ExampleEnumTag; handleResult(result: ResultTag): void; getResult(): ResultTag; + validate(value: number): number; + loadLabel(key: string): Promise; + reset(): Promise; + fetchCount(): Promise; eventCount: number; readonly delegateName: string; optionalName: string | null; @@ -87,6 +91,8 @@ export interface MyViewController extends SwiftHeapObject { updateLabel(prefix: string, suffix: string): void; checkEvenCount(): boolean; sendHelper(helper: Helper): void; + validateValue(value: number): number; + loadLabel(key: string): Promise; delegate: MyViewControllerDelegate; secondDelegate: MyViewControllerDelegate | null; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 96f132fda..f07007c79 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -380,6 +380,31 @@ export async function createInstantiator(options, swift) { return jsValue; } + 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 = decodeUTF8(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); + }; + const __bjs_codec_M10TestModuleT24MyViewControllerDelegate = { lower: (v) => { const objId = swift.memory.retain(v); @@ -512,6 +537,22 @@ export async function createInstantiator(options, swift) { promise[__bjs_promiseSettlers] = { resolve, reject }; return swift.memory.retain(promise); } + bjs["promise_resolve_TestModule_SS"] = function(promise, valueWord0, valueWord1, valueWord2) { + try { + const string = decodeString(valueWord0, valueWord1, valueWord2); + 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; @@ -602,6 +643,95 @@ 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_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, param0Word0, param0Word1, param0Word2) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Word0, param0Word1, param0Word2); + 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); + } + bjs["invoke_js_callback_TestModule_10TestModulesSi_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + callback(param0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSi_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSi_y = function(param0) { + instance.exports.invoke_swift_closure_TestModule_10TestModulesSi_y(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSi_y); + } + bjs["invoke_js_callback_TestModule_10TestModuley_y"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + callback(); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuley_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_y = function() { + instance.exports.invoke_swift_closure_TestModule_10TestModuley_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_10TestModuley_y); + } // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; @@ -913,6 +1043,43 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_MyViewControllerDelegate_validate"] = function bjs_MyViewControllerDelegate_validate(self, value) { + try { + let ret = swift.memory.getObject(self).validate(value); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_MyViewControllerDelegate_loadLabel"] = function bjs_MyViewControllerDelegate_loadLabel(resolveRef, rejectRef, self, keyWord0, keyWord1, keyWord2) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + try { + const string = decodeString(keyWord0, keyWord1, keyWord2); + Promise.resolve(swift.memory.getObject(self).loadLabel(string)).then(resolve, reject); + } catch (error) { + reject(error); + } + } + TestModule["bjs_MyViewControllerDelegate_reset"] = function bjs_MyViewControllerDelegate_reset(resolveRef, rejectRef, self) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + try { + Promise.resolve(swift.memory.getObject(self).reset()).then(resolve, reject); + } catch (error) { + reject(error); + } + } + TestModule["bjs_MyViewControllerDelegate_fetchCount"] = function bjs_MyViewControllerDelegate_fetchCount(resolveRef, rejectRef, self) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + try { + Promise.resolve(swift.memory.getObject(self).fetchCount()).then(resolve, reject); + } catch (error) { + reject(error); + } + } }, setInstance: (i) => { if (memory !== i.exports.memory) immortalStrings.clear(); @@ -1182,6 +1349,30 @@ export async function createInstantiator(options, swift) { sendHelper(helper) { instance.exports.bjs_MyViewController_sendHelper(this.pointer, helper.pointer); } + validateValue(value) { + const ret = instance.exports.bjs_MyViewController_validateValue(this.pointer, value); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + } + loadLabel(key) { + const keyBytes = textEncoder.encode(key); + const keyId = swift.memory.retain(keyBytes); + const ret = instance.exports.bjs_MyViewController_loadLabel(this.pointer, keyId, keyBytes.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; + } get delegate() { const ret = instance.exports.bjs_MyViewController_delegate_get(this.pointer); const ret1 = swift.memory.getObject(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 928cc44a0..f56929d7c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -1380,9 +1380,13 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Word0, param0Word1, param0Word2); - callback(string).then(resolve, reject); + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Word0, param0Word1, param0Word2); + Promise.resolve(callback(string)).then(resolve, reject); + } catch (error) { + reject(error); + } } bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleYaKSS_SS = function(param0) { @@ -1404,8 +1408,12 @@ export async function createInstantiator(options, swift) { 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); + try { + const callback = swift.memory.getObject(callbackId); + Promise.resolve(callback(param0 !== 0)).then(resolve, reject); + } catch (error) { + reject(error); + } } bjs["make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleYaKSb_9APIResultO = function(param0) { @@ -1425,9 +1433,13 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Word0, param0Word1, param0Word2); - callback(string).then(resolve, reject); + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Word0, param0Word1, param0Word2); + Promise.resolve(callback(string)).then(resolve, reject); + } catch (error) { + reject(error); + } } bjs["make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleYaSS_6AnimalV = function(param0) { @@ -1443,9 +1455,13 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModuleYaSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Word0, param0Word1, param0Word2); - callback(string).then(resolve, reject); + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Word0, param0Word1, param0Word2); + Promise.resolve(callback(string)).then(resolve, reject); + } catch (error) { + reject(error); + } } bjs["make_swift_closure_TestModule_10TestModuleYaSS_SS"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleYaSS_SS = function(param0) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index c47a65b6b..3ba6f5c0f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -393,9 +393,13 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Word0, param0Word1, param0Word2) { const resolve = swift.memory.getObject(resolveRef); const reject = swift.memory.getObject(rejectRef); - const callback = swift.memory.getObject(callbackId); - const string = decodeString(param0Word0, param0Word1, param0Word2); - callback(string).then(resolve, reject); + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Word0, param0Word1, param0Word2); + Promise.resolve(callback(string)).then(resolve, reject); + } catch (error) { + reject(error); + } } bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleYaKSS_SS = function(param0) { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md index 4c91ba749..5bc907137 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md @@ -217,6 +217,8 @@ struct AnyCounter: Counter, _BridgedSwiftProtocolWrapper { | Swift Feature | Status | |:--------------|:-------| | Method requirements: `func foo(_ param: String?) -> FooClass?` | ✅ | +| Throwing method requirements: `func foo() throws(JSException)` | ✅ | +| Async method requirements: `func foo() async throws(JSException) -> Bar` | ✅ | | Property requirements: `var property: Type { get }` / `var property: Type { get set }` | ✅ | | Optional parameters / return values in methods | ✅ | | Optional properties | ✅ | diff --git a/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift index a092d111c..17184c427 100644 --- a/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift +++ b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift @@ -24,6 +24,8 @@ import JavaScriptKit @JSFunction static func jsAsyncRoundTripOptionalAssociatedValueEnum( _ v: AsyncImportedPayloadResult? ) async throws(JSException) -> AsyncImportedPayloadResult? + @JSFunction static func jsAsyncThrowSynchronously(_ message: String) async throws(JSException) -> Double + @JSFunction static func jsAsyncReturnNonPromise(_ v: Double) async throws(JSException) -> Double } @Suite struct AsyncImportTests { @@ -104,6 +106,19 @@ import JavaScriptKit } } + // MARK: - Non-Promise behavior + + @Test func asyncSynchronousThrowRejects() async throws { + let error = await #expect(throws: JSException.self) { + try await AsyncImportImports.jsAsyncThrowSynchronously("SyncFailure") + } + #expect(error?.thrownValue.object?["message"].string == "SyncFailure") + } + + @Test func asyncNonPromiseReturnResolves() async throws { + try #expect(await AsyncImportImports.jsAsyncReturnNonPromise(42) == 42) + } + // MARK: - Structured return type @Test func fetchWeatherData() async throws { diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 8778c2c8e..c09b84c95 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -961,6 +961,10 @@ enum GraphOperations { func createOptionalGreeter() -> Greeter? func handleAPIResult(_ result: APIResult?) func getAPIResult() -> APIResult? + func validate(_ value: Int) throws(JSException) -> Int + func loadLabel(_ key: String) async throws(JSException) -> String + func reset() async throws(JSException) + func fetchCount() async -> Int } @JS class DataProcessorManager { @@ -1053,6 +1057,22 @@ enum GraphOperations { @JS func setProcessorAPIResult(_ apiResult: APIResult?) { processor.handleAPIResult(apiResult) } + + @JS func validateProcessorValue(_ value: Int) throws(JSException) -> Int { + return try processor.validate(value) + } + + @JS func loadProcessorLabel(_ key: String) async throws(JSException) -> String { + return try await processor.loadLabel(key) + } + + @JS func resetProcessor() async throws(JSException) { + try await processor.reset() + } + + @JS func fetchProcessorCount() async -> Int { + return await processor.fetchCount() + } } @JS class SwiftDataProcessor: DataProcessor { @@ -1117,6 +1137,25 @@ enum GraphOperations { @JS func getAPIResult() -> APIResult? { return apiResult } + + @JS func validate(_ value: Int) throws(JSException) -> Int { + guard value >= 0 else { + throw JSException(JSError(message: "SwiftDataProcessor rejects negative values").jsValue) + } + return value + } + + @JS func loadLabel(_ key: String) async throws(JSException) -> String { + return "\(label):\(key)" + } + + @JS func reset() async throws(JSException) { + count = 0 + } + + @JS func fetchCount() async -> Int { + return count + } } @JS class ProtocolReturnTests { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 52799fa7c..b89bdb510 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4366,6 +4366,39 @@ extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturn(ret) } + func validate(_ value: Int) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_validate(jsObjectValue, valueValue) + if let error = _swift_js_take_exception() { throw error } + return Int.bridgeJSLiftReturn(ret) + } + + func loadLabel(_ key: String) async throws(JSException) -> String { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<(sending String) -> Void>.sending($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + key.bridgeJSWithLoweredParameter { (keyWord0, keyWord1, keyWord2) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_loadLabel(resolveRef, rejectRef, jsObjectValue, keyWord0, keyWord1, keyWord2) + } + } + return resolved + } + + func reset() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_reset(resolveRef, rejectRef, jsObjectValue) + } + } + + func fetchCount() async -> Int { + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<(sending Int) -> Void>.sending($0) }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>.sending($0) }) { resolveRef, rejectRef in + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_fetchCount(resolveRef, rejectRef, jsObjectValue) + } + return resolved + } + var count: Int { get { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -4634,6 +4667,54 @@ fileprivate func bjs_DataProcessor_getAPIResult_extern(_ jsObject: Int32) -> Int return bjs_DataProcessor_getAPIResult_extern(jsObject) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_validate") +fileprivate func bjs_DataProcessor_validate_extern(_ jsObject: Int32, _ value: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_validate_extern(_ jsObject: Int32, _ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_validate(_ jsObject: Int32, _ value: Int32) -> Int32 { + return bjs_DataProcessor_validate_extern(jsObject, value) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_loadLabel") +fileprivate func bjs_DataProcessor_loadLabel_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_loadLabel_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_loadLabel(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32, _ keyWord0: Int32, _ keyWord1: Int32, _ keyWord2: Int32) -> Void { + return bjs_DataProcessor_loadLabel_extern(resolveRef, rejectRef, jsObject, keyWord0, keyWord1, keyWord2) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_reset") +fileprivate func bjs_DataProcessor_reset_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_reset_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_reset(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + return bjs_DataProcessor_reset_extern(resolveRef, rejectRef, jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_fetchCount") +fileprivate func bjs_DataProcessor_fetchCount_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_fetchCount_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_fetchCount(_ resolveRef: Int32, _ rejectRef: Int32, _ jsObject: Int32) -> Void { + return bjs_DataProcessor_fetchCount_extern(resolveRef, rejectRef, jsObject) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_get") fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 @@ -14415,6 +14496,73 @@ public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutab #endif } +@_expose(wasm, "bjs_DataProcessorManager_validateProcessorValue") +@_cdecl("bjs_DataProcessorManager_validateProcessorValue") +public func _bjs_DataProcessorManager_validateProcessorValue(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + do { + let ret = try _self.validateProcessorValue(_: value) + 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_DataProcessorManager_loadProcessorLabel") +@_cdecl("bjs_DataProcessorManager_loadProcessorLabel") +public func _bjs_DataProcessorManager_loadProcessorLabel(_ _self: UnsafeMutableRawPointer, _ keyBytes: Int32, _ keyLength: Int32) -> Int32 { + #if arch(wasm32) + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await _self.loadProcessorLabel(_: key) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DataProcessorManager_resetProcessor") +@_cdecl("bjs_DataProcessorManager_resetProcessor") +public func _bjs_DataProcessorManager_resetProcessor(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) -> Void in + try await _self.resetProcessor() + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DataProcessorManager_fetchProcessorCount") +@_cdecl("bjs_DataProcessorManager_fetchProcessorCount") +public func _bjs_DataProcessorManager_fetchProcessorCount(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = DataProcessorManager.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await _self.fetchProcessorCount() + } + #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 { @@ -14644,6 +14792,73 @@ public func _bjs_SwiftDataProcessor_getAPIResult(_ _self: UnsafeMutableRawPointe #endif } +@_expose(wasm, "bjs_SwiftDataProcessor_validate") +@_cdecl("bjs_SwiftDataProcessor_validate") +public func _bjs_SwiftDataProcessor_validate(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + do { + let ret = try _self.validate(_: value) + 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_SwiftDataProcessor_loadLabel") +@_cdecl("bjs_SwiftDataProcessor_loadLabel") +public func _bjs_SwiftDataProcessor_loadLabel(_ _self: UnsafeMutableRawPointer, _ keyBytes: Int32, _ keyLength: Int32) -> Int32 { + #if arch(wasm32) + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await _self.loadLabel(_: key) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftDataProcessor_reset") +@_cdecl("bjs_SwiftDataProcessor_reset") +public func _bjs_SwiftDataProcessor_reset(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) -> Void in + try await _self.reset() + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftDataProcessor_fetchCount") +@_cdecl("bjs_SwiftDataProcessor_fetchCount") +public func _bjs_SwiftDataProcessor_fetchCount(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = SwiftDataProcessor.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await _self.fetchCount() + } + #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 { @@ -17729,6 +17944,30 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueE return bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(resolveRef, rejectRef, vIsSome, vCaseId) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncThrowSynchronously_static") +fileprivate func bjs_AsyncImportImports_jsAsyncThrowSynchronously_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncThrowSynchronously_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncThrowSynchronously_static(_ resolveRef: Int32, _ rejectRef: Int32, _ messageWord0: Int32, _ messageWord1: Int32, _ messageWord2: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncThrowSynchronously_static_extern(resolveRef, rejectRef, messageWord0, messageWord1, messageWord2) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncReturnNonPromise_static") +fileprivate func bjs_AsyncImportImports_jsAsyncReturnNonPromise_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncReturnNonPromise_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncReturnNonPromise_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Float64) -> Void { + return bjs_AsyncImportImports_jsAsyncReturnNonPromise_static_extern(resolveRef, rejectRef, v) +} + func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) @@ -17874,6 +18113,31 @@ func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optio return resolved } +func _$AsyncImportImports_jsAsyncThrowSynchronously(_ message: String) async throws(JSException) -> Double { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Double) -> Void>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + message.bridgeJSWithLoweredParameter { (messageWord0, messageWord1, messageWord2) in + bjs_AsyncImportImports_jsAsyncThrowSynchronously_static(resolveRef, rejectRef, messageWord0, messageWord1, messageWord2) + } + } + return resolved +} + +func _$AsyncImportImports_jsAsyncReturnNonPromise(_ v: Double) async throws(JSException) -> Double { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Double) -> Void>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + let vValue = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncReturnNonPromise_static(resolveRef, rejectRef, vValue) + } + 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 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index d649d4e76..9d5da0a7f 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -3019,6 +3019,99 @@ } } + }, + { + "abiName" : "bjs_DataProcessorManager_validateProcessorValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validateProcessorValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_DataProcessorManager_loadProcessorLabel", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "loadProcessorLabel", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessorManager_resetProcessor", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "resetProcessor", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessorManager_fetchProcessorCount", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "fetchProcessorCount", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "name" : "DataProcessorManager", @@ -3325,6 +3418,99 @@ "_1" : "null" } } + }, + { + "abiName" : "bjs_SwiftDataProcessor_validate", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validate", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_SwiftDataProcessor_loadLabel", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "loadLabel", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_SwiftDataProcessor_reset", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "reset", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_SwiftDataProcessor_fetchCount", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "fetchCount", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "name" : "SwiftDataProcessor", @@ -19336,6 +19522,99 @@ "_1" : "null" } } + }, + { + "abiName" : "bjs_DataProcessor_validate", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validate", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_DataProcessor_loadLabel", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "loadLabel", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_reset", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "reset", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_fetchCount", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "fetchCount", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "name" : "DataProcessor", @@ -23286,6 +23565,54 @@ "_1" : "null" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncThrowSynchronously", + "parameters" : [ + { + "name" : "message", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncReturnNonPromise", + "parameters" : [ + { + "name" : "v", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } } ] } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs index 9be7af1be..a0f9a6ebd 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs @@ -44,6 +44,12 @@ export function getImports(importsContext) { jsAsyncRoundTripOptionalAssociatedValueEnum: (v) => { return Promise.resolve(v); }, + jsAsyncThrowSynchronously: (message) => { + throw new Error(message); + }, + jsAsyncReturnNonPromise: (v) => { + return v; + }, }; } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs index 3267d8fd6..07b1ec1ed 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs @@ -38,6 +38,14 @@ export async function runJsClosureAsyncTests(exports) { assert.notEqual(directionAReject, null); assert.equal(directionAReject.message, "CallbackRejected"); + await assert.rejects( + () => exports.awaitAsyncCallback(() => { + throw new Error("CallbackThrewSynchronously"); + }), + (error) => error instanceof Error && error.message === "CallbackThrewSynchronously" + ); + assert.equal(await exports.awaitAsyncCallback((req) => `plain-${req}`), "swift-saw:plain-request"); + const parser = exports.makeAsyncParser(); const parsed = parser("42"); diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 8a109bcb5..f54e3a149 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -145,6 +145,7 @@ export async function setupOptions(options, context) { throw new Error("No exports!?"); } await runAsyncWorksTests(exports); + await testAsyncProtocolSupport(exports); return; }, AsyncImportImports: getAsyncImportImports(importsContext), @@ -1311,6 +1312,102 @@ function setupTestGlobals(global) { }; } +/** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +async function testAsyncProtocolSupport(exports) { + let processorValue = 3; + let shouldRejectReset = false; + const jsProcessor = { + count: 0, + name: "AsyncJSProcessor", + optionalTag: null, + direction: null, + optionalTheme: null, + httpStatus: null, + apiResult: null, + helper: new exports.Greeter("AsyncHelper"), + optionalHelper: null, + optionalCount: null, + increment(amount) { processorValue += amount; }, + getValue() { return processorValue; }, + setLabelElements(labelPrefix, labelSuffix) { }, + getLabel() { return "async"; }, + isEven() { return processorValue % 2 === 0; }, + processGreeter(greeter) { return ""; }, + createGreeter() { return new exports.Greeter("AsyncGreeter"); }, + processOptionalGreeter(greeter) { return ""; }, + createOptionalGreeter() { return null; }, + handleAPIResult(result) { }, + getAPIResult() { return { tag: exports.APIResult.Tag.Info }; }, + validate(value) { return value; }, + loadLabel(key) { + if (key === "invalid") { + throw new Error("Invalid key thrown synchronously"); + } + return (async () => { + await Promise.resolve(); + if (key === "missing") { + throw new Error(`No label for ${key}`); + } + return `async:${key}`; + })(); + }, + async reset() { + await Promise.resolve(); + if (shouldRejectReset) { + throw new Error("Reset rejected"); + } + processorValue = 0; + }, + fetchCount() { return Promise.resolve(processorValue); } + }; + + const jsManager = new exports.DataProcessorManager(jsProcessor); + + assert.equal(await jsManager.loadProcessorLabel("key"), "async:key"); + await assert.rejects( + () => jsManager.loadProcessorLabel("missing"), + (error) => error instanceof Error && error.message === "No label for missing" + ); + await assert.rejects( + () => jsManager.loadProcessorLabel("invalid"), + (error) => error instanceof Error && error.message === "Invalid key thrown synchronously" + ); + const [firstLabel, secondLabel] = await Promise.all([ + jsManager.loadProcessorLabel("first"), + jsManager.loadProcessorLabel("second"), + ]); + assert.equal(firstLabel, "async:first"); + assert.equal(secondLabel, "async:second"); + + assert.equal(await jsManager.fetchProcessorCount(), 3); + await jsManager.resetProcessor(); + assert.equal(await jsManager.fetchProcessorCount(), 0); + + shouldRejectReset = true; + jsManager.incrementByAmount(2); + await assert.rejects( + () => jsManager.resetProcessor(), + (error) => error instanceof Error && error.message === "Reset rejected" + ); + assert.equal(await jsManager.fetchProcessorCount(), 2); + + jsManager.release(); + jsProcessor.helper.release(); + + const swiftProcessor = new exports.SwiftDataProcessor(); + const swiftManager = new exports.DataProcessorManager(swiftProcessor); + + swiftManager.setProcessorLabel("Swift", "Label"); + swiftManager.incrementByAmount(4); + assert.equal(await swiftManager.loadProcessorLabel("key"), "SwiftLabel:key"); + assert.equal(await swiftManager.fetchProcessorCount(), 4); + await swiftManager.resetProcessor(); + assert.equal(await swiftManager.fetchProcessorCount(), 0); + + swiftManager.release(); + swiftProcessor.release(); +} + /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function testProtocolSupport(exports) { let processorValue = 0; @@ -1340,7 +1437,16 @@ function testProtocolSupport(exports) { }, createOptionalGreeter() { return new exports.Greeter("JSOptionalGreeter"); }, handleAPIResult(result) { lastAPIResult = result; }, - getAPIResult() { return lastAPIResult; } + getAPIResult() { return lastAPIResult; }, + validate(value) { + if (value < 0) { + throw new Error("JSProcessor rejects negative values"); + } + return value * 2; + }, + async loadLabel(key) { return `${processorLabel}:${key}`; }, + async reset() { processorValue = 0; }, + async fetchCount() { return processorValue; } }; const successResult = { tag: exports.Utilities.Result.Tag.Success, param0: "Operation completed" }; @@ -1444,6 +1550,13 @@ function testProtocolSupport(exports) { jsProcessor.optionalCount = null; assert.equal(jsProcessor.optionalCount, null); + assert.equal(jsManager.validateProcessorValue(21), 42); + assert.throws( + () => jsManager.validateProcessorValue(-1), + (error) => error instanceof Error && error.message === "JSProcessor rejects negative values" + ); + assert.equal(jsManager.validateProcessorValue(5), 10); + newHelper.release(); optHelper.release(); jsManager.release(); @@ -1497,6 +1610,9 @@ function testProtocolSupport(exports) { swiftManager.setProcessorAPIResult(successResult); assert.deepEqual(swiftProcessor.getAPIResult(), successResult); + assert.equal(swiftManager.validateProcessorValue(7), 7); + assert.throws(() => swiftManager.validateProcessorValue(-1), /SwiftDataProcessor rejects negative values/); + swiftManager.release(); swiftProcessor.release(); @@ -1522,7 +1638,11 @@ function testProtocolSupport(exports) { processOptionalGreeter(greeter) { return ""; }, createOptionalGreeter() { return null; }, handleAPIResult(result) { }, - getAPIResult() { return { tag: exports.APIResult.Tag.Info }; } + getAPIResult() { return { tag: exports.APIResult.Tag.Info }; }, + validate(value) { return value; }, + async loadLabel(key) { return ""; }, + async reset() { }, + async fetchCount() { return 0; } }; let mainValue = 0; @@ -1547,7 +1667,11 @@ function testProtocolSupport(exports) { processOptionalGreeter(greeter) { return ""; }, createOptionalGreeter() { return null; }, handleAPIResult(result) { }, - getAPIResult() { return { tag: exports.APIResult.Tag.Info }; } + getAPIResult() { return { tag: exports.APIResult.Tag.Info }; }, + validate(value) { return value; }, + async loadLabel(key) { return ""; }, + async reset() { }, + async fetchCount() { return 0; } }; const managerWithOptional = new exports.DataProcessorManager(mainProcessor); From 681bb0b231a2680a6b25256c54115f7313bcd386 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 15 Oct 2026 11:34:25 +0200 Subject: [PATCH 128/140] [NFC] BridgeJS: Update renderAsyncFunction doc comment --- Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index c97bdf293..8e7c4939c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -2897,9 +2897,8 @@ extension BridgeJSLink { /// Renders an async import function with resolve/reject closure refs. /// - /// The generated function takes `resolveRef` and `rejectRef` as the first parameters, - /// looks up the resolve/reject closures from memory, and executes the body which - /// chains `.then(resolve, reject)` on the import's returned Promise. + /// The generated function takes `resolveRef` and `rejectRef` as the first parameters + /// and settles them with the result of the import call. private func renderAsyncFunction(name: String?) -> [String] { let printer = CodeFragmentPrinter() let allParams = ["resolveRef", "rejectRef"] + parameterNames From 0b3eb04082aa9f71348259149f81cdbc8f58c1ee Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 16 Oct 2026 08:30:57 +0200 Subject: [PATCH 129/140] JavaScriptEventLoop: Add opt-in `yieldInterval` for host responsiveness --- .../JavaScriptEventLoop+YieldInterval.swift | 105 ++++++++++++++++++ .../JavaScriptEventLoop.swift | 20 ++++ Sources/JavaScriptEventLoop/JobQueue.swift | 14 +++ .../JavaScript-Interop-Cheat-Sheet.md | 1 + ...avaScriptEventLoopYieldIntervalTests.swift | 79 +++++++++++++ 5 files changed, 219 insertions(+) create mode 100644 Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift create mode 100644 Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift new file mode 100644 index 000000000..73effb850 --- /dev/null +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift @@ -0,0 +1,105 @@ +// Clock and host task scheduling for `JavaScriptEventLoop.yieldInterval`. + +import JavaScriptKit +import _Concurrency + +#if compiler(>=5.5) + +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +extension JavaScriptEventLoop { + + #if hasFeature(Embedded) + // `ContinuousClock` is unavailable in Embedded Swift; use `performance.now()` in milliseconds. + typealias DrainInstant = Double + + func drainClockNow() -> DrainInstant { + if performanceNow == nil { + let performance = JSObject.global.performance.object! + performanceNow = (performance, performance.now.function!) + } + return performanceNow!.now(this: performanceNow!.performance).number! + } + + func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { + let (seconds, attoseconds) = interval.components + let intervalMilliseconds = Double(seconds) * 1_000 + Double(attoseconds) / 1_000_000_000_000_000 + return drainClockNow() - start >= intervalMilliseconds + } + #else + typealias DrainInstant = ContinuousClock.Instant + + func drainClockNow() -> DrainInstant { + ContinuousClock.now + } + + func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { + start.duration(to: .now) >= interval + } + #endif + + /// Runs `body` in a new JavaScript task via `setImmediate`, `MessageChannel`, or `setTimeout`. + func queueHostTask(_ body: @escaping () -> Void) { + if hostTaskScheduler == nil { + hostTaskScheduler = Self.makeHostTaskScheduler() + } + hostTaskScheduler!(body) + } + + private static func makeHostTaskScheduler() -> (@escaping () -> Void) -> Void { + let global = JSObject.global + if let setImmediate = global.setImmediate.function { + return { body in + _ = setImmediate( + JSOneshotClosure { _ in + body() + return .undefined + } + ) + } + } + if let messageChannel = global.MessageChannel.function { + // Unlike nested `setTimeout` calls, messages are not clamped to 4 ms. + let channel = messageChannel.new(arguments: [JSValue]()) + let sender = channel.port1.object! + let postMessage = sender.postMessage.function! + let pending = PendingHostTasks() + let receiver = JSClosure { _ in + pending.runAll() + return .undefined + } + channel.port2.object!.onmessage = .object(receiver) + return { body in + pending.bodies.append(body) + // Keep `receiver` alive as long as the scheduler. + withExtendedLifetime(receiver) { + _ = postMessage(this: sender, JSValue.undefined) + } + } + } + let setTimeout = global.setTimeout.function! + return { body in + _ = setTimeout( + JSOneshotClosure { _ in + body() + return .undefined + }, + 0 + ) + } + } +} + +/// Bodies waiting for the next `MessageChannel` message. +private final class PendingHostTasks { + var bodies: [() -> Void] = [] + + func runAll() { + let bodies = self.bodies + self.bodies = [] + for body in bodies { + body() + } + } +} + +#endif diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift index ead6157bf..ffca27795 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift @@ -48,6 +48,26 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { /// A function that invokes a given closure after a specified number of milliseconds. public var setTimeout: (Double, @escaping () -> Void) -> Void + /// The maximum time to run queued jobs before yielding to the JavaScript event loop. + /// + /// By default (`nil`), all queued jobs run in a single microtask, so long-running async work + /// blocks rendering, input, and other JavaScript tasks until it completes. When set, the + /// remaining jobs continue in a new JavaScript task after the interval, at the cost of some + /// latency. A single job is never interrupted. + /// + /// ```swift + /// JavaScriptEventLoop.shared.yieldInterval = .milliseconds(16) + /// ``` + public var yieldInterval: Duration? + + /// Continues a drain that stopped at ``yieldInterval``. Created lazily. + var hostTaskScheduler: ((@escaping () -> Void) -> Void)? + + #if hasFeature(Embedded) + /// Cached `performance.now` used by ``yieldInterval`` in Embedded Swift. + var performanceNow: (performance: JSObject, now: JSFunction)? + #endif + /// A mutable state to manage internal job queue /// Note that this should be guarded atomically when supporting multi-threaded environment. var queueState = QueueState() diff --git a/Sources/JavaScriptEventLoop/JobQueue.swift b/Sources/JavaScriptEventLoop/JobQueue.swift index a0f2c4bbb..280ddb035 100644 --- a/Sources/JavaScriptEventLoop/JobQueue.swift +++ b/Sources/JavaScriptEventLoop/JobQueue.swift @@ -43,12 +43,26 @@ extension JavaScriptEventLoop { func runAllJobs() { assert(queueState.isSpinning) + // The clock is only read while `yieldInterval` is set. + var start: DrainInstant? = yieldInterval == nil ? nil : drainClockNow() while let job = self.claimNextFromQueue() { #if compiler(>=5.9) job.runSynchronously(on: self.asUnownedSerialExecutor()) #else job._runSynchronously(on: self.asUnownedSerialExecutor()) #endif + + if let yieldInterval, queueState.headJob != nil { + if let start { + if hasRun(since: start, for: yieldInterval) { + // Keep `isSpinning` set so new jobs wait for the continuation. + queueHostTask { self.runAllJobs() } + return + } + } else { + start = drainClockNow() + } + } } queueState.isSpinning = false diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/JavaScript-Interop-Cheat-Sheet.md b/Sources/JavaScriptKit/Documentation.docc/Articles/JavaScript-Interop-Cheat-Sheet.md index 4280a4637..b554e5a7b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/JavaScript-Interop-Cheat-Sheet.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/JavaScript-Interop-Cheat-Sheet.md @@ -373,4 +373,5 @@ let swiftPromise = JSPromise.async { - Use `JSPromise.async(body:)` (with `Void` or `JSValue` return type) to expose Swift `async/await` work to JavaScript callers. - To await JavaScript `Promise` from Swift, import `JavaScriptEventLoop`, call `JavaScriptEventLoop.installGlobalExecutor()` early, and use the `value` property. - The `value` property suspends until the promise resolves or rejects, rethrowing rejections as ``JSException``. +- Long-running async work blocks rendering and input until it completes. Set `JavaScriptEventLoop.shared.yieldInterval` (for example, `.milliseconds(16)`) to yield to the JavaScript event loop between jobs. diff --git a/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift new file mode 100644 index 000000000..4269b89b2 --- /dev/null +++ b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift @@ -0,0 +1,79 @@ +import JavaScriptEventLoop +import JavaScriptKit +import XCTest + +final class JavaScriptEventLoopYieldIntervalTests: XCTestCase { + final class Box: @unchecked Sendable { + var value: Value + init(_ value: Value) { self.value = value } + } + + override func tearDown() { + JavaScriptEventLoop.shared.yieldInterval = nil + super.tearDown() + } + + static func busyWait(milliseconds: Int) { + let end = ContinuousClock.now + .milliseconds(milliseconds) + while ContinuousClock.now < end {} + } + + /// Returns, for each busy task, whether a JavaScript timer scheduled before them had fired. + func timerRanAfterEachTask(count: Int, milliseconds: Int) async -> [Bool] { + let timerRan = Box(false) + _ = JSObject.global.setTimeout!( + JSOneshotClosure { _ in + timerRan.value = true + return .undefined + }, + 0 + ) + let observed = Box([Bool]()) + let tasks = (0.. Date: Fri, 16 Oct 2026 11:40:19 +0200 Subject: [PATCH 130/140] JavaScriptEventLoop: Read the clock less often with `yieldInterval` --- .../JavaScriptEventLoop+YieldInterval.swift | 10 ++++------ Sources/JavaScriptEventLoop/JobQueue.swift | 13 ++++++++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift index 73effb850..dbcd30b9f 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+YieldInterval.swift @@ -20,10 +20,8 @@ extension JavaScriptEventLoop { return performanceNow!.now(this: performanceNow!.performance).number! } - func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { - let (seconds, attoseconds) = interval.components - let intervalMilliseconds = Double(seconds) * 1_000 + Double(attoseconds) / 1_000_000_000_000_000 - return drainClockNow() - start >= intervalMilliseconds + func drainElapsed(since start: DrainInstant) -> Duration { + .milliseconds(drainClockNow() - start) } #else typealias DrainInstant = ContinuousClock.Instant @@ -32,8 +30,8 @@ extension JavaScriptEventLoop { ContinuousClock.now } - func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { - start.duration(to: .now) >= interval + func drainElapsed(since start: DrainInstant) -> Duration { + start.duration(to: .now) } #endif diff --git a/Sources/JavaScriptEventLoop/JobQueue.swift b/Sources/JavaScriptEventLoop/JobQueue.swift index 280ddb035..0dcbcdc17 100644 --- a/Sources/JavaScriptEventLoop/JobQueue.swift +++ b/Sources/JavaScriptEventLoop/JobQueue.swift @@ -45,6 +45,10 @@ extension JavaScriptEventLoop { // The clock is only read while `yieldInterval` is set. var start: DrainInstant? = yieldInterval == nil ? nil : drainClockNow() + // A clock read costs more than a small job. Read it every `clockStride` jobs, and double + // the stride (up to 256) while the drain is far from the interval. + var clockStride = 1 + var jobsUntilClockRead = 1 while let job = self.claimNextFromQueue() { #if compiler(>=5.9) job.runSynchronously(on: self.asUnownedSerialExecutor()) @@ -54,11 +58,18 @@ extension JavaScriptEventLoop { if let yieldInterval, queueState.headJob != nil { if let start { - if hasRun(since: start, for: yieldInterval) { + jobsUntilClockRead -= 1 + if jobsUntilClockRead > 0 { continue } + let elapsed = drainElapsed(since: start) + if elapsed >= yieldInterval { // Keep `isSpinning` set so new jobs wait for the continuation. queueHostTask { self.runAllJobs() } return } + if elapsed * 4 < yieldInterval { + clockStride = min(clockStride * 2, 256) + } + jobsUntilClockRead = clockStride } else { start = drainClockNow() } From ed4bedb226150c055a4ce0cee994faea41f846c2 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 20 Oct 2026 10:13:50 +1100 Subject: [PATCH 131/140] BridgeJS: Escape reserved words --- .../Sources/BridgeJSCore/ExportSwift.swift | 18 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 31 +- .../MacroSwift/ReservedWordParameters.swift | 1 + .../ReservedWordParameters.json | 81 ++++ .../ReservedWordParameters.swift | 13 + .../ReservedWordParameters.d.ts | 18 + .../ReservedWordParameters.js | 382 ++++++++++++++++++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 3 + .../Generated/BridgeJS.swift | 15 + .../Generated/JavaScript/BridgeJS.json | 55 +++ Tests/prelude.mjs | 1 + 11 files changed, 605 insertions(+), 13 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 7d402aa9c..cf0907fa9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -216,7 +216,7 @@ public class ExportSwift { let liftingInfo = try param.type.liftParameterInfo() let argumentsToLift: [String] if liftingInfo.parameters.count == 1 { - argumentsToLift = [param.name] + argumentsToLift = [param.escapedSwiftIdentifier] } else { argumentsToLift = liftingInfo.parameters.map { (name, _) in param.name + name.capitalizedFirstLetter } } @@ -227,7 +227,9 @@ public class ExportSwift { switch param.type { case .closure(let signature, _): typeNameForIntrinsic = param.type.swiftType - liftingExpr = ExprSyntax("_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: param.name))") + liftingExpr = ExprSyntax( + "_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: param.escapedSwiftIdentifier))" + ) case .swiftStruct(let structName): typeNameForIntrinsic = structName liftingExpr = ExprSyntax("\(raw: structName).bridgeJSLiftParameter()") @@ -252,7 +254,7 @@ public class ExportSwift { ) } - parameterBindings.insert("let \(raw: param.name) = \(liftingExpr)", at: 0) + parameterBindings.insert("let \(raw: param.escapedSwiftIdentifier) = \(liftingExpr)", at: 0) for (name, type) in zip(argumentsToLift, liftingInfo.parameters.map { $0.type }) { abiParameterSignatures.append((name, type)) } @@ -268,14 +270,14 @@ public class ExportSwift { } private func removeFirstLiftedParameter() -> String { - return parameters.removeFirst().name + return parameters.removeFirst().escapedSwiftIdentifier } private func renderCallStatement(callee: ExprSyntax, returnType: BridgeType) -> CodeBlockItemSyntax { let labeledParams = parameters.map { param in LabeledExprSyntax( label: param.label, - expression: DeclReferenceExprSyntax(baseName: .identifier(param.name)) + expression: DeclReferenceExprSyntax(baseName: .identifier(param.escapedSwiftIdentifier)) ) } var callExpr: ExprSyntax = @@ -1593,6 +1595,12 @@ struct ProtocolCodegen { } } +extension Parameter { + fileprivate var escapedSwiftIdentifier: String { + name.backtickIfNeeded() + } +} + extension WasmCoreType { var swiftType: String { switch self { diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 8e7c4939c..ee9531d31 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1758,7 +1758,7 @@ public struct BridgeJSLink { loweringFragment.parameters.count == 1, "Lowering fragment should have exactly one parameter to lower" ) - let paramName = scope.variable(param.name) + let paramName = scope.variable(param.escapedJSIdentifier) let loweredValues = try loweringFragment.printCode([paramName], context) parameterForwardings.append(contentsOf: loweredValues) } @@ -1950,7 +1950,7 @@ public struct BridgeJSLink { } let parameterSignatures = parameters.map { param in let optional = param.hasDefault ? "?" : "" - return "\(param.name)\(optional): \(resolveTypeScriptType(param.type))" + return "\(param.escapedJSIdentifier)\(optional): \(resolveTypeScriptType(param.type))" } return "(\(parameterSignatures.joined(separator: ", "))): \(returnTypeWithEffect)" } @@ -2669,7 +2669,7 @@ extension BridgeJSLink { if let constructor = klass.constructor { let paramSignatures = constructor.parameters.map { param in let optional = param.hasDefault ? "?" : "" - return "\(param.name)\(optional): \(resolveTypeScriptType(param.type))" + return "\(param.escapedJSIdentifier)\(optional): \(resolveTypeScriptType(param.type))" } printer.write( lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) @@ -4321,9 +4321,9 @@ enum DefaultValueUtils { return parameters.map { param in if let defaultValue = param.defaultValue { let defaultJs = format(defaultValue, as: .javascript, resolveTypeName: resolveTypeName) - return "\(param.name) = \(defaultJs)" + return "\(param.escapedJSIdentifier) = \(defaultJs)" } - return param.name + return param.escapedJSIdentifier }.joined(separator: ", ") } } @@ -4348,11 +4348,11 @@ extension BridgeJSLink { } switch (docText, defaultValue) { case let (.some(text), .some(value)): - tagLines.append("@param \(parameter.name) \(text) (default: \(value))") + tagLines.append("@param \(parameter.escapedJSIdentifier) \(text) (default: \(value))") case let (.some(text), .none): - tagLines.append("@param \(parameter.name) \(text)") + tagLines.append("@param \(parameter.escapedJSIdentifier) \(text)") case let (.none, .some(value)): - tagLines.append("@param \(parameter.name) - Optional parameter (default: \(value))") + tagLines.append("@param \(parameter.escapedJSIdentifier) - Optional parameter (default: \(value))") case (.none, .none): continue } @@ -4477,6 +4477,21 @@ struct BridgeJSLinkError: Error { let message: String } +extension Parameter { + // From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words + private static let javaScriptReservedWords: Set = [ + "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", + "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", + "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", + "with", "let", "static", "yield", "await", "enum", "implements", "interface", "package", "private", + "protected", "public", "arguments", "eval", + ] + + fileprivate var escapedJSIdentifier: String { + Self.javaScriptReservedWords.contains(name) ? "_\(name)" : name + } +} + extension ClosureSignature { fileprivate func renderTSFunctionType(renderType: (BridgeType) -> String) -> String { let renderedParameters = parameters.enumerated().map { index, parameter in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift new file mode 100644 index 000000000..2c4c062cb --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift @@ -0,0 +1 @@ +@JS func check(extension: Int, break: Double, function: Bool, in: String) {} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json new file mode 100644 index 000000000..c27a4eb46 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json @@ -0,0 +1,81 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_check", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "check", + "parameters" : [ + { + "label" : "extension", + "name" : "extension", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "break", + "name" : "break", + "type" : { + "double" : { + + } + } + }, + { + "label" : "function", + "name" : "function", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "in", + "name" : "in", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift new file mode 100644 index 000000000..b09e1a76d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift @@ -0,0 +1,13 @@ +@_expose(wasm, "bjs_check") +@_cdecl("bjs_check") +public func _bjs_check(_ `extension`: Int32, _ `break`: Float64, _ function: Int32, _ inBytes: Int32, _ inLength: Int32) -> Void { + #if arch(wasm32) + let `in` = String.bridgeJSLiftParameter(inBytes, inLength) + let function = Bool.bridgeJSLiftParameter(function) + let `break` = Double.bridgeJSLiftParameter(`break`) + let `extension` = Int.bridgeJSLiftParameter(`extension`) + check(extension: `extension`, break: `break`, function: function, in: `in`) + #else + fatalError("Only available on WebAssembly") + #endif +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts new file mode 100644 index 000000000..027a6b9db --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts @@ -0,0 +1,18 @@ +// 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 = { + check(extension: number, _break: number, _function: boolean, _in: string): void; +} +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/ReservedWordParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js new file mode 100644 index 000000000..0abe5fdbf --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js @@ -0,0 +1,382 @@ +// 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; + let decodeUTF8; + const immortalStrings = new Map(); + const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); + 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(word0, word1, word2) { + tmpRetString = decodeString(word0, word1, word2); + } + 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(word0, word1, word2) { + return swift.memory.retain(decodeString(word0, word1, word2)); + } + 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(word0, word1, word2) { + const value = decodeString(word0, word1, word2); + 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, word0, word1, word2) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(word0, word1, word2); + } + } + 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) => { + if (memory !== i.exports.memory) immortalStrings.clear(); + instance = i; + memory = instance.exports.memory; + + decodeUTF8 = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + decodeString = (() => { + const byteAt = (word0, word1, byteIndex) => + byteIndex < 4 + ? (word0 >>> (byteIndex * 8)) & 255 + : (word1 >>> ((byteIndex - 4) * 8)) & 255; + // Valid small Swift strings need at most eight UTF-16 code units. + const decodeSmallUTF8 = (word0, word1, count) => { + if (count > 8) { + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + let byteIndex = 0, + unitCount = 0, + u0 = 0, + u1 = 0, + u2 = 0, + u3 = 0, + u4 = 0, + u5 = 0, + u6 = 0, + u7 = 0; + while (byteIndex < count) { + const b0 = byteAt(word0, word1, byteIndex++); + let codePoint; + if (b0 < 128) codePoint = b0; + else if (b0 < 224) codePoint = ((b0 & 31) << 6) | (byteAt(word0, word1, byteIndex++) & 63); + else if (b0 < 240) { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 15) << 12) | ((b1 & 63) << 6) | (b2 & 63); + } else { + const b1 = byteAt(word0, word1, byteIndex++), + b2 = byteAt(word0, word1, byteIndex++), + b3 = byteAt(word0, word1, byteIndex++); + codePoint = ((b0 & 7) << 18) | ((b1 & 63) << 12) | ((b2 & 63) << 6) | (b3 & 63); + } + const supplementary = codePoint > 0xffff; + const codeUnit = supplementary + ? 0xd800 + ((codePoint - 0x10000) >>> 10) + : codePoint; + switch (unitCount++) { + case 0: + u0 = codeUnit; + break; + case 1: + u1 = codeUnit; + break; + case 2: + u2 = codeUnit; + break; + case 3: + u3 = codeUnit; + break; + case 4: + u4 = codeUnit; + break; + case 5: + u5 = codeUnit; + break; + case 6: + u6 = codeUnit; + break; + case 7: + u7 = codeUnit; + break; + } + if (supplementary) { + const lowSurrogate = 0xdc00 + ((codePoint - 0x10000) & 1023); + switch (unitCount++) { + case 0: + u0 = lowSurrogate; + break; + case 1: + u1 = lowSurrogate; + break; + case 2: + u2 = lowSurrogate; + break; + case 3: + u3 = lowSurrogate; + break; + case 4: + u4 = lowSurrogate; + break; + case 5: + u5 = lowSurrogate; + break; + case 6: + u6 = lowSurrogate; + break; + case 7: + u7 = lowSurrogate; + break; + } + } + } + switch (unitCount) { + case 0: + return ""; + case 1: + return String.fromCharCode(u0); + case 2: + return String.fromCharCode(u0, u1); + case 3: + return String.fromCharCode(u0, u1, u2); + case 4: + return String.fromCharCode(u0, u1, u2, u3); + case 5: + return String.fromCharCode(u0, u1, u2, u3, u4); + case 6: + return String.fromCharCode(u0, u1, u2, u3, u4, u5); + case 7: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6); + case 8: + return String.fromCharCode(u0, u1, u2, u3, u4, u5, u6, u7); + } + }; + const decodeSmall = (word0, word1, word2) => { + const count = (word2 >>> 8) & 0x0f; + if ((word2 & 0x4000 /* ASCII */) === 0) return decodeSmallUTF8(word0, word1, count); + const char = String.fromCharCode; + switch (count) { + case 0: return ""; + case 1: return char(word0 & 0xff); + case 2: return char(word0 & 0xff, (word0 >>> 8) & 0xff); + case 3: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff); + case 4: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24); + case 5: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff); + case 6: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff); + case 7: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff); + case 8: return char(word0 & 0xff, (word0 >>> 8) & 0xff, (word0 >>> 16) & 0xff, word0 >>> 24, word1 & 0xff, (word1 >>> 8) & 0xff, (word1 >>> 16) & 0xff, word1 >>> 24); + default: + throw new Error(`Unsupported Swift inline String length: ${count} UTF-8 bytes (maximum 8). The Swift String layout may have changed; update JavaScriptKit and regenerate BridgeJS glue.`); + } + }; + return (word0, word1, word2) => { + if (word2 & 0x2000 /* small */) return decodeSmall(word0, word1, word2); + const ptr = (word1 + 20 /* nativeBias */) >>> 0; + const len = word0 >>> 0; + if ((word2 & 0x8000 /* immortal */) === 0 || len >= 0x200000 /* 2^21 Number key */) return decodeUTF8(ptr, len); + const key = ptr + len * 0x100000000; + const cached = immortalStrings.get(key); + if (cached !== undefined) return cached; + const value = decodeUTF8(ptr, len); + immortalStrings.set(key, value); + return value; + }; + })(); + + 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 = { + check: function bjs_check(extension, _break, _function, _in) { + const _inBytes = textEncoder.encode(_in); + const _inId = swift.memory.retain(_inBytes); + instance.exports.bjs_check(extension, _break, _function, _inId, _inBytes.length); + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c231d0ce9..9e5892a87 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -22,6 +22,9 @@ func runJsWorks() -> Void @JS func roundTripString(v: String) -> String { return v } +@JS func describeReservedWordParameters(extension: Int, break: Double, function: Bool, in: String) -> String { + return "\(`extension`):\(`break`):\(function):\(`in`)" +} @JS func roundTripSwiftHeapObject(v: Greeter) -> Greeter { return v } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index b89bdb510..884ecb8e1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -10324,6 +10324,21 @@ public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { #endif } +@_expose(wasm, "bjs_describeReservedWordParameters") +@_cdecl("bjs_describeReservedWordParameters") +public func _bjs_describeReservedWordParameters(_ `extension`: Int32, _ `break`: Float64, _ function: Int32, _ inBytes: Int32, _ inLength: Int32) -> Void { + #if arch(wasm32) + let `in` = String.bridgeJSLiftParameter(inBytes, inLength) + let function = Bool.bridgeJSLiftParameter(function) + let `break` = Double.bridgeJSLiftParameter(`break`) + let `extension` = Int.bridgeJSLiftParameter(`extension`) + let ret = describeReservedWordParameters(extension: `extension`, break: `break`, function: function, in: `in`) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripSwiftHeapObject") @_cdecl("bjs_roundTripSwiftHeapObject") public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 9d5da0a7f..8598361b6 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -15214,6 +15214,61 @@ } } }, + { + "abiName" : "bjs_describeReservedWordParameters", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeReservedWordParameters", + "parameters" : [ + { + "label" : "extension", + "name" : "extension", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "break", + "name" : "break", + "type" : { + "double" : { + + } + } + }, + { + "label" : "function", + "name" : "function", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "in", + "name" : "in", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index f54e3a149..15631bcbe 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -305,6 +305,7 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { ]) { assert.equal(exports.roundTripString(v), v); } + assert.equal(exports.describeReservedWordParameters(1, 2.5, true, "in"), "1:2.5:true:in"); const dict = { a: 1, b: 2 }; assert.deepEqual(exports.roundTripDictionaryExport(dict), dict); const optDict = { hello: "world" }; From 89057a154b644b2ef12599636b44f46548dd279c Mon Sep 17 00:00:00 2001 From: William Taylor Date: Wed, 28 Oct 2026 16:12:22 +1100 Subject: [PATCH 132/140] BridgeJS: Escape on import too --- .../Sources/BridgeJSCore/ExportSwift.swift | 13 +- .../Sources/BridgeJSCore/ImportTS.swift | 42 +- .../BridgeJSCore/SwiftToSkeleton.swift | 2 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 122 +++--- .../Sources/BridgeJSLink/JSGlueGen.swift | 28 +- .../BridgeJSMacros/JSMacroSupport.swift | 5 +- .../MacroSwift/ReservedWordParameters.swift | 22 + .../ReservedWordParameters.json | 378 ++++++++++++++++++ .../ReservedWordParameters.swift | 267 +++++++++++++ .../ReservedWordParameters.d.ts | 27 ++ .../ReservedWordParameters.js | 172 ++++++++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 12 + .../Generated/BridgeJS.swift | 98 +++++ .../Generated/JavaScript/BridgeJS.json | 199 +++++++++ .../BridgeJSRuntimeTests/ImportAPITests.swift | 10 + Tests/prelude.mjs | 7 + 16 files changed, 1296 insertions(+), 108 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index cf0907fa9..3197f559c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -213,10 +213,11 @@ public class ExportSwift { func liftParameter(param: Parameter) throws { parameters.append(param) + let escapedName = param.escapedSwiftIdentifier let liftingInfo = try param.type.liftParameterInfo() let argumentsToLift: [String] if liftingInfo.parameters.count == 1 { - argumentsToLift = [param.escapedSwiftIdentifier] + argumentsToLift = [escapedName] } else { argumentsToLift = liftingInfo.parameters.map { (name, _) in param.name + name.capitalizedFirstLetter } } @@ -228,7 +229,7 @@ public class ExportSwift { case .closure(let signature, _): typeNameForIntrinsic = param.type.swiftType liftingExpr = ExprSyntax( - "_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: param.escapedSwiftIdentifier))" + "_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: escapedName))" ) case .swiftStruct(let structName): typeNameForIntrinsic = structName @@ -254,7 +255,7 @@ public class ExportSwift { ) } - parameterBindings.insert("let \(raw: param.escapedSwiftIdentifier) = \(liftingExpr)", at: 0) + parameterBindings.insert("let \(raw: param.escapedSwiftBindingIdentifier) = \(liftingExpr)", at: 0) for (name, type) in zip(argumentsToLift, liftingInfo.parameters.map { $0.type }) { abiParameterSignatures.append((name, type)) } @@ -1595,12 +1596,6 @@ struct ProtocolCodegen { } } -extension Parameter { - fileprivate var escapedSwiftIdentifier: String { - name.backtickIfNeeded() - } -} - extension WasmCoreType { var swiftType: String { switch self { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 841c0409c..504b955d2 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -143,7 +143,8 @@ public struct ImportTS { } func lowerParameter(param: Parameter) throws { - if let genericPush = param.type.genericStackPushStatement(value: param.name) { + let escapedName = param.escapedSwiftIdentifier + if let genericPush = param.type.genericStackPushStatement(value: escapedName) { stackLoweringStmts.insert(genericPush, at: 0) return } @@ -153,10 +154,10 @@ public struct ImportTS { switch param.type { case .closure(let signature, useJSTypedClosure: false): let jsTypedClosureType = BridgeType.closure(signature, useJSTypedClosure: true).swiftType - body.write("let \(param.name) = \(jsTypedClosureType)(\(param.name))") + body.write("let \(param.escapedSwiftBindingIdentifier) = \(jsTypedClosureType)(\(escapedName))") // The just created JSObject is not owned by the caller unlike those passed in parameters, // so we need to extend its lifetime during the call to ensure the JSObject.id is valid. - valuesToExtendLifetimeDuringCall.append(param.name) + valuesToExtendLifetimeDuringCall.append(escapedName) default: break } @@ -177,7 +178,7 @@ public struct ImportTS { if loweringInfo.useBorrowing { let returnVariableName = "ret\(borrowedArguments.count)" let assign = needsReturnVariable ? "let \(returnVariableName) = " : "" - body.write("\(assign)\(param.name).bridgeJSWithLoweredParameter { \(pattern) in") + body.write("\(assign)\(escapedName).bridgeJSWithLoweredParameter { \(pattern) in") body.indent() borrowedArguments.append( BorrowedArgument( @@ -190,10 +191,10 @@ public struct ImportTS { ) } else if case .nullable(.swiftProtocol(let protocolName), _) = param.type, context == .exportSwift { body.write("let \(pattern): (Int32, Int32)") - body.write("if let \(param.name) {") + body.write("if let \(param.escapedSwiftBindingIdentifier) {") body.indent { body.write( - "\(pattern) = (1, _bridgeJSUnwrapProtocolExportable(\(param.name), \"\(protocolName)\").bridgeJSLowerAsProtocolReturn())" + "\(pattern) = (1, _bridgeJSUnwrapProtocolExportable(\(escapedName), \"\(protocolName)\").bridgeJSLowerAsProtocolReturn())" ) } body.write("} else {") @@ -205,10 +206,10 @@ public struct ImportTS { let initializerExpr: ExprSyntax if case .swiftProtocol(let protocolName) = param.type, context == .exportSwift { initializerExpr = ExprSyntax( - "_bridgeJSUnwrapProtocolExportable(\(raw: param.name), \"\(raw: protocolName)\").bridgeJSLowerAsProtocolReturn()" + "_bridgeJSUnwrapProtocolExportable(\(raw: escapedName), \"\(raw: protocolName)\").bridgeJSLowerAsProtocolReturn()" ) } else { - initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + initializerExpr = ExprSyntax("\(raw: escapedName).bridgeJSLowerParameter()") } let binding = loweringInfo.loweredParameters.isEmpty ? "_" : pattern @@ -218,10 +219,10 @@ public struct ImportTS { // Add to signatures and forwardings (unified for both single and multiple) for (index, (paramName, type)) in loweringInfo.loweredParameters.enumerated() { - // For single parameter, use param.name; for multiple, use constructed name + // For single parameter, use the escaped name; for multiple, use constructed name let abiParamName: String if loweringInfo.loweredParameters.count == 1 { - abiParamName = param.name + abiParamName = escapedName } else { abiParamName = "\(param.name)\(paramName.capitalizedFirstLetter)" } @@ -723,20 +724,21 @@ struct SwiftSignatureBuilder { var out = "(" out += parameters.map { param in let label = param.label ?? param.name + let escapedName = param.escapedSwiftIdentifier let paramType = buildParameterTypeSyntax(from: param.type) if useWildcardLabels { // Always use wildcard labels: "_ name: Type" - return "_ \(param.name): \(paramType)" - } else if label == param.name { + return "_ \(escapedName): \(paramType)" + } else if SwiftToSkeleton.normalizeIdentifier(label) == param.name { // External label same as parameter name: "count: Int" - return "\(param.name): \(paramType)" + return "\(escapedName): \(paramType)" } else if param.label == nil { // No label specified: use wildcard "_ name: Type" - return "_ \(param.name): \(paramType)" + return "_ \(escapedName): \(paramType)" } else { // External label differs: "label count: Int" - return "\(label) \(param.name): \(paramType)" + return "\(label) \(escapedName): \(paramType)" } }.joined(separator: ", ") out += ")" @@ -1065,3 +1067,13 @@ extension String { return self.isValidSwiftIdentifier(for: .variableName) ? self : "`\(self)`" } } + +extension Parameter { + var escapedSwiftIdentifier: String { + name == "self" ? name : name.backtickIfNeeded() + } + + var escapedSwiftBindingIdentifier: String { + name.backtickIfNeeded() + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index ad3722dac..ef39000b1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1587,7 +1587,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { continue } - let name = param.secondName?.text ?? param.firstName.text + let name = SwiftToSkeleton.normalizeIdentifier(param.secondName?.text ?? param.firstName.text) let label = param.firstName.text let defaultValue: DefaultValue? diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index ee9531d31..686f8d1e0 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1730,6 +1730,9 @@ public struct BridgeJSLink { class ExportedThunkBuilder { var body: CodeFragmentPrinter var parameterForwardings: [String] = [] + + private var signatureParameters: [(parameter: Parameter, name: String)] = [] + let effects: Effects let scope: JSGlueVariableScope let context: IntrinsicJSFragment.PrintCodeContext @@ -1759,6 +1762,7 @@ public struct BridgeJSLink { "Lowering fragment should have exactly one parameter to lower" ) let paramName = scope.variable(param.escapedJSIdentifier) + signatureParameters.append((param, paramName)) let loweredValues = try loweringFragment.printCode([paramName], context) parameterForwardings.append(contentsOf: loweredValues) } @@ -1767,6 +1771,20 @@ public struct BridgeJSLink { parameterForwardings.append("this.pointer") } + var parameterList: String { + signatureParameters.map { parameter, name in + guard let defaultValue = parameter.defaultValue else { + return name + } + let defaultJs = DefaultValueUtils.format( + defaultValue, + as: .javascript, + resolveTypeName: context.defaultValueTypeName + ) + return "\(name) = \(defaultJs)" + }.joined(separator: ", ") + } + func call(abiName: String, returnType: BridgeType) throws -> String? { if effects.isAsync { return try _call(abiName: abiName, returnType: .jsObject(nil)) @@ -1830,17 +1848,11 @@ public struct BridgeJSLink { func renderFunction( name: String, - parameters: [Parameter], returnExpr: String?, declarationPrefixKeyword: String? ) -> [String] { let printer = CodeFragmentPrinter() - let parameterList = DefaultValueUtils.formatParameterList( - parameters, - resolveTypeName: context.defaultValueTypeName - ) - printer.write( "\(declarationPrefixKeyword.map { "\($0) "} ?? "")\(name)(\(parameterList)) {" ) @@ -1948,11 +1960,15 @@ public struct BridgeJSLink { } else { returnTypeWithEffect = resolveTypeScriptType(returnType) } - let parameterSignatures = parameters.map { param in + return "\(renderTSParameterList(parameters)): \(returnTypeWithEffect)" + } + + private func renderTSParameterList(_ parameters: [Parameter]) -> String { + let parameterSignatures = zip(parameters, parameters.uniqueJSIdentifiers).map { param, name in let optional = param.hasDefault ? "?" : "" - return "\(param.escapedJSIdentifier)\(optional): \(resolveTypeScriptType(param.type))" + return "\(name)\(optional): \(resolveTypeScriptType(param.type))" } - return "(\(parameterSignatures.joined(separator: ", "))): \(returnTypeWithEffect)" + return "(\(parameterSignatures.joined(separator: ", ")))" } private func renderGenericClause(_ genericParameters: [GenericParameter]) -> String { @@ -2062,11 +2078,7 @@ public struct BridgeJSLink { ) let constructorPrinter = CodeFragmentPrinter() - let paramList = DefaultValueUtils.formatParameterList( - constructor.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) - constructorPrinter.write("init: function(\(paramList)) {") + constructorPrinter.write("init: function(\(thunkBuilder.parameterList)) {") constructorPrinter.indent { thunkBuilder.renderFunctionBody(into: constructorPrinter, returnExpr: returnExpr) } @@ -2290,7 +2302,6 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let funcLines = thunkBuilder.renderFunction( name: function.abiName, - parameters: function.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "function" ) @@ -2341,7 +2352,6 @@ extension BridgeJSLink { let funcLines = thunkBuilder.renderFunction( name: function.resolvedJSName, - parameters: function.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "static" ) @@ -2371,11 +2381,7 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let printer = CodeFragmentPrinter() - let parameterList = DefaultValueUtils.formatParameterList( - function.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) - printer.write("\(function.resolvedJSName)(\(parameterList)) {") + printer.write("\(function.resolvedJSName)(\(thunkBuilder.parameterList)) {") printer.indent { thunkBuilder.renderFunctionBody(into: printer, returnExpr: returnExpr) } @@ -2407,7 +2413,6 @@ extension BridgeJSLink { let funcLines = thunkBuilder.renderFunction( name: function.abiName, - parameters: function.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "function" ) @@ -2431,12 +2436,8 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: method.abiName, returnType: method.returnType) let methodPrinter = CodeFragmentPrinter() - let parameterList = DefaultValueUtils.formatParameterList( - method.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) methodPrinter.write( - "\(method.resolvedJSName): function(\(parameterList)) {" + "\(method.resolvedJSName): function(\(thunkBuilder.parameterList)) {" ) methodPrinter.indent { thunkBuilder.renderFunctionBody(into: methodPrinter, returnExpr: returnExpr) @@ -2486,7 +2487,7 @@ extension BridgeJSLink { returnType: .void ) - propertyPrinter.write("set \(property.resolvedJSName)(value) {") + propertyPrinter.write("set \(property.resolvedJSName)(\(setterThunkBuilder.parameterList)) {") propertyPrinter.indent { setterThunkBuilder.renderFunctionBody(into: propertyPrinter, returnExpr: nil) } @@ -2540,13 +2541,8 @@ extension BridgeJSLink { try thunkBuilder.lowerParameter(param: param) } - let constructorParamList = DefaultValueUtils.formatParameterList( - constructor.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) - jsPrinter.indent { - jsPrinter.write("constructor(\(constructorParamList)) {") + jsPrinter.write("constructor(\(thunkBuilder.parameterList)) {") let returnExpr = thunkBuilder.callConstructor(abiName: constructor.abiName) let constructCall = "\(klass.resolvedJSName).__construct(\(returnExpr))" jsPrinter.indent { @@ -2574,7 +2570,6 @@ extension BridgeJSLink { jsPrinter.write( lines: thunkBuilder.renderFunction( name: method.resolvedJSName, - parameters: method.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "static" ) @@ -2595,7 +2590,6 @@ extension BridgeJSLink { jsPrinter.write( lines: thunkBuilder.renderFunction( name: method.resolvedJSName, - parameters: method.parameters, returnExpr: returnExpr, declarationPrefixKeyword: nil ) @@ -2667,14 +2661,10 @@ extension BridgeJSLink { printer.write("class \(klass.resolvedJSName) {") printer.indent { if let constructor = klass.constructor { - let paramSignatures = constructor.parameters.map { param in - let optional = param.hasDefault ? "?" : "" - return "\(param.escapedJSIdentifier)\(optional): \(resolveTypeScriptType(param.type))" - } printer.write( lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) ) - printer.write("constructor(\(paramSignatures.joined(separator: ", ")));") + printer.write("constructor\(renderTSParameterList(constructor.parameters));") } for method in klass.methods.sorted(by: { $0.resolvedJSName < $1.resolvedJSName }) { let staticKeyword = method.effects.isStatic ? "static " : "" @@ -2720,7 +2710,6 @@ extension BridgeJSLink { jsPrinter.write( lines: getterThunkBuilder.renderFunction( name: property.resolvedJSName, - parameters: [], returnExpr: getterReturnExpr, declarationPrefixKeyword: getterKeyword ) @@ -2748,7 +2737,6 @@ extension BridgeJSLink { jsPrinter.write( lines: setterThunkBuilder.renderFunction( name: property.resolvedJSName, - parameters: [.init(label: nil, name: "value", type: property.type)], returnExpr: nil, declarationPrefixKeyword: setterKeyword ) @@ -2823,7 +2811,7 @@ extension BridgeJSLink { message: "Generic codec for '\(name)' was not declared before lifting parameter '\(param.name)'" ) } - let valueVar = scope.variable(param.name) + let valueVar = scope.variable(param.escapedJSIdentifier) let liftExpr = GenericJSCodegen.genericCodecLiftExpression(type: param.type, codec: codecVar) ?? "\(codecVar).lift()" @@ -2836,8 +2824,9 @@ extension BridgeJSLink { if liftingFragment.parameters.count == 0 { valuesToLift = [] } else if liftingFragment.parameters.count == 1 { - parameterNames.append(param.name) - valuesToLift = [scope.variable(param.name)] + let name = scope.variable(param.escapedJSIdentifier) + parameterNames.append(name) + valuesToLift = [name] } else { valuesToLift = liftingFragment.parameters.map { scope.variable(param.name + $0.capitalizedFirstLetter) } parameterNames.append(contentsOf: valuesToLift) @@ -3525,7 +3514,7 @@ extension BridgeJSLink { ) let setterPrinter = CodeFragmentPrinter() - setterPrinter.write("set \(property.resolvedJSName)(value) {") + setterPrinter.write("set \(property.resolvedJSName)(\(setterThunkBuilder.parameterList)) {") setterPrinter.indent { setterPrinter.write(contentsOf: setterThunkBuilder.body) setterPrinter.write(lines: setterThunkBuilder.checkExceptionLines()) @@ -4312,20 +4301,6 @@ enum DefaultValueUtils { .replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") } - - /// Generates a JavaScript parameter list with default values - static func formatParameterList( - _ parameters: [Parameter], - resolveTypeName: (BridgeType, OutputFormat) -> String? = { _, _ in nil } - ) -> String { - return parameters.map { param in - if let defaultValue = param.defaultValue { - let defaultJs = format(defaultValue, as: .javascript, resolveTypeName: resolveTypeName) - return "\(param.escapedJSIdentifier) = \(defaultJs)" - } - return param.escapedJSIdentifier - }.joined(separator: ", ") - } } extension BridgeJSLink { @@ -4337,7 +4312,7 @@ extension BridgeJSLink { let resolveTypeName = makeCodecPrintContext(printer: CodeFragmentPrinter()).defaultValueTypeName var tagLines: [String] = [] - for parameter in parameters { + for (parameter, name) in zip(parameters, parameters.uniqueJSIdentifiers) { let docText = parsed.parameter(named: parameter.name) let defaultValue = parameter.defaultValue.map { DefaultValueUtils.format( @@ -4348,11 +4323,11 @@ extension BridgeJSLink { } switch (docText, defaultValue) { case let (.some(text), .some(value)): - tagLines.append("@param \(parameter.escapedJSIdentifier) \(text) (default: \(value))") + tagLines.append("@param \(name) \(text) (default: \(value))") case let (.some(text), .none): - tagLines.append("@param \(parameter.escapedJSIdentifier) \(text)") + tagLines.append("@param \(name) \(text)") case let (.none, .some(value)): - tagLines.append("@param \(parameter.escapedJSIdentifier) - Optional parameter (default: \(value))") + tagLines.append("@param \(name) - Optional parameter (default: \(value))") case (.none, .none): continue } @@ -4492,6 +4467,23 @@ extension Parameter { } } +extension [Parameter] { + fileprivate var uniqueJSIdentifiers: [String] { + var names: [String] = [] + for parameter in self { + let escapedName = parameter.escapedJSIdentifier + var name = escapedName + var suffix = 1 + while names.contains(name) { + name = escapedName + suffix.description + suffix += 1 + } + names.append(name) + } + return names + } +} + extension ClosureSignature { fileprivate func renderTSFunctionType(renderType: (BridgeType) -> String) -> String { let renderedParameters = parameters.enumerated().map { index, parameter in diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 2da07f2be..673a64212 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2586,25 +2586,21 @@ struct IntrinsicJSFragment: Sendable { // Attach instance methods to the struct instance for method in structDef.methods where !method.effects.isStatic { - let paramList = DefaultValueUtils.formatParameterList( - method.parameters, - resolveTypeName: context.defaultValueTypeName + let builder = BridgeJSLink.ExportedThunkBuilder( + effects: method.effects, + context: context + ) + builder.body.write( + "\(JSGlueVariableScope.reservedStructHelpers).\(context.scope.helperKey(forTypeNamed: structDef.swiftCallName)).lower(this);" ) + for param in method.parameters { + try builder.lowerParameter(param: param) + } + let returnExpr = try builder.call(abiName: method.abiName, returnType: method.returnType) printer.write( - "\(instanceVar).\(method.resolvedJSName) = function(\(paramList)) {" + "\(instanceVar).\(method.resolvedJSName) = function(\(builder.parameterList)) {" ) - try printer.indent { - let builder = BridgeJSLink.ExportedThunkBuilder( - effects: method.effects, - context: context - ) - builder.body.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(context.scope.helperKey(forTypeNamed: structDef.swiftCallName)).lower(this);" - ) - for param in method.parameters { - try builder.lowerParameter(param: param) - } - let returnExpr = try builder.call(abiName: method.abiName, returnType: method.returnType) + printer.indent { builder.renderFunctionBody(into: printer, returnExpr: returnExpr) } printer.write("}.bind(\(instanceVar));") diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift index 224462ddb..c347bfb21 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift @@ -90,8 +90,9 @@ enum JSMacroHelper { static func parameterNames(_ parameters: FunctionParameterListSyntax) -> [String] { parameters.compactMap { param in let nameToken = param.secondName ?? param.firstName - let nameText = nameToken.text - return nameText == "_" ? nil : nameText + guard nameToken.text != "_" else { return nil } + let nameText = stripBackticks(nameToken.text) + return nameText.isValidSwiftIdentifier(for: .variableName) ? nameText : "`\(nameText)`" } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift index 2c4c062cb..d17db250d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ReservedWordParameters.swift @@ -1 +1,23 @@ @JS func check(extension: Int, break: Double, function: Bool, in: String) {} +@JS func checkEscaped(_ `in`: String) {} + +@JS class ReservedWordBox { + @JS init(in: Int) {} + @JS func run(for: Int) {} + @JS static func make(default: Int) -> Int { 0 } +} + +@JS protocol ReservedWordDelegate { + func handle(in: Int, for: String, _ `default`: Bool) +} + +@JSFunction func importedCheck(in: Int, for: String, _ `default`: Bool) throws(JSException) + +@JS func checkEscapedCollision(in: Int, _in: Int) {} +@JS func checkGlueNameCollision(instance: Int, swift: String) {} + +@JS protocol BacktickedLabelDelegate { + func handle(`in`: Int) +} + +@JSFunction func importedSelfClosure(_ `self`: @escaping () -> Void) throws(JSException) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json index c27a4eb46..380de8738 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.json @@ -4,7 +4,101 @@ ], "classes" : [ + { + "constructor" : { + "abiName" : "bjs_ReservedWordBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "in", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_ReservedWordBox_run", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "run", + "parameters" : [ + { + "label" : "for", + "name" : "for", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + } + } + }, + { + "abiName" : "bjs_ReservedWordBox_static_make", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "make", + "parameters" : [ + { + "label" : "default", + "name" : "default", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "className" : { + "_0" : "ReservedWordBox" + } + } + } + ], + "name" : "ReservedWordBox", + "properties" : [ + + ], + "swiftCallName" : "ReservedWordBox" + } ], "enums" : [ @@ -63,17 +157,301 @@ "returnType" : { "void" : { + } + } + }, + { + "abiName" : "bjs_checkEscaped", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkEscaped", + "parameters" : [ + { + "label" : "_", + "name" : "in", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_checkEscapedCollision", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkEscapedCollision", + "parameters" : [ + { + "label" : "in", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "_in", + "name" : "_in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_checkGlueNameCollision", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkGlueNameCollision", + "parameters" : [ + { + "label" : "instance", + "name" : "instance", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "swift", + "name" : "swift", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + } } } ], "protocols" : [ + { + "methods" : [ + { + "abiName" : "bjs_ReservedWordDelegate_handle", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "handle", + "parameters" : [ + { + "label" : "in", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "for", + "name" : "for", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "default", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "ReservedWordDelegate", + "properties" : [ + ] + }, + { + "methods" : [ + { + "abiName" : "bjs_BacktickedLabelDelegate_handle", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "handle", + "parameters" : [ + { + "label" : "`in`", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "BacktickedLabelDelegate", + "properties" : [ + + ] + } ], "structs" : [ ] }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "importedCheck", + "parameters" : [ + { + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "for", + "type" : { + "string" : { + + } + } + }, + { + "name" : "default", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "importedSelfClosure", + "parameters" : [ + { + "name" : "self", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuley_y", + "moduleName" : "TestModule", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, "moduleName" : "TestModule", "usedExternalModules" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift index b09e1a76d..51b65629f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ReservedWordParameters.swift @@ -1,3 +1,122 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuley_y") +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_y(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuley_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_y") +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_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_TestModule_10TestModuley_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_y") +public func _invoke_swift_closure_TestModule_10TestModuley_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ReservedWordDelegate where Self: _BridgedSwiftProtocolWrapper { + func handle(`in`: Int, `for`: String, _ `default`: Bool) -> Void { + `for`.bridgeJSWithLoweredParameter { (forWord0, forWord1, forWord2) in + let defaultValue = `default`.bridgeJSLowerParameter() + let inValue = `in`.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_ReservedWordDelegate_handle(jsObjectValue, inValue, forWord0, forWord1, forWord2, defaultValue) + } + } +} + +struct AnyReservedWordDelegate: ReservedWordDelegate, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyReservedWordDelegate(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ReservedWordDelegate_handle") +fileprivate func bjs_ReservedWordDelegate_handle_extern(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void +#else +fileprivate func bjs_ReservedWordDelegate_handle_extern(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ReservedWordDelegate_handle(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void { + return bjs_ReservedWordDelegate_handle_extern(jsObject, `in`, forWord0, forWord1, forWord2, `default`) +} + +extension BacktickedLabelDelegate where Self: _BridgedSwiftProtocolWrapper { + func handle(`in`: Int) -> Void { + let inValue = `in`.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_BacktickedLabelDelegate_handle(jsObjectValue, inValue) + } +} + +struct AnyBacktickedLabelDelegate: BacktickedLabelDelegate, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyBacktickedLabelDelegate(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_BacktickedLabelDelegate_handle") +fileprivate func bjs_BacktickedLabelDelegate_handle_extern(_ jsObject: Int32, _ `in`: Int32) -> Void +#else +fileprivate func bjs_BacktickedLabelDelegate_handle_extern(_ jsObject: Int32, _ `in`: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_BacktickedLabelDelegate_handle(_ jsObject: Int32, _ `in`: Int32) -> Void { + return bjs_BacktickedLabelDelegate_handle_extern(jsObject, `in`) +} + @_expose(wasm, "bjs_check") @_cdecl("bjs_check") public func _bjs_check(_ `extension`: Int32, _ `break`: Float64, _ function: Int32, _ inBytes: Int32, _ inLength: Int32) -> Void { @@ -10,4 +129,152 @@ public func _bjs_check(_ `extension`: Int32, _ `break`: Float64, _ function: Int #else fatalError("Only available on WebAssembly") #endif +} + +@_expose(wasm, "bjs_checkEscaped") +@_cdecl("bjs_checkEscaped") +public func _bjs_checkEscaped(_ inBytes: Int32, _ inLength: Int32) -> Void { + #if arch(wasm32) + let `in` = String.bridgeJSLiftParameter(inBytes, inLength) + checkEscaped(_: `in`) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_checkEscapedCollision") +@_cdecl("bjs_checkEscapedCollision") +public func _bjs_checkEscapedCollision(_ `in`: Int32, _ _in: Int32) -> Void { + #if arch(wasm32) + let _in = Int.bridgeJSLiftParameter(_in) + let `in` = Int.bridgeJSLiftParameter(`in`) + checkEscapedCollision(in: `in`, _in: _in) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_checkGlueNameCollision") +@_cdecl("bjs_checkGlueNameCollision") +public func _bjs_checkGlueNameCollision(_ instance: Int32, _ swiftBytes: Int32, _ swiftLength: Int32) -> Void { + #if arch(wasm32) + let swift = String.bridgeJSLiftParameter(swiftBytes, swiftLength) + let instance = Int.bridgeJSLiftParameter(instance) + checkGlueNameCollision(instance: instance, swift: swift) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ReservedWordBox_init") +@_cdecl("bjs_ReservedWordBox_init") +public func _bjs_ReservedWordBox_init(_ `in`: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let `in` = Int.bridgeJSLiftParameter(`in`) + let ret = ReservedWordBox(in: `in`) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ReservedWordBox_run") +@_cdecl("bjs_ReservedWordBox_run") +public func _bjs_ReservedWordBox_run(_ _self: UnsafeMutableRawPointer, _ `for`: Int32) -> Void { + #if arch(wasm32) + let `for` = Int.bridgeJSLiftParameter(`for`) + let _self = ReservedWordBox.bridgeJSLiftParameter(_self) + _self.run(for: `for`) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ReservedWordBox_static_make") +@_cdecl("bjs_ReservedWordBox_static_make") +public func _bjs_ReservedWordBox_static_make(_ `default`: Int32) -> Int32 { + #if arch(wasm32) + let `default` = Int.bridgeJSLiftParameter(`default`) + let ret = ReservedWordBox.make(default: `default`) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ReservedWordBox_deinit") +@_cdecl("bjs_ReservedWordBox_deinit") +public func _bjs_ReservedWordBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ReservedWordBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ReservedWordBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ReservedWordBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ReservedWordBox_wrap") +fileprivate func _bjs_ReservedWordBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ReservedWordBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ReservedWordBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ReservedWordBox_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importedCheck") +fileprivate func bjs_importedCheck_extern(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void +#else +fileprivate func bjs_importedCheck_extern(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importedCheck(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Void { + return bjs_importedCheck_extern(`in`, forWord0, forWord1, forWord2, `default`) +} + +func _$importedCheck(_ `in`: Int, _ `for`: String, _ `default`: Bool) throws(JSException) -> Void { + `for`.bridgeJSWithLoweredParameter { (forWord0, forWord1, forWord2) in + let defaultValue = `default`.bridgeJSLowerParameter() + let inValue = `in`.bridgeJSLowerParameter() + bjs_importedCheck(inValue, forWord0, forWord1, forWord2, defaultValue) + } + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importedSelfClosure") +fileprivate func bjs_importedSelfClosure_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_importedSelfClosure_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importedSelfClosure(_ self: Int32) -> Void { + return bjs_importedSelfClosure_extern(self) +} + +func _$importedSelfClosure(_ self: @escaping () -> Void) throws(JSException) -> Void { + let `self` = JSTypedClosure<() -> Void>(self) + let selfFuncRef = self.bridgeJSLowerParameter() + withExtendedLifetime((self)) { + bjs_importedSelfClosure(selfFuncRef) + } + if let error = _swift_js_take_exception() { + throw error + } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts index 027a6b9db..82dc96f71 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.d.ts @@ -4,10 +4,37 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export interface ReservedWordDelegate { + handle(_in: number, _for: string, _default: boolean): void; +} + +export interface BacktickedLabelDelegate { + handle(_in: number): void; +} + +/// 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 ReservedWordBox extends SwiftHeapObject { + run(_for: number): void; +} export type Exports = { check(extension: number, _break: number, _function: boolean, _in: string): void; + checkEscaped(_in: string): void; + checkEscapedCollision(_in: number, _in1: number): void; + checkGlueNameCollision(instance: number, swift: string): void; + ReservedWordBox: { + new(_in: number): ReservedWordBox; + make(_default: number): number; + }, } export type Imports = { + importedCheck(_in: number, _for: string, _default: boolean): void; + importedSelfClosure(self: () => void): void; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js index 0abe5fdbf..c5e67f8ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js @@ -33,6 +33,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 = decodeUTF8(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 { /** @@ -41,6 +66,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(word0, word1, word2) { tmpRetString = decodeString(word0, word1, word2); } @@ -206,6 +232,69 @@ 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_10TestModuley_y"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + callback(); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuley_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_y = function() { + instance.exports.invoke_swift_closure_TestModule_10TestModuley_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_10TestModuley_y); + } + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_ReservedWordBox_wrap"] = function(pointer) { + const obj = _exports['ReservedWordBox'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_importedCheck"] = function bjs_importedCheck(_in, forWord0, forWord1, forWord2, _default) { + try { + const string = decodeString(forWord0, forWord1, forWord2); + imports.importedCheck(_in, string, _default !== 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importedSelfClosure"] = function bjs_importedSelfClosure(self) { + try { + imports.importedSelfClosure(swift.memory.getObject(self)); + } catch (error) { + setException(error); + } + } + TestModule["bjs_ReservedWordDelegate_handle"] = function bjs_ReservedWordDelegate_handle(self, _in, forWord0, forWord1, forWord2, _default) { + try { + const string = decodeString(forWord0, forWord1, forWord2); + swift.memory.getObject(self).handle(_in, string, _default !== 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_BacktickedLabelDelegate_handle"] = function bjs_BacktickedLabelDelegate_handle(self, _in) { + try { + swift.memory.getObject(self).handle(_in); + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { if (memory !== i.exports.memory) immortalStrings.clear(); @@ -368,12 +457,95 @@ export async function createInstantiator(options, swift) { /** @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 ReservedWordBox extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ReservedWordBox_deinit, ReservedWordBox.prototype, null); + } + + constructor(_in) { + const ret = instance.exports.bjs_ReservedWordBox_init(_in); + return ReservedWordBox.__construct(ret); + } + run(_for) { + instance.exports.bjs_ReservedWordBox_run(this.pointer, _for); + } + static make(_default) { + const ret = instance.exports.bjs_ReservedWordBox_static_make(_default); + return ret; + } + } const exports = { check: function bjs_check(extension, _break, _function, _in) { const _inBytes = textEncoder.encode(_in); const _inId = swift.memory.retain(_inBytes); instance.exports.bjs_check(extension, _break, _function, _inId, _inBytes.length); }, + checkEscaped: function bjs_checkEscaped(_in) { + const _inBytes = textEncoder.encode(_in); + const _inId = swift.memory.retain(_inBytes); + instance.exports.bjs_checkEscaped(_inId, _inBytes.length); + }, + checkEscapedCollision: function bjs_checkEscapedCollision(_in, _in1) { + instance.exports.bjs_checkEscapedCollision(_in, _in1); + }, + checkGlueNameCollision: function bjs_checkGlueNameCollision(instance1, swift1) { + const swift1Bytes = textEncoder.encode(swift1); + const swift1Id = swift.memory.retain(swift1Bytes); + instance.exports.bjs_checkGlueNameCollision(instance1, swift1Id, swift1Bytes.length); + }, + ReservedWordBox, }; _exports = exports; return exports; diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 9e5892a87..1429bb0fb 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -25,6 +25,18 @@ func runJsWorks() -> Void @JS func describeReservedWordParameters(extension: Int, break: Double, function: Bool, in: String) -> String { return "\(`extension`):\(`break`):\(function):\(`in`)" } +@JS func describeBacktickedParameter(_ `in`: String) -> String { + return `in` +} +@JS func describeCollidingParameters(in: Int, _in: Int, instance: Int, swift: String) -> String { + return "\(`in`):\(_in):\(instance):\(swift)" +} +@JS protocol ReservedWordDescriber { + func describe(in: Int, for: String) -> String +} +@JS func describeWithReservedWordDescriber(_ describer: any ReservedWordDescriber) -> String { + return describer.describe(in: 1, for: "for") +} @JS func roundTripSwiftHeapObject(v: Greeter) -> Greeter { return v } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 884ecb8e1..f2c868c84 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4294,6 +4294,39 @@ fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ return bjs_ArrayElementProtocol_value_set_extern(jsObject, newValue) } +extension ReservedWordDescriber where Self: _BridgedSwiftProtocolWrapper { + func describe(`in`: Int, `for`: String) -> String { + let ret0 = `for`.bridgeJSWithLoweredParameter { (forWord0, forWord1, forWord2) in + let inValue = `in`.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_ReservedWordDescriber_describe(jsObjectValue, inValue, forWord0, forWord1, forWord2) + return ret + } + let ret = ret0 + return String.bridgeJSLiftReturn(ret) + } +} + +struct AnyReservedWordDescriber: ReservedWordDescriber, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyReservedWordDescriber(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ReservedWordDescriber_describe") +fileprivate func bjs_ReservedWordDescriber_describe_extern(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32) -> Int32 +#else +fileprivate func bjs_ReservedWordDescriber_describe_extern(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ReservedWordDescriber_describe(_ jsObject: Int32, _ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32) -> Int32 { + return bjs_ReservedWordDescriber_describe_extern(jsObject, `in`, forWord0, forWord1, forWord2) +} + extension DataProcessor where Self: _BridgedSwiftProtocolWrapper { func increment(by amount: Int) -> Void { let amountValue = amount.bridgeJSLowerParameter() @@ -10339,6 +10372,45 @@ public func _bjs_describeReservedWordParameters(_ `extension`: Int32, _ `break`: #endif } +@_expose(wasm, "bjs_describeBacktickedParameter") +@_cdecl("bjs_describeBacktickedParameter") +public func _bjs_describeBacktickedParameter(_ inBytes: Int32, _ inLength: Int32) -> Void { + #if arch(wasm32) + let `in` = String.bridgeJSLiftParameter(inBytes, inLength) + let ret = describeBacktickedParameter(_: `in`) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_describeCollidingParameters") +@_cdecl("bjs_describeCollidingParameters") +public func _bjs_describeCollidingParameters(_ `in`: Int32, _ _in: Int32, _ instance: Int32, _ swiftBytes: Int32, _ swiftLength: Int32) -> Void { + #if arch(wasm32) + let swift = String.bridgeJSLiftParameter(swiftBytes, swiftLength) + let instance = Int.bridgeJSLiftParameter(instance) + let _in = Int.bridgeJSLiftParameter(_in) + let `in` = Int.bridgeJSLiftParameter(`in`) + let ret = describeCollidingParameters(in: `in`, _in: _in, instance: instance, swift: swift) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_describeWithReservedWordDescriber") +@_cdecl("bjs_describeWithReservedWordDescriber") +public func _bjs_describeWithReservedWordDescriber(_ describer: Int32) -> Void { + #if arch(wasm32) + let describer = AnyReservedWordDescriber.bridgeJSLiftParameter(describer) + let ret = describeWithReservedWordDescriber(_: describer) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripSwiftHeapObject") @_cdecl("bjs_roundTripSwiftHeapObject") public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { @@ -19975,6 +20047,32 @@ func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int] return String.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsDescribeReservedWordParameters") +fileprivate func bjs_jsDescribeReservedWordParameters_extern(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Int32 +#else +fileprivate func bjs_jsDescribeReservedWordParameters_extern(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsDescribeReservedWordParameters(_ `in`: Int32, _ forWord0: Int32, _ forWord1: Int32, _ forWord2: Int32, _ `default`: Int32) -> Int32 { + return bjs_jsDescribeReservedWordParameters_extern(`in`, forWord0, forWord1, forWord2, `default`) +} + +func _$jsDescribeReservedWordParameters(_ `in`: Int, _ `for`: String, _ `default`: Bool) throws(JSException) -> String { + let ret0 = `for`.bridgeJSWithLoweredParameter { (forWord0, forWord1, forWord2) in + let defaultValue = `default`.bridgeJSLowerParameter() + let inValue = `in`.bridgeJSLowerParameter() + let ret = bjs_jsDescribeReservedWordParameters(inValue, forWord0, forWord1, forWord2, defaultValue) + 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_jsGenericRoundTrip") fileprivate func bjs_jsGenericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 8598361b6..265fcf9cb 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -15269,6 +15269,117 @@ } } }, + { + "abiName" : "bjs_describeBacktickedParameter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeBacktickedParameter", + "parameters" : [ + { + "label" : "_", + "name" : "in", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_describeCollidingParameters", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeCollidingParameters", + "parameters" : [ + { + "label" : "in", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "_in", + "name" : "_in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "instance", + "name" : "instance", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "swift", + "name" : "swift", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_describeWithReservedWordDescriber", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeWithReservedWordDescriber", + "parameters" : [ + { + "label" : "_", + "name" : "describer", + "type" : { + "swiftProtocol" : { + "_0" : "ReservedWordDescriber" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { @@ -19314,6 +19425,51 @@ } ] }, + { + "methods" : [ + { + "abiName" : "bjs_ReservedWordDescriber_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + { + "label" : "in", + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "for", + "name" : "for", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "ReservedWordDescriber", + "properties" : [ + + ] + }, { "methods" : [ { @@ -26306,6 +26462,49 @@ "returnType" : { "string" : { + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsDescribeReservedWordParameters", + "parameters" : [ + { + "name" : "in", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "for", + "type" : { + "string" : { + + } + } + }, + { + "name" : "default", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "string" : { + } } } diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index c98ab3e61..b3e921672 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -31,6 +31,12 @@ import JavaScriptKit _ b: [Int] ) throws(JSException) -> String +@JSFunction func jsDescribeReservedWordParameters( + in: Int, + for: String, + _ `default`: Bool +) throws(JSException) -> String + class ImportAPITests: XCTestCase { func testRoundTripVoid() throws { try jsRoundTripVoid() @@ -211,4 +217,8 @@ class ImportAPITests: XCTestCase { #""s"|[1,2]|[7,8,9]"# ) } + + func testReservedWordParameters() throws { + XCTAssertEqual(try jsDescribeReservedWordParameters(in: 1, for: "for", true), "1:for:true") + } } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 15631bcbe..17b48679c 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -164,6 +164,7 @@ export async function setupOptions(options, context) { jsJoinOptionalStructThenArray: joinStackParams, jsJoinEnumThenArray: joinStackParams, jsJoinStringThenStackParams: joinStackParams, + jsDescribeReservedWordParameters: (a, b, c) => `${a}:${b}:${c}`, jsGenericRoundTrip: (v) => v, jsGenericRoundTripClass: (v) => v, jsGenericParsePoint: (json) => JSON.parse(json), @@ -306,6 +307,12 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.roundTripString(v), v); } assert.equal(exports.describeReservedWordParameters(1, 2.5, true, "in"), "1:2.5:true:in"); + assert.equal(exports.describeBacktickedParameter("in"), "in"); + assert.equal(exports.describeCollidingParameters(1, 2, 3, "swift"), "1:2:3:swift"); + assert.equal( + exports.describeWithReservedWordDescriber({ describe: (a, b) => `${a}:${b}` }), + "1:for" + ); const dict = { a: 1, b: 2 }; assert.deepEqual(exports.roundTripDictionaryExport(dict), dict); const optDict = { hello: "world" }; From c332a3bef097ce585ce61f360ef47b0ab3059e5b Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 28 Oct 2026 20:28:41 +1000 Subject: [PATCH 133/140] JavaScriptEventLoop: Avoid O(N^2) job queue insert for bursts of jobs --- Sources/JavaScriptEventLoop/JobQueue.swift | 38 +++++-- .../JavaScriptEventLoopTests.swift | 107 ++++++++++++++++++ ...avaScriptEventLoopYieldIntervalTests.swift | 27 +++++ 3 files changed, 163 insertions(+), 9 deletions(-) diff --git a/Sources/JavaScriptEventLoop/JobQueue.swift b/Sources/JavaScriptEventLoop/JobQueue.swift index 0dcbcdc17..8ca74e1c8 100644 --- a/Sources/JavaScriptEventLoop/JobQueue.swift +++ b/Sources/JavaScriptEventLoop/JobQueue.swift @@ -1,6 +1,6 @@ // This file contains the job queue implementation which re-order jobs based on their priority. -// The current implementation is much simple to be easily debugged, but should be re-implemented -// using priority queue ideally. +// Jobs form runs, one per priority in descending order, FIFO within a run. The first job of each +// run points to its last job, so an insert steps over whole runs. import _Concurrency import _CJavaScriptEventLoop @@ -19,15 +19,18 @@ extension JavaScriptEventLoop { func insertJobQueue(job newJob: UnownedJob) { withUnsafeMutablePointer(to: &queueState.headJob) { headJobPtr in var position: UnsafeMutablePointer = headJobPtr - while let cur = position.pointee { - if cur.rawPriority < newJob.rawPriority { - newJob.nextInQueue().pointee = cur - position.pointee = newJob + while let runHead = position.pointee, runHead.rawPriority >= newJob.rawPriority { + let runTail = runHead.lastInRun().pointee! + if runHead.rawPriority == newJob.rawPriority { + newJob.nextInQueue().pointee = runTail.nextInQueue().pointee + runTail.nextInQueue().pointee = newJob + runHead.lastInRun().pointee = newJob return } - position = cur.nextInQueue() + position = runTail.nextInQueue() } - newJob.nextInQueue().pointee = nil + newJob.nextInQueue().pointee = position.pointee + newJob.lastInRun().pointee = newJob position.pointee = newJob } @@ -81,7 +84,14 @@ extension JavaScriptEventLoop { func claimNextFromQueue() -> UnownedJob? { if let job = self.queueState.headJob { - self.queueState.headJob = job.nextInQueue().pointee + let nextJob = job.nextInQueue().pointee + if let nextJob { + let runTail = job.lastInRun().pointee! + if !runTail.isSameJob(as: job) { + nextJob.lastInRun().pointee = runTail + } + } + self.queueState.headJob = nextJob return job } return nil @@ -107,6 +117,16 @@ extension UnownedJob { } } + /// The last job of the run. Valid only on the first job of a run. + fileprivate func lastInRun() -> UnsafeMutablePointer { + return withUnsafeMutablePointer(to: &asImpl().pointee.SchedulerPrivate.1) { rawLastJobPtr in + UnsafeMutableRawPointer(rawLastJobPtr).bindMemory(to: UnownedJob?.self, capacity: 1) + } + } + + fileprivate func isSameJob(as other: UnownedJob) -> Bool { + asImpl() == other.asImpl() + } } private struct JobFlags { diff --git a/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopTests.swift b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopTests.swift index 8fbbd817f..7fbb712a7 100644 --- a/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopTests.swift +++ b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopTests.swift @@ -113,6 +113,113 @@ final class JavaScriptEventLoopTests: XCTestCase { XCTAssertEqual(context.completed, ["t4", "t3", "t5"]) } + final class OrderContext: @unchecked Sendable { + var completed: [String] = [] + var expectedCount = 0 + var continuation: CheckedContinuation? + + func record(_ name: String) { + completed.append(name) + if completed.count == expectedCount { + continuation?.resume() + continuation = nil + } + } + } + + /// Starts tasks without awaiting them, so no await raises the priority of a queued task. + func runUnawaited(expectedCount: Int, _ start: (OrderContext) -> Void) async -> [String] { + let context = OrderContext() + context.expectedCount = expectedCount + await withCheckedContinuation { continuation in + context.continuation = continuation + start(context) + } + return context.completed + } + + func testTaskPriorityOrderWithMixedPriorities() async throws { + let burst: [(String, TaskPriority)] = [ + ("low1", .low), ("medium1", .medium), ("low2", .low), ("high1", .high), + ("medium2", .medium), ("low3", .low), ("high2", .high), ("medium3", .medium), + ] + let burstOrder = await runUnawaited(expectedCount: burst.count) { context in + for (name, priority) in burst { + Task(priority: priority) { context.record(name) } + } + } + XCTAssertEqual(burstOrder, ["high1", "high2", "medium1", "medium2", "medium3", "low1", "low2", "low3"]) + + let nestedOrder = await runUnawaited(expectedCount: 7) { context in + Task(priority: .medium) { + context.record("outer") + let nested: [(String, TaskPriority)] = [ + ("nestedLow1", .low), ("nestedHigh", .high), ("nestedMedium", .medium), ("nestedLow2", .low), + ] + for (name, priority) in nested { + Task(priority: priority) { context.record(name) } + } + } + Task(priority: .medium) { context.record("medium") } + Task(priority: .low) { context.record("low") } + } + XCTAssertEqual( + nestedOrder, + ["outer", "nestedHigh", "medium", "nestedMedium", "low", "nestedLow1", "nestedLow2"] + ) + + let priorities: [TaskPriority] = [ + .low, .high, .background, .medium, TaskPriority(rawValue: 22), TaskPriority(rawValue: 5), + ] + let many = (0..<600).map { index in ("\(index)", priorities[index % priorities.count]) } + let manyOrder = await runUnawaited(expectedCount: many.count) { context in + for (name, priority) in many { + Task(priority: priority) { context.record(name) } + } + } + let expectedManyOrder = many.enumerated() + .sorted { lhs, rhs in + lhs.element.1.rawValue != rhs.element.1.rawValue + ? lhs.element.1.rawValue > rhs.element.1.rawValue + : lhs.offset < rhs.offset + } + .map(\.element.0) + XCTAssertEqual(manyOrder, expectedManyOrder) + } + + func testTaskPriorityOrderAfterQueueEmpties() async throws { + let rounds: [[(String, TaskPriority)]] = [ + [("low1", .low), ("low2", .low), ("high1", .high), ("low3", .low)], + [("high1", .high), ("medium1", .medium), ("high2", .high), ("low1", .low)], + [("medium1", .medium), ("medium2", .medium), ("medium3", .medium)], + ] + let expectedOrders = [ + ["high1", "low1", "low2", "low3"], + ["high1", "high2", "medium1", "low1"], + ["medium1", "medium2", "medium3"], + ] + for (round, expectedOrder) in zip(rounds, expectedOrders) { + let order = await runUnawaited(expectedCount: round.count) { context in + for (name, priority) in round { + Task(priority: priority) { context.record(name) } + } + } + XCTAssertEqual(order, expectedOrder) + } + } + + func testTaskPriorityOrderAfterSingleJobRunIsClaimed() async throws { + let order = await runUnawaited(expectedCount: 4) { context in + Task(priority: .low) { context.record("low1") } + Task(priority: .low) { context.record("low2") } + Task(priority: .high) { + context.record("high") + Task(priority: .low) { context.record("low3") } + } + } + XCTAssertEqual(order, ["high", "low1", "low2", "low3"]) + } + // MARK: - Promise Tests func testPromiseResolution() async throws { diff --git a/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift index 4269b89b2..a18c162ce 100644 --- a/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift +++ b/Tests/JavaScriptEventLoopTests/JavaScriptEventLoopYieldIntervalTests.swift @@ -76,4 +76,31 @@ final class JavaScriptEventLoopYieldIntervalTests: XCTestCase { for task in tasks { await task.value } XCTAssertEqual(order.value, Array(0..<20)) } + + func testPriorityOrderAcrossYields() async { + JavaScriptEventLoop.shared.yieldInterval = .milliseconds(1) + let order = Box([String]()) + let expectedOrder = ["h0", "h1", "h2", "h3", "h4", "m0", "m1", "m2", "m3", "l0", "l1", "l2", "l3", "l4"] + // Tasks are not awaited, so no await raises the priority of a queued task. + await withCheckedContinuation { (continuation: CheckedContinuation) in + @Sendable func record(_ name: String) { + Self.busyWait(milliseconds: 1) + order.value.append(name) + if order.value.count == expectedOrder.count { continuation.resume() } + } + let priorities: [(String, TaskPriority)] = [("l", .low), ("m", .medium), ("h", .high)] + for index in 0..<12 { + let (prefix, priority) = priorities[index % 3] + let name = "\(prefix)\(index / 3)" + Task(priority: priority) { + record(name) + if name == "h0" { + Task(priority: .low) { record("l4") } + Task(priority: .high) { record("h4") } + } + } + } + } + XCTAssertEqual(order.value, expectedOrder) + } } From 835ee61f8879b50165badf721cefb04e4dcf5121 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 3 Nov 2026 01:41:20 +0100 Subject: [PATCH 134/140] BridgeJS: Check thrown errors before lifting return values --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 9 ++- .../Inputs/MacroSwift/Protocol.swift | 5 ++ .../BridgeJSCodegenTests/Protocol.json | 17 +++++ .../BridgeJSCodegenTests/Protocol.swift | 26 ++++++++ .../__Snapshots__/BridgeJSLinkTests/Async.js | 8 +-- .../ImportedTypeInExportedInterface.js | 4 +- .../BridgeJSLinkTests/Protocol.d.ts | 1 + .../BridgeJSLinkTests/Protocol.js | 12 ++++ .../BridgeJSLinkTests/ProtocolInClosure.js | 16 ++--- .../BridgeJSLinkTests/SwiftClosure.js | 64 +++++++++---------- .../BridgeJSLinkTests/SwiftClosureImports.js | 4 +- .../BridgeJSRuntimeTests/ExportAPITests.swift | 6 ++ .../Generated/BridgeJS.swift | 50 +++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 34 ++++++++++ Tests/prelude.mjs | 3 + 15 files changed, 206 insertions(+), 53 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 686f8d1e0..d882aad1c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1809,6 +1809,7 @@ public struct BridgeJSLink { body.write("const \(returnVariable) = \(call);") fragmentArguments = [returnVariable] } + body.write(lines: checkExceptionLines()) let liftedValues = try liftingFragment.printCode(fragmentArguments, context) assert(liftedValues.count <= 1, "Lifting fragment should produce at most one value") return liftedValues.first @@ -1818,10 +1819,11 @@ public struct BridgeJSLink { let call = "\(JSGlueVariableScope.reservedInstance).exports.\(abiName)(\(parameterForwardings.joined(separator: ", ")))" body.write("const ret = \(call);") + body.write(lines: checkExceptionLines()) return "ret" } - func checkExceptionLines() -> [String] { + private func checkExceptionLines() -> [String] { guard effects.isThrows else { return [] } @@ -1837,10 +1839,9 @@ public struct BridgeJSLink { ] } - /// Renders the thunk body (body code, exception handling, and optional return) into a printer. + /// Renders the thunk body and optional return; `call`/`callConstructor` put the exception check in `body`. func renderFunctionBody(into printer: CodeFragmentPrinter, returnExpr: String?) { printer.write(contentsOf: body) - printer.write(lines: checkExceptionLines()) if let returnExpr = returnExpr { printer.write("return \(returnExpr);") } @@ -3490,7 +3491,6 @@ extension BridgeJSLink { getterPrinter.write("get \(property.resolvedJSName)() {") getterPrinter.indent { getterPrinter.write(contentsOf: getterThunkBuilder.body) - getterPrinter.write(lines: getterThunkBuilder.checkExceptionLines()) if let returnExpr = getterReturnExpr { getterPrinter.write("return \(returnExpr);") } @@ -3517,7 +3517,6 @@ extension BridgeJSLink { setterPrinter.write("set \(property.resolvedJSName)(\(setterThunkBuilder.parameterList)) {") setterPrinter.indent { setterPrinter.write(contentsOf: setterThunkBuilder.body) - setterPrinter.write(lines: setterThunkBuilder.checkExceptionLines()) } setterPrinter.write("},") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift index 106f30761..670cb29fc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift @@ -107,6 +107,11 @@ import JavaScriptKit @JS func loadLabel(_ key: String) async throws(JSException) -> String { return try await delegate.loadLabel(key) } + + @JS func validatedDelegate() throws(JSException) -> MyViewControllerDelegate { + _ = try delegate.validate(0) + return delegate + } } // Protocol array support diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index 4fbec6b49..40aa34cdf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -286,6 +286,23 @@ } } + }, + { + "abiName" : "bjs_MyViewController_validatedDelegate", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validatedDelegate", + "parameters" : [ + + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } } ], "name" : "MyViewController", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 3c4ba2a78..2f75db462 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1257,6 +1257,32 @@ public func _bjs_MyViewController_loadLabel(_ _self: UnsafeMutableRawPointer, _ #endif } +@_expose(wasm, "bjs_MyViewController_validatedDelegate") +@_cdecl("bjs_MyViewController_validatedDelegate") +public func _bjs_MyViewController_validatedDelegate(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = MyViewController.bridgeJSLiftParameter(_self) + do { + let ret = _bridgeJSUnwrapProtocolExportable(try _self.validatedDelegate(), "MyViewControllerDelegate") + return ret.bridgeJSLowerAsProtocolReturn() + } 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_MyViewController_delegate_get") @_cdecl("bjs_MyViewController_delegate_get") public func _bjs_MyViewController_delegate_get(_ _self: UnsafeMutableRawPointer) -> Int32 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 33c4ff195..6cc51f282 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -944,26 +944,26 @@ export async function createInstantiator(options, swift) { asyncRoundTripStructThrows: function bjs_asyncRoundTripStructThrows(v) { structHelpers.M10TestModuleT10AsyncPoint.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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }, asyncCombineStructs: function bjs_asyncCombineStructs(a, b) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 4bfce3e14..2f45f8eed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -755,14 +755,14 @@ export async function createInstantiator(options, swift) { const exports = { makeFoo: function bjs_makeFoo() { const ret = instance.exports.bjs_makeFoo(); - 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }, processFooArray: function bjs_processFooArray(foos) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts index e9b099f70..4259fb347 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -93,6 +93,7 @@ export interface MyViewController extends SwiftHeapObject { sendHelper(helper: Helper): void; validateValue(value: number): number; loadLabel(key: string): Promise; + validatedDelegate(): MyViewControllerDelegate; delegate: MyViewControllerDelegate; secondDelegate: MyViewControllerDelegate | null; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index f07007c79..8802e8786 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -1363,14 +1363,26 @@ export async function createInstantiator(options, swift) { const keyBytes = textEncoder.encode(key); const keyId = swift.memory.retain(keyBytes); const ret = instance.exports.bjs_MyViewController_loadLabel(this.pointer, keyId, keyBytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); + return ret1; + } + validatedDelegate() { + const ret = instance.exports.bjs_MyViewController_validatedDelegate(this.pointer); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; } get delegate() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index d6fa6f143..a9730573c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -248,14 +248,14 @@ export async function createInstantiator(options, swift) { bjs["make_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModule10RenderableP_10RenderableP = function(param0) { const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule10RenderableP_10RenderableP(boxPtr, swift.memory.retain(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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule10RenderableP_10RenderableP); @@ -273,14 +273,14 @@ export async function createInstantiator(options, swift) { bjs["make_swift_closure_TestModule_10TestModule10RenderableP_SS"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModule10RenderableP_SS = function(param0) { instance.exports.invoke_swift_closure_TestModule_10TestModule10RenderableP_SS(boxPtr, swift.memory.retain(param0)); - const ret = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret = tmpRetString; + tmpRetString = undefined; return ret; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule10RenderableP_SS); @@ -305,14 +305,14 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSq10RenderableP_SS(boxPtr, +isSome, result); - const ret = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret = tmpRetString; + tmpRetString = undefined; return ret; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq10RenderableP_SS); @@ -330,14 +330,14 @@ export async function createInstantiator(options, swift) { bjs["make_swift_closure_TestModule_10TestModuley_10RenderableP"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuley_10RenderableP = function() { const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuley_10RenderableP(boxPtr); - 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuley_10RenderableP); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index f56929d7c..3f4ab6e05 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -751,14 +751,14 @@ export async function createInstantiator(options, swift) { const param0Bytes = textEncoder.encode(param0); const param0Id = swift.memory.retain(param0Bytes); instance.exports.invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO(boxPtr, param0Id, param0Bytes.length); - const ret = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret = tmpRetString; + tmpRetString = undefined; return ret; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule5ThemeO_5ThemeO); @@ -777,13 +777,13 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModule6AnimalV_6AnimalV = function(param0) { structHelpers.M10TestModuleT6Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(boxPtr); - const structValue = structHelpers.M10TestModuleT6Animal.lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const structValue = structHelpers.M10TestModuleT6Animal.lift(); return structValue; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule6AnimalV_6AnimalV); @@ -826,13 +826,13 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModule9APIResultO_9APIResultO = function(param0) { const param0CaseId = enumHelpers.M10TestModuleT9APIResult.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(boxPtr, param0CaseId); - const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return ret; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule9APIResultO_9APIResultO); @@ -928,14 +928,14 @@ export async function createInstantiator(options, swift) { const param0Bytes = textEncoder.encode(param0); const param0Id = swift.memory.retain(param0Bytes); instance.exports.invoke_swift_closure_TestModule_10TestModuleSS_SS(boxPtr, param0Id, param0Bytes.length); - const ret = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const ret = tmpRetString; + tmpRetString = undefined; return ret; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSS_SS); @@ -1046,14 +1046,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(boxPtr, +isSome, isSome ? param0 : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO); @@ -1089,14 +1089,14 @@ export async function createInstantiator(options, swift) { result1 = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(boxPtr, +isSome, result, result1); - const optResult = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetString; + tmpRetString = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO); @@ -1115,13 +1115,13 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV = function(param0) { __bjs_codec_Optional_M10TestModuleT6Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(boxPtr); - const optValue = __bjs_codec_Optional_M10TestModuleT6Animal.lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optValue = __bjs_codec_Optional_M10TestModuleT6Animal.lift(); return optValue; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV); @@ -1146,15 +1146,15 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC(boxPtr, +isSome, result); - const pointer = tmpRetOptionalHeapObject; - tmpRetOptionalHeapObject = undefined; - const optResult = pointer === null ? null : _exports['Person'].__construct(pointer); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + const optResult = pointer === null ? null : _exports['Person'].__construct(pointer); return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC); @@ -1192,14 +1192,14 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(boxPtr, +isSome, result); - const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT9APIResult.lift(tag); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT9APIResult.lift(tag); return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO); @@ -1218,14 +1218,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(boxPtr, +isSome, isSome ? param0 : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO); @@ -1261,14 +1261,14 @@ export async function createInstantiator(options, swift) { result1 = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSqSS_SqSS(boxPtr, +isSome, result, result1); - const optResult = tmpRetString; - tmpRetString = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetString; + tmpRetString = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSS_SqSS); @@ -1287,14 +1287,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSqSb_SqSb = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb(boxPtr, +isSome, isSome ? param0 ? 1 : 0 : 0); - const optResult = tmpRetOptionalBool; - tmpRetOptionalBool = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalBool; + tmpRetOptionalBool = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSb_SqSb); @@ -1313,14 +1313,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSqSd_SqSd = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSqSd_SqSd(boxPtr, +isSome, isSome ? param0 : 0.0); - const optResult = tmpRetOptionalDouble; - tmpRetOptionalDouble = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSd_SqSd); @@ -1339,14 +1339,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSqSf_SqSf = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf(boxPtr, +isSome, isSome ? param0 : 0.0); - const optResult = tmpRetOptionalFloat; - tmpRetOptionalFloat = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSf_SqSf); @@ -1365,14 +1365,14 @@ export async function createInstantiator(options, swift) { const lower_closure_TestModule_10TestModuleSqSi_SqSi = function(param0) { const isSome = param0 != null; instance.exports.invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi(boxPtr, +isSome, isSome ? param0 : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; return optResult; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSi_SqSi); @@ -1393,14 +1393,14 @@ export async function createInstantiator(options, swift) { 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSS_SS); @@ -1418,14 +1418,14 @@ export async function createInstantiator(options, swift) { 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSb_9APIResultO); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 3ba6f5c0f..b15678998 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -406,14 +406,14 @@ export async function createInstantiator(options, swift) { 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; } + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); return ret1; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSS_SS); diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 1429bb0fb..55ab78e7a 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -110,6 +110,12 @@ struct TestError: Error { @JS func throwsWithDoubleResult() throws(JSException) -> Double { return 1.0 } @JS func throwsWithSwiftHeapObjectResult() throws(JSException) -> Greeter { return Greeter(name: "Test") } @JS func throwsWithJSObjectResult() throws(JSException) -> JSObject { return JSObject() } +@JS func throwsBeforeJSObjectResult() throws(JSException) -> JSObject { + throw JSException(JSError(message: "JSObjectResultError").jsValue) +} +@JS func throwsBeforeProtocolResult() throws(JSException) -> DataProcessor { + throw JSException(JSError(message: "ProtocolResultError").jsValue) +} @JS func zeroArgAsyncThrows() async throws(JSException) -> String { throw JSException(JSError(message: "ZeroArgAsyncThrowsError").jsValue) diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index f2c868c84..3b82a15d5 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -10793,6 +10793,56 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { #endif } +@_expose(wasm, "bjs_throwsBeforeJSObjectResult") +@_cdecl("bjs_throwsBeforeJSObjectResult") +public func _bjs_throwsBeforeJSObjectResult() -> Int32 { + #if arch(wasm32) + do { + let ret = try throwsBeforeJSObjectResult() + 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_throwsBeforeProtocolResult") +@_cdecl("bjs_throwsBeforeProtocolResult") +public func _bjs_throwsBeforeProtocolResult() -> Int32 { + #if arch(wasm32) + do { + let ret = _bridgeJSUnwrapProtocolExportable(try throwsBeforeProtocolResult(), "DataProcessor") + return ret.bridgeJSLowerAsProtocolReturn() + } 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 { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 265fcf9cb..c4fd1d602 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -15971,6 +15971,40 @@ } } }, + { + "abiName" : "bjs_throwsBeforeJSObjectResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsBeforeJSObjectResult", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_throwsBeforeProtocolResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsBeforeProtocolResult", + "parameters" : [ + + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "DataProcessor" + } + } + }, { "abiName" : "bjs_zeroArgAsyncThrows", "effects" : { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 17b48679c..e1d856647 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -629,6 +629,9 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.fail("Expected no error"); } + assert.throws(() => exports.throwsBeforeJSObjectResult(), { name: "Error", message: "JSObjectResultError" }); + assert.throws(() => exports.throwsBeforeProtocolResult(), { name: "Error", message: "ProtocolResultError" }); + // Test enums assert.equal(exports.Direction.North, 0); assert.equal(exports.Direction.South, 1); From 99bfd1e8fec8a2f4b14aa724046a48eb41979116 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 3 Nov 2026 06:59:32 +0100 Subject: [PATCH 135/140] CI: Run example builds on ubuntu-22.04 --- .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 a9e90c175..7f4f6c87e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -163,7 +163,7 @@ jobs: # 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 + runs-on: ubuntu-22.04 strategy: fail-fast: false matrix: @@ -196,7 +196,7 @@ jobs: # 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 + runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift From b8003b8e945656e951b2174f317de1adc66f7555 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 3 Nov 2026 02:23:30 +0100 Subject: [PATCH 136/140] BridgeJS: Diagnose async and throwing @JS struct initializers --- .../Sources/BridgeJSCore/SwiftToSkeleton.swift | 8 ++++++++ .../BridgeJSToolTests/DiagnosticsTests.swift | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index ef39000b1..7e075a8af 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1986,6 +1986,14 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let effects = collectEffects(signature: node.signature) else { return .skipChildren } + if effects.isAsync || effects.isThrows { + diagnose( + node: node, + message: "@JS struct initializer cannot be async or throw", + hint: "BridgeJS calls this initializer to rebuild struct values passed from JavaScript" + ) + return .skipChildren + } let structAbiName = exportedStructByName[structKey]?.abiName ?? "unknown" let constructor = ExportedConstructor( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 580360bb7..aadf04f00 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -535,6 +535,21 @@ import Testing #expect(skeleton.exported != nil) } + @Test + func throwingStructInitProducesDiagnostic() throws { + let source = """ + @JS struct Point { + var x: Double + + @JS init(x: Double) throws(JSException) { + self.x = x + } + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("@JS struct initializer cannot be async or throw")) + } + @Test func structWithoutExplicitInitSucceeds() throws { let source = """ From f1d5c94c4239d0fd9e398eb3ed19db98a2c629ae Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 3 Nov 2026 02:21:18 +0100 Subject: [PATCH 137/140] BridgeJS: Fix JSValue reference ownership across the bridge --- .../Sources/BridgeJSLink/JSGlueGen.swift | 124 +++++++++--------- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 9 +- .../BridgeJSLinkTests/ArrayTypes.js | 9 +- .../__Snapshots__/BridgeJSLinkTests/Async.js | 9 +- .../AsyncAssociatedValueEnum.js | 7 + .../BridgeJSLinkTests/AsyncImport.js | 7 + .../BridgeJSLinkTests/AsyncStaticImport.js | 7 + .../BridgeJSLinkTests/DefaultParameters.js | 9 +- .../BridgeJSLinkTests/DictionaryTypes.js | 9 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 9 +- .../BridgeJSLinkTests/EnumRawType.js | 9 +- .../BridgeJSLinkTests/GenericImports.js | 9 +- .../BridgeJSLinkTests/ImportArray.js | 9 +- .../ImportedTypeInExportedInterface.js | 9 +- .../BridgeJSLinkTests/JSValue.js | 21 ++- .../BridgeJSLinkTests/Namespaces.Global.js | 9 +- .../BridgeJSLinkTests/Namespaces.js | 9 +- .../BridgeJSLinkTests/Optionals.js | 9 +- .../BridgeJSLinkTests/Protocol.js | 9 +- .../BridgeJSLinkTests/SwiftClosure.js | 9 +- .../BridgeJSLinkTests/SwiftClosureImports.js | 7 + .../BridgeJSLinkTests/SwiftStruct.js | 9 +- .../BridgeJSLinkTests/SwiftStructImports.js | 9 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 18 +-- .../BridgeJSRuntimeTests/ExportAPITests.swift | 8 ++ .../Generated/BridgeJS.swift | 22 ++++ .../Generated/JavaScript/BridgeJS.json | 34 +++++ Tests/prelude.mjs | 17 ++- 28 files changed, 330 insertions(+), 95 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 673a64212..20f231dc8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -749,6 +749,27 @@ struct IntrinsicJSFragment: Sendable { private static let jsValueLowerHelperName = "__bjs_jsValueLower" private static let jsValueLiftHelperName = "__bjs_jsValueLift" + private static let jsValueTakeHelperName = "__bjs_jsValueTake" + + /// Mirrors `JavaScriptValueKind` in `_CJavaScriptKit.h`. + private enum JSValueKind: Int, CaseIterable { + case boolean = 0 + case string = 1 + case number = 2 + case object = 3 + case null = 4 + case undefined = 5 + case symbol = 7 + case bigInt = 8 + + /// Whether `payload1` is a reference in `swift.memory`. + var holdsReference: Bool { + switch self { + case .string, .object, .symbol, .bigInt: return true + case .boolean, .number, .null, .undefined: return false + } + } + } private static func registerJSValueHelpers(scope: JSGlueVariableScope) { scope.registerIntrinsic("jsValueHelpers") { helperPrinter in @@ -777,6 +798,20 @@ struct IntrinsicJSFragment: Sendable { helperPrinter.write("return \(resultVar);") } helperPrinter.write("}") + helperPrinter.write("function \(jsValueTakeHelperName)(kind, payload1, payload2) {") + helperPrinter.indent { + helperPrinter.write("const value = \(jsValueLiftHelperName)(kind, payload1, payload2);") + let holdsReference = JSValueKind.allCases.filter(\.holdsReference) + .map { "kind === \($0.rawValue)" } + .joined(separator: " || ") + helperPrinter.write("if (\(holdsReference)) {") + helperPrinter.indent { + helperPrinter.write("\(JSGlueVariableScope.reservedSwift).memory.release(payload1);") + } + helperPrinter.write("}") + helperPrinter.write("return value;") + } + helperPrinter.write("}") } } @@ -792,7 +827,7 @@ struct IntrinsicJSFragment: Sendable { printer.write("let \(payload2Var);") printer.write("if (\(value) === null) {") printer.indent { - printer.write("\(kindVar) = 4;") + printer.write("\(kindVar) = \(JSValueKind.null.rawValue);") printer.write("\(payload1Var) = 0;") printer.write("\(payload2Var) = 0;") } @@ -802,22 +837,22 @@ struct IntrinsicJSFragment: Sendable { printer.indent { printer.write("case \"boolean\":") printer.indent { - printer.write("\(kindVar) = 0;") + printer.write("\(kindVar) = \(JSValueKind.boolean.rawValue);") printer.write("\(payload1Var) = \(value) ? 1 : 0;") printer.write("\(payload2Var) = 0;") printer.write("break;") } printer.write("case \"number\":") printer.indent { - printer.write("\(kindVar) = 2;") + printer.write("\(kindVar) = \(JSValueKind.number.rawValue);") printer.write("\(payload1Var) = 0;") printer.write("\(payload2Var) = \(value);") printer.write("break;") } - func emitRetainCase(_ caseName: String, kind: Int) { + func emitRetainCase(_ caseName: String, kind: JSValueKind) { printer.write("case \"\(caseName)\":") printer.indent { - printer.write("\(kindVar) = \(kind);") + printer.write("\(kindVar) = \(kind.rawValue);") printer.write( "\(payload1Var) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));" ) @@ -825,18 +860,18 @@ struct IntrinsicJSFragment: Sendable { printer.write("break;") } } - emitRetainCase("string", kind: 1) + emitRetainCase("string", kind: .string) printer.write("case \"undefined\":") printer.indent { - printer.write("\(kindVar) = 5;") + printer.write("\(kindVar) = \(JSValueKind.undefined.rawValue);") printer.write("\(payload1Var) = 0;") printer.write("\(payload2Var) = 0;") printer.write("break;") } - emitRetainCase("object", kind: 3) - emitRetainCase("function", kind: 3) - emitRetainCase("symbol", kind: 7) - emitRetainCase("bigint", kind: 8) + emitRetainCase("object", kind: .object) + emitRetainCase("function", kind: .object) + emitRetainCase("symbol", kind: .symbol) + emitRetainCase("bigint", kind: .bigInt) printer.write("default:") printer.indent { printer.write("throw new TypeError(\"Unsupported JSValue type\");") @@ -874,53 +909,21 @@ struct IntrinsicJSFragment: Sendable { printer.write("let \(resultVar);") printer.write("switch (\(kind)) {") printer.indent { - printer.write("case 0:") - printer.indent { - printer.write("\(resultVar) = \(payload1) !== 0;") - printer.write("break;") - } - printer.write("case 1:") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" - ) - printer.write("break;") - } - printer.write("case 2:") - printer.indent { - printer.write("\(resultVar) = \(payload2);") - printer.write("break;") - } - printer.write("case 3:") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" - ) - printer.write("break;") - } - printer.write("case 4:") - printer.indent { - printer.write("\(resultVar) = null;") - printer.write("break;") - } - printer.write("case 5:") - printer.indent { - printer.write("\(resultVar) = undefined;") - printer.write("break;") - } - printer.write("case 7:") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" - ) - printer.write("break;") - } - printer.write("case 8:") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" - ) - printer.write("break;") + for valueKind in JSValueKind.allCases { + let value: String + switch valueKind { + case .boolean: value = "\(payload1) !== 0" + case .number: value = payload2 + case .null: value = "null" + case .undefined: value = "undefined" + case .string, .object, .symbol, .bigInt: + value = "\(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1))" + } + printer.write("case \(valueKind.rawValue):") + printer.indent { + printer.write("\(resultVar) = \(value);") + printer.write("break;") + } } printer.write("default:") printer.indent { @@ -961,11 +964,12 @@ struct IntrinsicJSFragment: Sendable { let resultVar = scope.variable("jsValue") registerJSValueHelpers(scope: scope) printer.write( - "const \(resultVar) = \(jsValueLiftHelperName)(\(kind), \(payload1), \(payload2));" + "const \(resultVar) = \(jsValueTakeHelperName)(\(kind), \(payload1), \(payload2));" ) return [resultVar] } ) + /// Swift lends the payload reference for the duration of the call, so it is not released here. static let jsValueLiftParameter = IntrinsicJSFragment( parameters: ["kind", "payload1", "payload2"], printCode: { arguments, context in @@ -2232,7 +2236,7 @@ struct IntrinsicJSFragment: Sendable { let resultVar = scope.variable("jsValue") registerJSValueHelpers(scope: scope) printer.write( - "const \(resultVar) = \(jsValueLiftHelperName)(\(kindVar), \(payload1Var), \(payload2Var));" + "const \(resultVar) = \(jsValueTakeHelperName)(\(kindVar), \(payload1Var), \(payload2Var));" ) return [resultVar] } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index b434d4e5e..adc2e0fc9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -267,7 +267,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -361,6 +361,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT16PolygonReference = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index f4c519fe9..6365fd99e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -274,7 +274,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -368,6 +368,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 6cc51f282..980dd9fdc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -271,7 +271,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -365,6 +365,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT10AsyncPoint = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 099a0756e..69f17eae3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -128,6 +128,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_createEnumHelpers_M10TestModuleT18AsyncPayloadResult = () => ({ lower: (value) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index 856c42435..db15b92a8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -121,6 +121,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 36d839ed9..f6da4e275 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -121,6 +121,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 03afa8031..cbca91ea2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -267,7 +267,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -361,6 +361,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT6Config = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 10f84209a..ab6cf6ebe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Dict_Int = __bjs_dictCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Dict_String = __bjs_dictCodec(__bjs_stringCodec); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 3f0c005f2..36d219f64 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -342,7 +342,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -436,6 +436,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index ce8d4ed42..e33778458 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -336,7 +336,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -430,6 +430,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT8FileSize = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index 49aaa5798..d6250c200 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -295,7 +295,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -389,6 +389,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index a3e0fd6d3..2a64c6775 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 2f45f8eed..3c4743ee6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Foo = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 07d7ba167..afccabed4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Array_JSValue = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue); const __bjs_codec_Optional_Array_JSValue = __bjs_optionalCodec(__bjs_codec_Array_JSValue); @@ -821,7 +828,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; } echoOptional(value) { @@ -844,7 +851,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); optResult = jsValue; } else { optResult = null; @@ -856,7 +863,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; } set value(value) { @@ -871,7 +878,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); optResult = jsValue; } else { optResult = null; @@ -901,7 +908,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, roundTripOptionalJSValue: function bjs_roundTripOptionalJSValue(value) { @@ -924,7 +931,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); optResult = jsValue; } else { optResult = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index a5f6d34f4..e76f92d8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT7Greeter = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index b13010601..31e413e1f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT7Greeter = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index fb8018c44..7aaa5296c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_JSObject = { lower: (v) => { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 8802e8786..945759fb1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -285,7 +285,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -379,6 +379,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 3f4ab6e05..082a42323 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -291,7 +291,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -385,6 +385,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index b15678998..3045dd8cb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -121,6 +121,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 54aa63d69..39ba60207 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -266,7 +266,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -360,6 +360,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 2ebef1501..0f0838b41 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -261,7 +261,7 @@ export async function createInstantiator(options, swift) { const jsValuePayload2 = f64Stack.pop(); const jsValuePayload1 = i32Stack.pop(); const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + const jsValue = __bjs_jsValueTake(jsValueKind, jsValuePayload1, jsValuePayload2); return jsValue; }, }, @@ -355,6 +355,13 @@ export async function createInstantiator(options, swift) { } return jsValue; } + function __bjs_jsValueTake(kind, payload1, payload2) { + const value = __bjs_jsValueLift(kind, payload1, payload2); + if (kind === 1 || kind === 3 || kind === 7 || kind === 8) { + swift.memory.release(payload1); + } + return value; + } const __bjs_codec_M10TestModuleT5Point = { lower: (v) => { diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index dd5e1e970..0b7fc3120 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -969,11 +969,14 @@ extension JSValue: _BridgedSwiftStackType { } @_spi(BridgeJS) public consuming func bridgeJSStackPush() -> Void { - let lowered = bridgeJSLowerParameter() - let retainedPayload1 = Self.bridgeJSRetainPayloadIfNeeded(kind: lowered.kind, payload1: lowered.payload1) - _swift_js_push_i32(lowered.kind) - _swift_js_push_i32(retainedPayload1) - _swift_js_push_f64(lowered.payload2) + // Retain inside `withRawJSValue` so `self` still owns the JS reference. + withRawJSValue { raw in + let kind = Int32(raw.kind.rawValue) + let payload1 = Int32(bitPattern: raw.payload1) + _swift_js_push_i32(kind) + _swift_js_push_i32(Self.bridgeJSRetainPayloadIfNeeded(kind: kind, payload1: payload1)) + _swift_js_push_f64(raw.payload2) + } } @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (kind: Int32, payload1: Int32, payload2: Double) { @@ -986,19 +989,18 @@ extension JSValue: _BridgedSwiftStackType { } } + /// Takes ownership of the payload reference that JavaScript retained when it lowered the value. @_spi(BridgeJS) public static func bridgeJSLiftParameter( _ kind: Int32, _ payload1: Int32, _ payload2: Double ) -> JSValue { - let retainedPayload1 = bridgeJSRetainPayloadIfNeeded(kind: kind, payload1: payload1) - guard let kindEnum = JavaScriptValueKind(rawValue: UInt32(kind)) else { fatalError("Invalid JSValue kind: \(kind)") } let rawValue = RawJSValue( kind: kindEnum, - payload1: JavaScriptPayload1(UInt32(bitPattern: retainedPayload1)), + payload1: JavaScriptPayload1(UInt32(bitPattern: payload1)), payload2: payload2 ) return rawValue.jsValue diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 55ab78e7a..a3e60711f 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -73,6 +73,14 @@ func runJsWorks() -> Void return v } +@JS func makeJSValueString() -> JSValue { + return .string("makeJSValueString") +} + +@JS func makeJSValueObject() -> JSValue { + return .object(JSObject()) +} + @JS func roundTripOptionalJSValue(v: JSValue?) -> JSValue? { return v } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 3b82a15d5..8bfe460fc 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -10531,6 +10531,28 @@ public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload #endif } +@_expose(wasm, "bjs_makeJSValueString") +@_cdecl("bjs_makeJSValueString") +public func _bjs_makeJSValueString() -> Void { + #if arch(wasm32) + let ret = makeJSValueString() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeJSValueObject") +@_cdecl("bjs_makeJSValueObject") +public func _bjs_makeJSValueObject() -> Void { + #if arch(wasm32) + let ret = makeJSValueObject() + return ret.bridgeJSLowerReturn() + #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 { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index c4fd1d602..fb4d924e7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -15686,6 +15686,40 @@ } } }, + { + "abiName" : "bjs_makeJSValueString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeJSValueString", + "parameters" : [ + + ], + "returnType" : { + "jsValue" : { + + } + } + }, + { + "abiName" : "bjs_makeJSValueObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeJSValueObject", + "parameters" : [ + + ], + "returnType" : { + "jsValue" : { + + } + } + }, { "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index e1d856647..6c53eb59f 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -227,7 +227,7 @@ export async function setupOptions(options, context) { }; }, addToCoreImports(importObject, importsContext) { - const { getInstance, getExports } = importsContext; + const { getInstance, getExports, _swift } = importsContext; options.addToCoreImports?.(importObject, importsContext); importObject["JavaScriptEventLoopTestSupportTests"] = { "isMainThread": () => context.isMainThread, @@ -238,7 +238,7 @@ export async function setupOptions(options, context) { if (!exports) { throw new Error("No exports!?"); } - return BridgeJSRuntimeTests_runJsWorks(getInstance(), exports); + return BridgeJSRuntimeTests_runJsWorks(getInstance(), exports, _swift); } bridgeJSRuntimeTests["runJsStructWorks"] = () => { const exports = getExports(); @@ -267,7 +267,7 @@ export async function setupOptions(options, context) { import assert from "node:assert"; /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ -function BridgeJSRuntimeTests_runJsWorks(instance, exports) { +function BridgeJSRuntimeTests_runJsWorks(instance, exports, swift) { exports.roundTripVoid(); for (const v of [ 0.0, 1.0, -1.0, @@ -610,6 +610,17 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { const result = exports.roundTripJSValue(value); assert.strictEqual(result, value); } + assert.strictEqual(exports.makeJSValueString(), "makeJSValueString"); + const madeObject = exports.makeJSValueObject(); + assert.deepStrictEqual(madeObject, {}); + + const isRetained = (value) => swift.memory._slotByValue.has(value); + assert.equal(isRetained(madeObject), false); + for (const value of [{}, "roundTripJSValue-ownership", Symbol("ownership"), 0xfedcba9876543210n]) { + assert.strictEqual(exports.roundTripJSValue(value), value); + assert.deepStrictEqual(exports.roundTripOptionalJSValueArray([value]), [value]); + assert.equal(isRetained(value), false); + } assert.strictEqual(exports.roundTripOptionalJSValue(null), null); assert.strictEqual(exports.roundTripOptionalJSValue(undefined), null); From 817304f59df3b75873a565982d80e48a7b9b4179 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 4 Nov 2026 01:13:26 +1000 Subject: [PATCH 138/140] PackageToJS: Import only the UWASI features Swift needs The UWASI platform wrappers imported `useAll` and `MemoryFileSystem`, so bundles always carried UWASI's in-memory file system and came out larger than the browser_wasi_shim default. Import `useStdio`, `useArgs`, `useEnviron`, `useClock`, `usePoll`, `useProc` and `useRandom` instead. File syscalls now return ENOSYS. With `--enable-code-coverage`, the Node wrapper adds `useMemoryFS`, because the test runner reads the coverage profile through `extractFile`. The browser wrapper never imports a file system. --- Plugins/PackageToJS/README.md | 6 + Plugins/PackageToJS/Sources/PackageToJS.swift | 1 + .../Templates/platforms/browser.js | 27 +- .../PackageToJS/Templates/platforms/node.js | 29 +- .../PackageToJS/Templates/platforms/uwasi.js | 50 ++- .../Tests/Inputs/UWASIAdapterTests.mjs | 168 +++++++--- .../Tests/PackagingPlannerTests.swift | 20 +- .../PackageToJS/Tests/TemplatesTests.swift | 18 +- .../planBuild_debug.json | 24 +- .../planBuild_debug_uwasi.json | 26 +- .../planBuild_debug_uwasi_coverage.json | 311 ++++++++++++++++++ .../planBuild_release.json | 24 +- .../planBuild_release_dwarf.json | 24 +- .../planBuild_release_name.json | 24 +- .../planBuild_release_no_optimize.json | 24 +- .../PackagingPlannerTests/planTestBuild.json | 32 +- .../Articles/Package-Output-Structure.md | 6 + 17 files changed, 622 insertions(+), 192 deletions(-) create mode 100644 Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi_coverage.json diff --git a/Plugins/PackageToJS/README.md b/Plugins/PackageToJS/README.md index 0e3e0e124..01a420466 100644 --- a/Plugins/PackageToJS/README.md +++ b/Plugins/PackageToJS/README.md @@ -22,6 +22,12 @@ to generate browser and Node platform wrappers backed by `uwasi` instead: swift package --swift-sdk wasm32-unknown-wasi js --wasi-runtime uwasi ``` +The `uwasi` wrappers import only the stdio, args, environ, clock, poll, proc and +random features, so bundlers can drop `uwasi`'s file system and file syscalls return +`ENOSYS`. With `--enable-code-coverage`, the Node wrapper adds an in-memory file +system so the test runner can read the coverage profile. To give an application a +file system, pass your own `wasi` object to `instantiate`. + The generated browser main-thread setup rejects blocking WASI waits. Run guests that require `poll_oneoff` clock waits in a worker. Node and browser workers use `uwasi`'s blocking implementation. diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index cf236c5cc..b736cca69 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -957,6 +957,7 @@ struct PackagingPlanner { let staticConditions: [String: Bool] = [ "USE_WASI_CDN": options.useCDN, "USE_UWASI": options.wasiRuntime == .uwasi, + "USE_UWASI_FILESYSTEM": options.wasiRuntime == .uwasi && options.enableCodeCoverage, "HAS_BRIDGE": skeletons.count > 0, "HAS_IMPORTS": skeletons.count > 0, "TARGET_DEFAULT_PLATFORM_NODE": options.defaultPlatform == .node, diff --git a/Plugins/PackageToJS/Templates/platforms/browser.js b/Plugins/PackageToJS/Templates/platforms/browser.js index e8c596308..6b148685f 100644 --- a/Plugins/PackageToJS/Templates/platforms/browser.js +++ b/Plugins/PackageToJS/Templates/platforms/browser.js @@ -4,11 +4,12 @@ import { MODULE_PATH /* #if USE_SHARED_MEMORY */, MEMORY_TYPE /* #endif */} from /* #if USE_UWASI */ /* #if USE_WASI_CDN */ // @ts-ignore -import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'https://cdn.jsdelivr.net/npm/uwasi@1.5.2/+esm'; +import { WASI, lineBuffered, useStdio, useArgs, useEnviron, useClock, usePoll, useProc, useRandom } from 'https://cdn.jsdelivr.net/npm/uwasi@1.5.2/+esm'; /* #else */ -import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'uwasi'; +import { WASI, lineBuffered, useStdio, useArgs, useEnviron, useClock, usePoll, useProc, useRandom } from 'uwasi'; /* #endif */ import { browserMainThreadSleep, createUwasi } from './uwasi.js'; +const uwasiRuntime = { WASI, lineBuffered, useStdio, useArgs, useEnviron, useClock, usePoll, useProc, useRandom }; /* #else */ /* #if USE_WASI_CDN */ // @ts-ignore @@ -38,10 +39,7 @@ export async function defaultBrowserThreadSetup() { /* #if IS_WASI */ /* #if USE_UWASI */ - const { wasi } = createUwasi( - { WASI, MemoryFileSystem, useAll, lineBuffered }, - { modulePath: MODULE_PATH } - ) + const { wasi } = createUwasi(uwasiRuntime, { modulePath: MODULE_PATH }) /* #else */ const wasi = new WASI(/* args */[MODULE_PATH], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin @@ -127,16 +125,13 @@ export async function defaultBrowserSetup(options) { const onStdoutLine = options.onStdoutLine ?? ((line) => console.log(line)) const onStderrLine = options.onStderrLine ?? ((line) => console.error(line)) /* #if USE_UWASI */ - const { wasi } = createUwasi( - { WASI, MemoryFileSystem, useAll, lineBuffered }, - { - modulePath: MODULE_PATH, - args, - onStdoutLine, - onStderrLine, - sleep: browserMainThreadSleep(), - } - ) + const { wasi } = createUwasi(uwasiRuntime, { + modulePath: MODULE_PATH, + args, + onStdoutLine, + onStderrLine, + sleep: browserMainThreadSleep(), + }) /* #else */ const wasi = new WASI(/* args */[MODULE_PATH, ...args], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin diff --git a/Plugins/PackageToJS/Templates/platforms/node.js b/Plugins/PackageToJS/Templates/platforms/node.js index b01290252..4725201b7 100644 --- a/Plugins/PackageToJS/Templates/platforms/node.js +++ b/Plugins/PackageToJS/Templates/platforms/node.js @@ -4,8 +4,17 @@ import { Worker, parentPort } from "node:worker_threads"; import { MODULE_PATH /* #if USE_SHARED_MEMORY */, MEMORY_TYPE /* #endif */} from "../instantiate.js" /* #if IS_WASI */ /* #if USE_UWASI */ -import { WASI, MemoryFileSystem, useAll, lineBuffered } from 'uwasi'; +import { WASI, lineBuffered, useStdio, useArgs, useEnviron, useClock, usePoll, useProc, useRandom } from 'uwasi'; +/* #if USE_UWASI_FILESYSTEM */ +import { MemoryFileSystem, useMemoryFS } from 'uwasi'; +/* #endif */ import { createUwasi } from './uwasi.js'; +const uwasiRuntime = { + WASI, lineBuffered, useStdio, useArgs, useEnviron, useClock, usePoll, useProc, useRandom, +/* #if USE_UWASI_FILESYSTEM */ + MemoryFileSystem, useMemoryFS, +/* #endif */ +}; /* #else */ import { WASI, File, OpenFile, ConsoleStdout, PreopenDirectory, Directory, Inode } from '@bjorn3/browser_wasi_shim'; /* #endif */ @@ -28,10 +37,7 @@ export async function defaultNodeThreadSetup() { } /* #if USE_UWASI */ - const { wasi } = createUwasi( - { WASI, MemoryFileSystem, useAll, lineBuffered }, - { modulePath: MODULE_PATH } - ) + const { wasi } = createUwasi(uwasiRuntime, { modulePath: MODULE_PATH }) /* #else */ const wasi = new WASI(/* args */[MODULE_PATH], /* env */[], /* fd */[ new OpenFile(new File([])), // stdin @@ -136,14 +142,11 @@ export async function defaultNodeSetup(options = {}) { const args = options.args ?? process.argv.slice(2) /* #if USE_UWASI */ - const { wasi } = createUwasi( - { WASI, MemoryFileSystem, useAll, lineBuffered }, - { - modulePath: MODULE_PATH, - args, - withExtractFile: true, - } - ) + const { wasi } = createUwasi(uwasiRuntime, { + modulePath: MODULE_PATH, + args, + withExtractFile: true, + }) /* #else */ const rootFs = new Map(); const wasi = new WASI(/* args */[MODULE_PATH, ...args], /* env */[], /* fd */[ diff --git a/Plugins/PackageToJS/Templates/platforms/uwasi.js b/Plugins/PackageToJS/Templates/platforms/uwasi.js index e7a9ce1bc..56212a108 100644 --- a/Plugins/PackageToJS/Templates/platforms/uwasi.js +++ b/Plugins/PackageToJS/Templates/platforms/uwasi.js @@ -17,7 +17,19 @@ export function browserMainThreadSleep() { } /** - * @param {{ WASI: any, MemoryFileSystem: any, useAll: any, lineBuffered: any }} runtime + * @param {{ + * WASI: any, + * lineBuffered: any, + * useStdio: any, + * useArgs: any, + * useEnviron: any, + * useClock: any, + * usePoll: any, + * useProc: any, + * useRandom: any, + * MemoryFileSystem?: any, + * useMemoryFS?: any, + * }} runtime * @param {{ * modulePath: string, * args?: string[], @@ -32,27 +44,35 @@ export function createUwasi(runtime, options) { const onStdoutLine = options.onStdoutLine ?? ((line) => console.log(line)); const onStderrLine = options.onStderrLine ?? ((line) => console.error(line)); - const fileSystem = new runtime.MemoryFileSystem({ "/": "/" }); - const stdout = runtime.lineBuffered(onStdoutLine); - const stderr = runtime.lineBuffered(onStderrLine); + const stdio = { + stdin: () => "", + stdout: runtime.lineBuffered(onStdoutLine), + stderr: runtime.lineBuffered(onStderrLine), + outputBuffers: true, + }; + const fileSystem = runtime.MemoryFileSystem + ? new runtime.MemoryFileSystem({ "/": "/" }) + : undefined; const wasi = new runtime.WASI({ args: [options.modulePath, ...args], env: {}, features: [ - runtime.useAll({ - withFileSystem: fileSystem, - withStdio: { - stdin: () => "", - stdout, - stderr, - outputBuffers: true, - }, - sleep: options.sleep, - }), + fileSystem + ? runtime.useMemoryFS({ + withFileSystem: fileSystem, + withStdio: stdio, + }) + : runtime.useStdio(stdio), + runtime.useArgs(), + runtime.useEnviron(), + runtime.useClock(), + runtime.usePoll({ sleep: options.sleep }), + runtime.useProc(), + runtime.useRandom(), ], }); - if (options.withExtractFile) { + if (fileSystem && options.withExtractFile) { Object.assign(wasi, { extractFile(filePath) { const node = fileSystem.lookup(filePath); diff --git a/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs index 94dfab59e..8084c5805 100644 --- a/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs +++ b/Plugins/PackageToJS/Tests/Inputs/UWASIAdapterTests.mjs @@ -1,25 +1,72 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { MemoryFileSystem, useAll, WASI } from "uwasi"; +import { + MemoryFileSystem, + useArgs, + useClock, + useEnviron, + useMemoryFS, + usePoll, + useProc, + useRandom, + useStdio, + WASI, +} from "uwasi"; import { browserMainThreadSleep, createUwasi, } from "../../Templates/platforms/uwasi.js"; -test("PackageToJS UWASI adapter preserves its host contracts", () => { - const stdout = []; - const stderr = []; - let lineBufferedCalls = 0; +const minimalRuntime = { + WASI, + useStdio, + useArgs, + useEnviron, + useClock, + usePoll, + useProc, + useRandom, +}; +const fileSystemRuntime = { ...minimalRuntime, MemoryFileSystem, useMemoryFS }; +const WASI_ERRNO_NOSYS = 52; + +function recordingLineBuffered() { + const calls = { count: 0 }; const lineBuffered = (writeLine) => { - lineBufferedCalls += 1; + calls.count += 1; return (chunk) => { const line = new TextDecoder().decode(chunk).replace(/\n$/, ""); writeLine(line); }; }; + return { calls, lineBuffered }; +} + +function bindMemory(wasi) { + const memory = new WebAssembly.Memory({ initial: 1 }); + wasi.setInstance({ exports: { memory } }); + return { + view: new DataView(memory.buffer), + bytes: new Uint8Array(memory.buffer), + }; +} + +function writeTo(wasi, { view, bytes }, fd, text) { + const chunk = new TextEncoder().encode(text); + bytes.set(chunk, 64); + view.setUint32(0, 64, true); + view.setUint32(4, chunk.length, true); + assert.equal(wasi.wasiImport.fd_write(fd, 0, 1, 8), 0); + assert.equal(view.getUint32(8, true), chunk.length); +} + +test("PackageToJS UWASI adapter preserves its host contracts with a file system", () => { + const stdout = []; + const stderr = []; + const { calls, lineBuffered } = recordingLineBuffered(); const { wasi, fileSystem } = createUwasi( - { WASI, MemoryFileSystem, useAll, lineBuffered }, + { ...fileSystemRuntime, lineBuffered }, { modulePath: "main.wasm", onStdoutLine: (line) => stdout.push(line), @@ -27,22 +74,11 @@ test("PackageToJS UWASI adapter preserves its host contracts", () => { withExtractFile: true, }, ); - const memory = new WebAssembly.Memory({ initial: 1 }); - wasi.setInstance({ exports: { memory } }); - - const view = new DataView(memory.buffer); - const bytes = new Uint8Array(memory.buffer); - const write = (fd, chunk) => { - bytes.set(chunk, 64); - view.setUint32(0, 64, true); - view.setUint32(4, chunk.length, true); - assert.equal(wasi.wasiImport.fd_write(fd, 0, 1, 8), 0); - assert.equal(view.getUint32(8, true), chunk.length); - }; + const memory = bindMemory(wasi); - write(1, new TextEncoder().encode("output\n")); - write(2, new TextEncoder().encode("error\n")); - assert.equal(lineBufferedCalls, 2); + writeTo(wasi, memory, 1, "output\n"); + writeTo(wasi, memory, 2, "error\n"); + assert.equal(calls.count, 2); assert.deepEqual(stdout, ["output"]); assert.deepEqual(stderr, ["error"]); @@ -53,39 +89,77 @@ test("PackageToJS UWASI adapter preserves its host contracts", () => { ); }); -test("PackageToJS forwards the host sleep policy", (t) => { - t.mock.method(performance, "now", () => 0); - const { wasi } = createUwasi( - { - WASI, - MemoryFileSystem, - useAll, - lineBuffered: (writeLine) => writeLine, - }, +test("PackageToJS UWASI adapter omits the file system by default", () => { + const stdout = []; + const stderr = []; + const { calls, lineBuffered } = recordingLineBuffered(); + const { wasi, fileSystem } = createUwasi( + { ...minimalRuntime, lineBuffered }, { modulePath: "main.wasm", - sleep(milliseconds) { - throw new Error(`cannot block for ${milliseconds}ms`); - }, + onStdoutLine: (line) => stdout.push(line), + onStderrLine: (line) => stderr.push(line), + withExtractFile: true, }, ); - const memory = new WebAssembly.Memory({ initial: 1 }); - wasi.setInstance({ exports: { memory } }); + const memory = bindMemory(wasi); + + writeTo(wasi, memory, 1, "output\n"); + writeTo(wasi, memory, 2, "error\n"); + assert.equal(calls.count, 2); + assert.deepEqual(stdout, ["output"]); + assert.deepEqual(stderr, ["error"]); - const view = new DataView(memory.buffer); - view.setBigUint64(0, 0n, true); - view.setUint8(8, 0); - view.setUint32(16, 1, true); - view.setBigUint64(24, 1_000_000n, true); - view.setBigUint64(32, 0n, true); - view.setUint16(40, 0, true); - - assert.throws( - () => wasi.wasiImport.poll_oneoff(0, 128, 1, 256), - /cannot block for 1ms/, + assert.equal(fileSystem, undefined); + assert.equal("extractFile" in wasi, false); + assert.equal(wasi.wasiImport.fd_prestat_get(3, 0), 8); + assert.equal( + wasi.wasiImport.path_open(3, 0, 0, 0, 0, 0n, 0n, 0, 0), + WASI_ERRNO_NOSYS, ); + for (const name of [ + "args_get", + "environ_get", + "clock_time_get", + "poll_oneoff", + "proc_exit", + "random_get", + ]) { + assert.ok(wasi.wasiImport[name].length > 0, `${name} must be provided`); + } }); +for (const [name, runtime] of [ + ["minimal", minimalRuntime], + ["file system", fileSystemRuntime], +]) { + test(`PackageToJS forwards the host sleep policy (${name})`, (t) => { + t.mock.method(performance, "now", () => 0); + const { wasi } = createUwasi( + { ...runtime, lineBuffered: (writeLine) => writeLine }, + { + modulePath: "main.wasm", + sleep(milliseconds) { + throw new Error(`cannot block for ${milliseconds}ms`); + }, + }, + ); + const { view } = bindMemory(wasi); + + view.setBigUint64(0, 0n, true); + view.setUint8(8, 0); + view.setUint32(16, 1, true); + view.setBigUint64(24, 1_000_000n, true); + view.setBigUint64(32, 0n, true); + view.setUint16(40, 0, true); + + assert.throws( + () => wasi.wasiImport.poll_oneoff(0, 128, 1, 256), + /cannot block for 1ms/, + ); + }); +} + test("PackageToJS blocks waits only on the browser main thread", () => { assert.equal(browserMainThreadSleep(), undefined); diff --git a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift index 2341f59af..d94e672bc 100644 --- a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift +++ b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift @@ -52,27 +52,31 @@ import Testing @Test(arguments: [ ( variant: "debug", configuration: "debug", noOptimize: false, - debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim, enableCodeCoverage: false ), ( variant: "debug_uwasi", configuration: "debug", noOptimize: false, - debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.uwasi + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.uwasi, enableCodeCoverage: false + ), + ( + variant: "debug_uwasi_coverage", configuration: "debug", noOptimize: false, + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.uwasi, enableCodeCoverage: true ), ( variant: "release", configuration: "release", noOptimize: false, - debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim, enableCodeCoverage: false ), ( variant: "release_no_optimize", configuration: "release", noOptimize: true, - debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim + debugInfoFormat: DebugInfoFormat.none, wasiRuntime: WASIRuntime.browserWASIShim, enableCodeCoverage: false ), ( variant: "release_dwarf", configuration: "release", noOptimize: false, - debugInfoFormat: DebugInfoFormat.dwarf, wasiRuntime: WASIRuntime.browserWASIShim + debugInfoFormat: DebugInfoFormat.dwarf, wasiRuntime: WASIRuntime.browserWASIShim, enableCodeCoverage: false ), ( variant: "release_name", configuration: "release", noOptimize: false, - debugInfoFormat: DebugInfoFormat.name, wasiRuntime: WASIRuntime.browserWASIShim + debugInfoFormat: DebugInfoFormat.name, wasiRuntime: WASIRuntime.browserWASIShim, enableCodeCoverage: false ), ]) func planBuild( @@ -80,10 +84,12 @@ import Testing configuration: String, noOptimize: Bool, debugInfoFormat: PackageToJS.DebugInfoFormat, - wasiRuntime: WASIRuntime + wasiRuntime: WASIRuntime, + enableCodeCoverage: Bool ) throws { var options = PackageToJS.PackageOptions() options.wasiRuntime = wasiRuntime + options.enableCodeCoverage = enableCodeCoverage let system = TestPackagingSystem() let planner = PackagingPlanner( options: options, diff --git a/Plugins/PackageToJS/Tests/TemplatesTests.swift b/Plugins/PackageToJS/Tests/TemplatesTests.swift index cc2b4d2a0..81240658b 100644 --- a/Plugins/PackageToJS/Tests/TemplatesTests.swift +++ b/Plugins/PackageToJS/Tests/TemplatesTests.swift @@ -17,12 +17,14 @@ import Foundation /// `npx tsc -p Templates/tsconfig.json` /// Test both WASI runtimes in node and browser platform variants. @Test(arguments: [ - (platform: "node", runtime: "browser-wasi-shim", sharedMemory: false), - (platform: "browser", runtime: "browser-wasi-shim", sharedMemory: false), - (platform: "node", runtime: "uwasi", sharedMemory: false), - (platform: "browser", runtime: "uwasi", sharedMemory: true), + (platform: "node", runtime: "browser-wasi-shim", sharedMemory: false, filesystem: false), + (platform: "browser", runtime: "browser-wasi-shim", sharedMemory: false, filesystem: false), + (platform: "node", runtime: "uwasi", sharedMemory: false, filesystem: false), + (platform: "node", runtime: "uwasi", sharedMemory: false, filesystem: true), + (platform: "browser", runtime: "uwasi", sharedMemory: true, filesystem: false), + (platform: "browser", runtime: "uwasi", sharedMemory: false, filesystem: true), ]) - func tscCheck(platform: String, runtime: String, sharedMemory: Bool) throws { + func tscCheck(platform: String, runtime: String, sharedMemory: Bool, filesystem: Bool) throws { // Use a local temporary directory to place instantiated templates so that // they can reference repo-root node_modules packages like @types/node. try FileManager.default.createDirectory( @@ -41,6 +43,7 @@ import Foundation "IS_WASI": true, "USE_WASI_CDN": false, "USE_UWASI": runtime == "uwasi", + "USE_UWASI_FILESYSTEM": runtime == "uwasi" && filesystem, "HAS_BRIDGE": false, "HAS_IMPORTS": false, "TARGET_DEFAULT_PLATFORM_NODE": platform == "node", @@ -78,6 +81,11 @@ import Foundation ) let expectedImport = runtime == "uwasi" ? "from 'uwasi'" : "from '@bjorn3/browser_wasi_shim'" #expect(platformSource.contains(expectedImport)) + if runtime == "uwasi" { + #expect(!platformSource.contains("useAll")) + #expect(platformSource.contains("useStdio")) + #expect(platformSource.contains("MemoryFileSystem") == (platform == "node" && filesystem)) + } let manifestData = try Data(contentsOf: destination.appending(path: "package.json")) let manifest = try #require( diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json index a21b94fd6..5ac062bc4 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json index 0948e2b74..b75adacfb 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/uwasi.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -274,7 +274,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjpmYWxzZSwiVVNFX1dBU0lfQ0ROIjpmYWxzZX0sInN1YnN0aXR1dGlvbnMiOnsiUEFDS0FHRV9UT19KU19NT0RVTEVfUEFUSCI6Im1haW4ud2FzbSIsIlBBQ0tBR0VfVE9fSlNfUEFDS0FHRV9OQU1FIjoidGVzdCJ9fQ==", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi_coverage.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi_coverage.json new file mode 100644 index 000000000..c503152db --- /dev/null +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug_uwasi_coverage.json @@ -0,0 +1,311 @@ +[ + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$INTERMEDIATES", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$WASM_PRODUCT_ARTIFACT" + ], + "output" : "$INTERMEDIATES\/wasm-imports.json", + "wants" : [ + "$INTERMEDIATES" + ] + }, + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$OUTPUT", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/index.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/index.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/index.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/index.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/instantiate.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/instantiate.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/instantiate.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/instantiate.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$WASM_PRODUCT_ARTIFACT" + ], + "output" : "$OUTPUT\/main.wasm", + "wants" : [ + "$OUTPUT" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/package.json", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" + ] + }, + { + "attributes" : [ + "silent" + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH" + ], + "output" : "$OUTPUT\/platforms", + "wants" : [ + + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/browser.worker.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/browser.worker.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/node.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/node.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/node.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/node.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/platforms\/uwasi.js", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/platforms\/uwasi.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Sources\/JavaScriptKit\/Runtime\/index.d.ts", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/runtime.d.ts", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + + ], + "inputs" : [ + "$PLANNER_SOURCE_PATH", + "$SELF_PACKAGE\/Sources\/JavaScriptKit\/Runtime\/index.mjs", + "$INTERMEDIATES\/wasm-imports.json" + ], + "output" : "$OUTPUT\/runtime.js", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOnRydWUsIlVTRV9VV0FTSV9GSUxFU1lTVEVNIjp0cnVlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "wants" : [ + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" + ] + }, + { + "attributes" : [ + "phony", + "silent" + ], + "inputs" : [ + + ], + "output" : "all", + "wants" : [ + "$OUTPUT\/main.wasm", + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/package.json", + "$OUTPUT\/index.js", + "$OUTPUT\/index.d.ts", + "$OUTPUT\/instantiate.js", + "$OUTPUT\/instantiate.d.ts", + "$OUTPUT\/platforms\/browser.js", + "$OUTPUT\/platforms\/browser.d.ts", + "$OUTPUT\/platforms\/browser.worker.js", + "$OUTPUT\/platforms\/node.js", + "$OUTPUT\/platforms\/node.d.ts", + "$OUTPUT\/runtime.js", + "$OUTPUT\/runtime.d.ts", + "$OUTPUT\/platforms\/uwasi.js" + ] + } +] \ No newline at end of file diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json index d2f0d0f38..7a881a621 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json @@ -60,7 +60,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -77,7 +77,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -94,7 +94,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -111,7 +111,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -142,7 +142,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -187,7 +187,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -204,7 +204,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -221,7 +221,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -238,7 +238,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -255,7 +255,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -272,7 +272,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json index a21b94fd6..5ac062bc4 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json index d2f0d0f38..7a881a621 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json @@ -60,7 +60,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -77,7 +77,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -94,7 +94,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -111,7 +111,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -142,7 +142,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -187,7 +187,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -204,7 +204,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -221,7 +221,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -238,7 +238,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -255,7 +255,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -272,7 +272,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", 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 a21b94fd6..5ac062bc4 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json @@ -46,7 +46,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -63,7 +63,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -80,7 +80,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -97,7 +97,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -127,7 +127,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -155,7 +155,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -172,7 +172,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -189,7 +189,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -206,7 +206,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -223,7 +223,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -240,7 +240,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -257,7 +257,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json index 3c4029927..e9a0b9fea 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json @@ -72,7 +72,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/bin\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -89,7 +89,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -106,7 +106,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -123,7 +123,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -140,7 +140,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -170,7 +170,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json" @@ -198,7 +198,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -215,7 +215,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -232,7 +232,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -249,7 +249,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -266,7 +266,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -283,7 +283,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -300,7 +300,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -317,7 +317,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.browser.html", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -334,7 +334,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", @@ -351,7 +351,7 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfVVdBU0kiOmZhbHNlLCJVU0VfVVdBU0lfRklMRVNZU1RFTSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", "wants" : [ "$OUTPUT", "$INTERMEDIATES\/wasm-imports.json", diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md index 6f3d30ac9..b0b84469a 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/Package-Output-Structure.md @@ -128,6 +128,12 @@ PackageToJS uses `@bjorn3/browser_wasi_shim` for WASI packages by default. Pass `--wasi-runtime uwasi` to generate both platform wrappers against `uwasi`; this also adds `platforms/uwasi.js` to the package. +The `uwasi` wrappers import only the stdio, args, environ, clock, poll, proc and random +features, so file syscalls return `ENOSYS` and bundlers can drop `uwasi`'s file system. +With `--enable-code-coverage`, the Node wrapper adds an in-memory file system so the +test runner can read the coverage profile. To give an application a file system, pass +your own `wasi` object to `instantiate`. + The browser main-thread setup rejects blocking `poll_oneoff` clock waits instead of freezing the page. Run guests that require blocking waits in a worker. Node and browser workers use `uwasi`'s blocking implementation. From 0cd2df484e879efb74b6a33e5a77bebaedb7ee62 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Sat, 7 Nov 2026 16:26:57 +0900 Subject: [PATCH 139/140] Runtime: Copy only the view's window in swjs_load_typed_array (#810) * Runtime: Copy only the view's window in swjs_load_typed_array `new Uint8Array(typedArray.buffer)` views the whole backing `ArrayBuffer`, ignoring the `byteOffset` and `byteLength` of the view it was handed. A view with a non-zero offset (anything from `subarray`, or `new Uint8Array(buffer, offset, length)`) therefore arrives in the guest shifted by that offset, silently wrong rather than failing. It is also a memory-safety bug: `JSTypedArray.copyMemory(to:)` sizes the destination from the view's own `length`, so whenever the view is smaller than its backing buffer the runtime writes past the end of the destination and corrupts whatever follows it in linear memory. Co-Authored-By: Claude Opus 5 * Tests: Use Int32(bitPattern:) for the 0xDEADBEEF sentinel Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5 --- Plugins/PackageToJS/Templates/runtime.mjs | 7 +- Runtime/src/index.ts | 11 +- Runtime/test/load-typed-array.test.ts | 107 ++++++++++++++++++ .../JSTypedArrayTests.swift | 78 +++++++++++++ 4 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 Runtime/test/load-typed-array.test.ts diff --git a/Plugins/PackageToJS/Templates/runtime.mjs b/Plugins/PackageToJS/Templates/runtime.mjs index b0be54bb4..6170e58d0 100644 --- a/Plugins/PackageToJS/Templates/runtime.mjs +++ b/Plugins/PackageToJS/Templates/runtime.mjs @@ -759,7 +759,12 @@ class SwiftRuntime { swjs_load_typed_array: (ref, buffer) => { const memory = this.memory; const typedArray = memory.getObject(ref); - const bytes = new Uint8Array(typedArray.buffer); + // Copy only the window the view describes. `typedArray.buffer` + // is the whole backing `ArrayBuffer`, which may be larger than + // the view and may start before it; the guest sizes the + // destination from the view's own length, so viewing the entire + // buffer would both shift the bytes and overrun the destination. + const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); this.getUint8Array().set(bytes, buffer >>> 0); }, swjs_release: (ref) => { diff --git a/Runtime/src/index.ts b/Runtime/src/index.ts index 879774a7d..e05bf712e 100644 --- a/Runtime/src/index.ts +++ b/Runtime/src/index.ts @@ -763,7 +763,16 @@ export class SwiftRuntime { swjs_load_typed_array: (ref: ref, buffer: pointer) => { const memory = this.memory; const typedArray = memory.getObject(ref); - const bytes = new Uint8Array(typedArray.buffer); + // Copy only the window the view describes. `typedArray.buffer` + // is the whole backing `ArrayBuffer`, which may be larger than + // the view and may start before it; the guest sizes the + // destination from the view's own length, so viewing the entire + // buffer would both shift the bytes and overrun the destination. + const bytes = new Uint8Array( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength, + ); this.getUint8Array().set(bytes, buffer >>> 0); }, diff --git a/Runtime/test/load-typed-array.test.ts b/Runtime/test/load-typed-array.test.ts new file mode 100644 index 000000000..724aa23fa --- /dev/null +++ b/Runtime/test/load-typed-array.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, test } from "vitest"; +import { SwiftRuntime } from "../src/index.js"; + +// `swjs_load_typed_array` must copy only the window a TypedArray view describes, +// not its whole backing `ArrayBuffer`. The guest sizes the destination from the +// view's own `length`/`byteLength`, so copying the entire buffer both shifts the +// bytes (a view with a non-zero `byteOffset` lands offset in the guest) and +// writes past the end of the destination. +const DESTINATION = 1024; + +function makeRuntime(): { runtime: SwiftRuntime; memory: WebAssembly.Memory } { + const memory = new WebAssembly.Memory({ initial: 1 }); + const runtime = new SwiftRuntime(); + runtime.setInstance({ + exports: { + memory, + swjs_library_version: () => 708, + }, + } as unknown as WebAssembly.Instance); + return { runtime, memory }; +} + +describe("swjs_load_typed_array respects the view's window", () => { + test("copies a Uint8Array view from its byteOffset", () => { + const { runtime, memory } = makeRuntime(); + const backing = new ArrayBuffer(32); + new Uint8Array(backing).set( + Array.from({ length: 32 }, (_, i) => 0xa0 + i), + ); + const view = new Uint8Array(backing, 8, 8); + + const space = (runtime as any).memory; + const imports = runtime.wasmImports as any; + imports.swjs_load_typed_array(space.retain(view), DESTINATION); + + const guest = new Uint8Array(memory.buffer); + expect( + Array.from(guest.subarray(DESTINATION, DESTINATION + 8)), + ).toEqual(Array.from(view)); + }); + + test("does not write past the end of the view", () => { + const { runtime, memory } = makeRuntime(); + const backing = new ArrayBuffer(32); + new Uint8Array(backing).fill(0xff); + const view = new Uint8Array(backing, 8, 8); + + // Fill the guest memory around the destination with a sentinel so any + // byte written beyond the view's `byteLength` is visible. + const guest = new Uint8Array(memory.buffer); + guest.fill(0x5a, DESTINATION, DESTINATION + 64); + + const space = (runtime as any).memory; + const imports = runtime.wasmImports as any; + imports.swjs_load_typed_array(space.retain(view), DESTINATION); + + expect( + Array.from(guest.subarray(DESTINATION + 8, DESTINATION + 64)), + ).toEqual(new Array(56).fill(0x5a)); + }); + + test("copies a multi-byte element view from its byteOffset", () => { + const { runtime, memory } = makeRuntime(); + const backing = new ArrayBuffer(32); + new Int32Array(backing).set([1, 2, 3, 4, 5, 6, 7, 8]); + const view = new Int32Array(backing, 8, 4); + + const space = (runtime as any).memory; + const imports = runtime.wasmImports as any; + imports.swjs_load_typed_array(space.retain(view), DESTINATION); + + const guest = new Int32Array(memory.buffer, DESTINATION, 4); + expect(Array.from(guest)).toEqual([3, 4, 5, 6]); + }); + + test("copies a DataView from its byteOffset", () => { + const { runtime, memory } = makeRuntime(); + const backing = new ArrayBuffer(32); + new Uint8Array(backing).set( + Array.from({ length: 32 }, (_, i) => 0xa0 + i), + ); + const view = new DataView(backing, 8, 8); + + const space = (runtime as any).memory; + const imports = runtime.wasmImports as any; + imports.swjs_load_typed_array(space.retain(view), DESTINATION); + + const guest = new Uint8Array(memory.buffer); + expect( + Array.from(guest.subarray(DESTINATION, DESTINATION + 8)), + ).toEqual(Array.from(new Uint8Array(backing, 8, 8))); + }); + + test("still copies a whole-buffer view unchanged", () => { + const { runtime, memory } = makeRuntime(); + const view = new Uint8Array([1, 2, 3, 4, 5]); + + const space = (runtime as any).memory; + const imports = runtime.wasmImports as any; + imports.swjs_load_typed_array(space.retain(view), DESTINATION); + + const guest = new Uint8Array(memory.buffer); + expect( + Array.from(guest.subarray(DESTINATION, DESTINATION + 5)), + ).toEqual([1, 2, 3, 4, 5]); + }); +}); diff --git a/Tests/JavaScriptKitTests/JSTypedArrayTests.swift b/Tests/JavaScriptKitTests/JSTypedArrayTests.swift index a4649879e..ad12a4e81 100644 --- a/Tests/JavaScriptKitTests/JSTypedArrayTests.swift +++ b/Tests/JavaScriptKitTests/JSTypedArrayTests.swift @@ -110,6 +110,84 @@ final class JSTypedArrayTests: XCTestCase { } } + func testTypedArrayWithByteOffset() { + // A view over part of a larger `ArrayBuffer`: `byteOffset` is non-zero and + // `byteLength` is smaller than the backing buffer. Copying the whole + // buffer instead of the view's window would both shift the bytes and + // write past the end of the destination, which is sized from `length`. + let backingLength = 32 + let viewOffset = 8 + let viewLength = 8 + + let arrayBuffer = JSObject.global.ArrayBuffer.function!.new(backingLength) + let wholeBuffer = JSTypedArray( + unsafelyWrapping: JSObject.global.Uint8Array.function!.new(arrayBuffer) + ) + for i in 0..( + unsafelyWrapping: JSObject.global.Uint8Array.function!.new( + arrayBuffer, + viewOffset, + viewLength + ) + ) + XCTAssertEqual(view.length, viewLength) + XCTAssertEqual(view.lengthInBytes, viewLength) + + let expected = (0...allocate(capacity: backingLength) + defer { storage.deallocate() } + storage.initialize(repeating: sentinel) + let destination = UnsafeMutableBufferPointer(rebasing: storage[0..(elements).jsObject.buffer.object! + let view = JSTypedArray( + unsafelyWrapping: JSObject.global.Int32Array.function!.new( + arrayBuffer, + viewOffsetInBytes, + viewLength + ) + ) + XCTAssertEqual(view.length, viewLength) + XCTAssertEqual(view.lengthInBytes, viewLength * MemoryLayout.size) + + let expected: [Int32] = [3, 4, 5, 6] + XCTAssertEqual(view.withUnsafeBytes { Array($0) }, expected) + + let sentinel = Int32(bitPattern: 0xDEAD_BEEF) + let storage = UnsafeMutableBufferPointer.allocate(capacity: elements.count) + defer { storage.deallocate() } + storage.initialize(repeating: sentinel) + let destination = UnsafeMutableBufferPointer(rebasing: storage[0..(length: 100) for i in 0..<100 { From 0a1c5a89adf273f99a626fce1dd3f255c45285d2 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Sat, 7 Nov 2026 17:28:18 +1000 Subject: [PATCH 140/140] BridgeJS: Normalize pointer in swift_js_push_typed_array (#828) --- Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 3 ++- .../BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/AliasInClosure.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ArrayTypes.js | 3 ++- .../BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js | 3 ++- .../BridgeJSLinkTests/AsyncAssociatedValueEnum.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/AsyncImport.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/DefaultParameters.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/DocComments.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumAlias.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js | 3 ++- .../BridgeJSLinkTests/EnumAssociatedValueImport.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumCase.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumNamespace.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/EnumRawType.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js | 3 ++- .../BridgeJSLinkTests/ExtensionOrderIndependence.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/GenericImports.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/GlobalGetter.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js | 3 ++- .../BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js | 3 ++- .../BridgeJSLinkTests/IdentityModeClass.PerClass.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ImportArray.js | 3 ++- .../BridgeJSLinkTests/ImportedTypeInExportedInterface.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSClass.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js | 3 ++- .../BridgeJSLinkTests/JSImportBareModuleFallback.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSImportModule.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSNameOverride.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSNameTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/JSValue.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/MixedGlobal.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/MixedModules.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/MixedPrivate.js | 3 ++- .../BridgeJSLinkTests/NamespacedClassSignature.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/Namespaces.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/NestedType.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/Optionals.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/PropertyTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/Protocol.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StaticFunctions.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StaticProperties.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StringParameter.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StringReturn.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftClass.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftClosure.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftStruct.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/Throws.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/UnsafePointer.js | 3 ++- .../__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js | 3 ++- 74 files changed, 148 insertions(+), 74 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index d882aad1c..82150d065 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -782,9 +782,10 @@ public struct BridgeJSLink { printer.indent { printer.write("const Ctor = taCtors[kind];") printer.write("const byteLen = count * Ctor.BYTES_PER_ELEMENT;") + printer.write("const start = ptr >>> 0;") // slice() copies the bytes into a new ArrayBuffer that is properly aligned printer.write( - "const copy = \(JSGlueVariableScope.reservedMemory).buffer.slice(ptr, ptr + byteLen);" + "const copy = \(JSGlueVariableScope.reservedMemory).buffer.slice(start, start + byteLen);" ) printer.write("\(JSGlueVariableScope.reservedTaStack).push(Array.from(new Ctor(copy)));") } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index adc2e0fc9..dafac12d3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -505,7 +505,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index d4174627e..4793a3d48 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 6365fd99e..1e46aa559 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -568,7 +568,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 980dd9fdc..ab64ccfa0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -480,7 +480,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_AsyncPoint"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 69f17eae3..3e1483580 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -245,7 +245,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index db15b92a8..7e6c1e2c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -227,7 +227,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index f6da4e275..0b854158d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -227,7 +227,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index 1d7ebeabf..08cab592c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -122,7 +122,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Account_Credentials"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index cbca91ea2..f8a62adb1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -492,7 +492,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Config"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index ab6cf6ebe..6e763b743 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -472,7 +472,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Counters"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 902f06ff9..aa3ac20c9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -122,7 +122,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 3ff888129..00725576a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 36d219f64..3369c92f9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -1067,7 +1067,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index 0d770ed41..df18151cc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -150,7 +150,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 999d1847f..5e55689ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -129,7 +129,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index 3a78dd143..20e16735c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -111,7 +111,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index b838f4c96..a8a01bda5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -149,7 +149,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 929f55c86..e63ffc2ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index e33778458..299a1d730 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -532,7 +532,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js index 1b54d416e..b573e3559 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js @@ -176,7 +176,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Library_Shelf"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js index cda13ba4c..094d37c11 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js @@ -125,7 +125,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Depot_Crate"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js index d0d1ea8bd..ca1cf7361 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js @@ -121,7 +121,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Meta"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 50d25d09b..636aacd1e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index d6250c200..a39fe8bd7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -579,7 +579,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_GenericPoint"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 1d299cab4..6917cc24e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 8c3f0b5b4..435110d18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index cc70a978a..308778af0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index b9b854e52..e1717e32e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index b9b854e52..e1717e32e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 2a64c6775..56a1489f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -440,7 +440,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 3c4743ee6..ea45f4fb1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -476,7 +476,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_FooContainer"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index edcedc1b7..8de2a8dc0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index cbec50c8f..732b4aaec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index 9cbaf2a3e..abd4e32d5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js index 50ed98d9a..f72355ae0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js @@ -111,7 +111,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js index ca94e5a13..bf2c55047 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js @@ -108,7 +108,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js index af4273cc3..130c0367c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -108,7 +108,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 0190b9c65..5025b2803 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -127,7 +127,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_RenamedVector"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js index 107f497fc..bbd490bd5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameTypes.js @@ -110,7 +110,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index 9d03440f5..8ce616dd0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index afccabed4..37c4134d6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -439,7 +439,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 964b97e3a..dfe74e98b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index d8eee50de..4219f5249 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 359f5ddd9..405be1d28 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js index 1d6b6c343..db7ead8eb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index e76f92d8f..a40655ea6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -447,7 +447,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 31e413e1f..815e564be 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -447,7 +447,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index 82710d04b..a1c133290 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_User_Stats"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js index 541ad55df..b9697fc97 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js @@ -126,7 +126,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Catalog_Entry"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 7aaa5296c..ac372c3d1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -463,7 +463,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 3b8c9adbc..2d89454c2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index 1177dc82b..d3b49e4f3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 44eab0d15..d136df4fc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 945759fb1..5ab588886 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -532,7 +532,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index a9730573c..c35d725e6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js index 06af75757..87daa2d84 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js @@ -148,7 +148,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Library_Shelf"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js index c5e67f8ae..deb145efa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReservedWordParameters.js @@ -131,7 +131,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 4cc10e4b9..a5f1258e4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -149,7 +149,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index b9c8414b0..e52f9d5dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -149,7 +149,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 7eff82661..94888662f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -110,7 +110,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index f8aa35927..84fb321ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -110,7 +110,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 6dc173b63..78f6a8dbc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index eb4e4c37b..0a8460da0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index f9b50f9f8..c5e8ebe24 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -164,7 +164,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Shape"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index e171064a6..fc6903739 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 082a42323..ece62f6ac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -574,7 +574,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Animal"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 3045dd8cb..eb2347864 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -227,7 +227,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 39ba60207..7ba2ada2f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -617,7 +617,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_DataPoint"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 0f0838b41..c1bb5d023 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -458,7 +458,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 80e2a1984..1abc20336 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -130,7 +130,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 5a575ffed..3b36bb511 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -105,7 +105,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {}; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index ef00d53a6..f3d2a217a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -122,7 +122,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_PointerFields"] = function(objectId) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 5abfccc3f..c8693eeb3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -106,7 +106,8 @@ export async function createInstantiator(options, swift) { 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); + const start = ptr >>> 0; + const copy = memory.buffer.slice(start, start + byteLen); taStack.push(Array.from(new Ctor(copy))); } bjs["bjs_core_register_type_handles"] = function() {};