From bd8b6ad3a92dbb02ef28e62ef34edd484a364303 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 22 Sep 2026 16:20:13 +0200 Subject: [PATCH 1/3] BridgeJS: Support generic exports and callbacks --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 44 +- .../Sources/BridgeJSCore/ExportSwift.swift | 252 +++++++++- .../Sources/BridgeJSCore/ImportTS.swift | 8 +- .../BridgeJSCore/SwiftToSkeleton.swift | 316 +++++++++++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 457 ++++++++++++++---- .../Sources/BridgeJSLink/JSGlueGen.swift | 66 +++ .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 67 ++- 7 files changed, 1061 insertions(+), 149 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 7459d6058..eeecdac6a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -47,6 +47,7 @@ public struct ClosureCodegen { for (index, paramType) in signature.parameters.enumerated() { try builder.lowerParameter(param: Parameter(label: nil, name: "param\(index)", type: paramType)) } + builder.appendTypeIDParameters(signature.genericParameterNames) // Generate the call and return value lifting try builder.call() @@ -69,7 +70,14 @@ public struct ClosureCodegen { let helperEnumDeclPrinter = CodeFragmentPrinter() helperEnumDeclPrinter.write("private enum \(helperName) {") helperEnumDeclPrinter.indent { - helperEnumDeclPrinter.write("static func bridgeJSLift(_ callbackId: Int32) -> \(swiftClosureType) {") + let genericNames = signature.genericParameterNames + let genericClause = + genericNames.isEmpty + ? "" : "<\(genericNames.map { "\($0): BridgedSwiftGenericBridgeable" }.joined(separator: ", "))>" + let parameters = (["_ callbackId: Int32"] + genericNames.map { "_: \($0).Type" }).joined(separator: ", ") + helperEnumDeclPrinter.write( + "static func bridgeJSLift\(genericClause)(\(parameters)) -> \(swiftClosureType) {" + ) helperEnumDeclPrinter.indent { helperEnumDeclPrinter.write("let callback = JSObject.bridgeJSLiftParameter(callbackId)") let parameters: String @@ -112,6 +120,10 @@ public struct ClosureCodegen { let helperEnumDecl: DeclSyntax = "\(raw: helperEnumDeclPrinter.lines.joined(separator: "\n"))" + if !signature.genericParameterNames.isEmpty { + return [externDecl, helperEnumDecl] + } + let accessModifier = accessLevel.modifierKeyword.map { "\($0) " } ?? "" let declaration = signature.sendingParameters ? "static func sending" : "init" let returnClause = signature.sendingParameters ? " -> Self" : "" @@ -164,10 +176,38 @@ public struct ClosureCodegen { guard !signatureAccessLevels.isEmpty else { return nil } var decls: [DeclSyntax] = [] + var asyncGenericResults = Set() 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)) + if signature.genericParameterNames.isEmpty { + decls.append(try renderClosureInvokeHandler(signature)) + } + let returnType = signature.returnType + if signature.isAsync, returnType.usesGenericParameter, asyncGenericResults.insert(returnType).inserted { + let parameter = Parameter(label: nil, name: "value", type: .jsValue) + let effects = Effects(isAsync: false, isThrows: true) + let builder = try ImportTS.CallJSEmission( + moduleName: "bjs", + abiName: "async_callback_result_\(signature.moduleName)_\(returnType.mangleTypeName)", + effects: effects, + returnType: returnType + ) + try builder.lowerParameter(param: parameter) + builder.appendTypeIDParameters(returnType.referencedGenericNames) + try builder.call() + try builder.liftReturnValue() + decls.append(builder.renderImportDecl()) + decls.append( + builder.renderThunkDecl( + name: "_bjs_async_result_\(returnType.mangleTypeName)", + parameters: [parameter], + returnType: returnType, + effects: effects, + genericParameters: returnType.referencedGenericNames.map { GenericParameter(name: $0) } + ) + ) + } } return withSpan("Format Closure Glue") { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 6b5d3ef76..9dded05ab 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -162,17 +162,24 @@ public class ExportSwift { for parameter in parameters { try builder.lowerParameter(param: parameter) } + let genericNames = valueType.referencedGenericNames + let genericParameters = genericNames.map { GenericParameter(name: $0) } + builder.appendTypeIDParameters(genericNames) try builder.call() try builder.liftReturnValue() let valueParam = valueType == .void ? "" : ", _ value: \(valueType.swiftType)" + let genericClause = + genericNames.isEmpty + ? "" : "<\(genericNames.map { "\($0): BridgedSwiftGenericBridgeable" }.joined(separator: ", "))>" let macroDecl: DeclSyntax = - "@JSFunction func \(raw: functionName)(_ promise: JSObject\(raw: valueParam)) throws(JSException)" + "@JSFunction func \(raw: functionName)\(raw: genericClause)(_ promise: JSObject\(raw: valueParam)) throws(JSException)" let glueDecl = builder.renderThunkDecl( name: "_$\(functionName)", parameters: parameters, returnType: .void, - effects: effects + effects: effects, + genericParameters: genericParameters ) return [macroDecl, builder.renderImportDecl(), glueDecl] } @@ -185,14 +192,18 @@ public class ExportSwift { var externDecls: [DeclSyntax] = [] let effects: Effects + let genericParameters: [GenericParameter] + var genericParameterNames: [String] { genericParameters.map(\.name) } + /// The async return type settled through `_bjs_makePromise`'s `Promise_resolve_` /// helper. Set for every `async` thunk. var asyncResolveReturnType: BridgeType? var parameterBindings: [CodeBlockItemSyntax] = [] - init(effects: Effects, returnType: BridgeType) throws { + init(effects: Effects, returnType: BridgeType, genericParameters: [GenericParameter] = []) throws { self.effects = effects + self.genericParameters = genericParameters guard effects.isAsync else { return } guard returnType.isAsyncResolvable else { throw BridgeJSCoreError( @@ -213,6 +224,15 @@ public class ExportSwift { func liftParameter(param: Parameter) throws { parameters.append(param) + if param.type.usesGenericParameter { + guard let popExpression = param.type.exportGenericStackPopExpression else { + throw BridgeJSCoreError( + "Unsupported generic parameter shape for '\(param.name)': \(param.type.swiftType)" + ) + } + parameterBindings.insert("let \(raw: param.name) = \(raw: popExpression)", at: 0) + return + } let liftingInfo = try param.type.liftParameterInfo() let argumentsToLift: [String] if liftingInfo.parameters.count == 1 { @@ -227,7 +247,10 @@ 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))") + let arguments = ([param.name] + signature.genericParameterNames.map { "\($0).self" }).joined( + separator: ", " + ) + liftingExpr = ExprSyntax("_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: arguments))") case .swiftStruct(let structName): typeNameForIntrinsic = structName liftingExpr = ExprSyntax("\(raw: structName).bridgeJSLiftParameter()") @@ -302,8 +325,9 @@ public class ExportSwift { return CodeBlockItemSyntax(item: .init(ExpressionStmtSyntax(expression: callExpr))) } else { let (prefix, suffix) = protocolCastSuffix(for: returnType) + let annotation = returnType.usesGenericParameter ? ": \(returnType.swiftType)" : "" return CodeBlockItemSyntax( - item: .init(DeclSyntax("let ret = \(raw: prefix)\(raw: callExpr)\(raw: suffix)")) + item: .init(DeclSyntax("let ret\(raw: annotation) = \(raw: prefix)\(raw: callExpr)\(raw: suffix)")) ) } } @@ -371,6 +395,10 @@ public class ExportSwift { // The async return value is lowered by the generated `Promise_resolve_*` helper. return } + if let pushStatement = returnType.exportGenericStackPushStatement(value: "ret") { + append("\(raw: pushStatement)") + return + } switch returnType { case .closure(_, useJSTypedClosure: false): @@ -406,7 +434,9 @@ public class ExportSwift { /// `throws(any Error)` instead of `throws(JSException)`. /// See: https://github.com/swiftlang/swift/issues/76165 private func asyncThrowsClosureHead(returnSpelling: String?, forcesCapture: Bool) -> String { - guard effects.isThrows else { return "" } + guard effects.isThrows else { + return genericParameters.isEmpty ? "" : " () async -> \(returnSpelling ?? "Void") in" + } let returns = returnSpelling.map { " -> \($0)" } ?? "" let capture = forcesCapture ? "[__bjs_capture] " : "" return " \(capture)() async throws(JSException)\(returns) in" @@ -422,7 +452,7 @@ public class ExportSwift { effects.isThrows && parameterBindings.isEmpty } - func render(abiName: String) -> DeclSyntax { + private func renderBody() -> CodeBlockItemListSyntax { var bindings = parameterBindings let body: CodeBlockItemListSyntax if effects.isAsync, let resolveType = asyncResolveReturnType { @@ -470,6 +500,14 @@ public class ExportSwift { \(CodeBlockItemListSyntax(bindings.map { $0.with(\.leadingTrivia, .newline) })) \(body) """ + return preparedBody + } + + func render(abiName: String) -> DeclSyntax { + if !genericParameterNames.isEmpty { + return renderGenericEntryThunk(abiName: abiName) + } + let preparedBody = renderBody() // Build function signature using SwiftSignatureBuilder let signature = SwiftSignatureBuilder.buildABIFunctionSignature( abiParameters: abiParameterSignatures, @@ -490,6 +528,164 @@ public class ExportSwift { private func returnPlaceholderStmt() -> String { return abiReturnType?.swiftReturnPlaceholderStmt ?? "return" } + + func protocolConstraints(_ genericName: String) -> [String] { + genericParameters.first(where: { $0.name == genericName })?.constraints ?? [] + } + + func constraintComposition(_ genericName: String) -> String { + let parameter = genericParameters.first(where: { $0.name == genericName }) + let constraints = parameter?.swiftConstraints ?? parameter?.constraints ?? [] + return (["BridgedSwiftGenericBridgeable"] + constraints).joined(separator: " & ") + } + + func existentialMetatype(_ genericName: String) -> String { + let constraints = protocolConstraints(genericName) + if constraints.isEmpty { + return "any BridgedSwiftGenericBridgeable.Type" + } + return "any (\(constraintComposition(genericName))).Type" + } + + private func renderGenericEntryThunk(abiName: String) -> DeclSyntax { + let genericNames = genericParameterNames + let count = genericNames.count + func genericIndex(_ genericName: String) -> Int { genericNames.firstIndex(of: genericName)! } + func metatypeName(_ genericName: String) -> String { "_generic\(genericIndex(genericName))Type" } + func typeIdName(_ genericName: String) -> String { + ABINameGenerator.genericTypeIdParameterName(index: genericIndex(genericName)) + } + + let concreteABIParameters = abiParameterSignatures + let concreteABINames = concreteABIParameters.map { $0.name } + let returnPrefix = abiReturnType == nil ? "" : "return " + let returnClause = abiReturnType.map { " -> \($0.swiftType)" } ?? "" + let thunkSignature = SwiftSignatureBuilder.buildABIFunctionSignature( + abiParameters: concreteABIParameters + genericNames.map { (name: typeIdName($0), type: .i32) }, + returnType: abiReturnType + ) + + let printer = CodeFragmentPrinter() + printer.write("#if hasFeature(Embedded)") + printer.write(SwiftCodePattern.buildExposeAttributes(abiName: abiName)) + printer.write("public func _\(abiName)\(thunkSignature) {") + printer.indent { + printer.write( + "fatalError(\"Generic @JS exported functions are not supported in Embedded Swift\")" + ) + } + printer.write("}") + printer.write("#else") + let entryDecl = SwiftCodePattern.buildExposedFunctionDecl( + abiName: abiName, + signature: thunkSignature + ) { printer in + for genericName in genericNames { + let constraints = protocolConstraints(genericName) + let recoveredName = + constraints.isEmpty ? metatypeName(genericName) : "\(metatypeName(genericName))Base" + printer.write( + "let \(recoveredName) = " + + "Unmanaged.fromOpaque(" + + "UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: \(typeIdName(genericName)))))!" + + ").takeUnretainedValue().type" + ) + if !constraints.isEmpty { + printer.write( + "guard let \(metatypeName(genericName)) = \(recoveredName) as? \(existentialMetatype(genericName)) else {" + ) + printer.indent { + printer.write( + "fatalError(\"BridgeJS: type '\\(\(recoveredName))' does not conform to required protocol(s): \(constraints.joined(separator: ", "))\")" + ) + } + printer.write("}") + } + } + let open1Arguments = genericNames.map { metatypeName($0) } + concreteABINames + let open1Call = "_\(abiName)_open1(\(open1Arguments.joined(separator: ", ")))" + if effects.isThrows && !effects.isAsync { + printer.write("do {") + printer.indent { + printer.write("\(returnPrefix)try \(open1Call)") + } + printer.write("} catch let error {") + printer.indent { + printer.write( + multilineString: """ + 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)) + } + } + \(returnPlaceholderStmt()) + """ + ) + } + printer.write("}") + } else { + printer.write("\(returnPrefix)\(open1Call)") + } + } + printer.write(multilineString: entryDecl.description) + + for k in 1...count { + let openName = "_\(abiName)_open\(k)" + let openedName = genericNames[k - 1] + let alreadyOpened = Array(genericNames[0..<(k - 1)]) + let remaining = Array(genericNames[k.." + + var params: [String] = [] + params.append("_ \(metatypeName(openedName)): \(openedName).Type") + for openedAlready in alreadyOpened { + params.append("as\(openedAlready) \(metatypeName(openedAlready)): \(openedAlready).Type") + } + for remainingName in remaining { + params.append("_ \(metatypeName(remainingName)): \(existentialMetatype(remainingName))") + } + for abiParam in concreteABIParameters { + params.append("_ \(abiParam.name): \(abiParam.type.swiftType)") + } + + let effectsClause = effects.isThrows && !effects.isAsync ? " throws(JSException)" : "" + printer.write( + "private func \(openName)\(genericClause)(\(params.joined(separator: ", ")))\(effectsClause)\(returnClause) {" + ) + printer.indent { + if k < count { + let nextOpenedName = genericNames[k] + var callArguments: [String] = [metatypeName(nextOpenedName)] + for threadedName in genericNames[0.. DeclSyntax { - let builder = try ExportedThunkBuilder(effects: function.effects, returnType: function.returnType) + let builder = try ExportedThunkBuilder( + effects: function.effects, + returnType: function.returnType, + genericParameters: function.genericParameters ?? [] + ) for param in function.parameters { try builder.liftParameter(param: param) } @@ -655,7 +855,11 @@ public class ExportSwift { ownerTypeName: String, instanceSelfType: BridgeType ) throws -> DeclSyntax { - let builder = try ExportedThunkBuilder(effects: method.effects, returnType: method.returnType) + let builder = try ExportedThunkBuilder( + effects: method.effects, + returnType: method.returnType, + genericParameters: method.genericParameters ?? [] + ) if !method.effects.isStatic { try builder.liftParameter(param: Parameter(label: nil, name: "_self", type: instanceSelfType)) } @@ -922,7 +1126,7 @@ struct StackCodegen { return "()" case .generic: fatalError( - "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + "Generic parameters cannot appear in struct fields or enum payloads; they are handled by the exported thunk builder" ) } } @@ -971,7 +1175,7 @@ struct StackCodegen { return lowerDictionaryStatements(valueType: valueType, accessor: accessor, varPrefix: varPrefix) case .generic: fatalError( - "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + "Generic parameters cannot appear in struct fields or enum payloads; they are handled by the exported thunk builder" ) } } @@ -1664,6 +1868,24 @@ extension BridgeType { } } + var exportGenericStackPopExpression: String? { + switch self { + case .generic(let name): return "\(name).bridgeJSStackPop()" + case .array(.generic(let name)): return "Array<\(name)>.bridgeJSStackPop()" + case .nullable(.generic(let name), _): return "Optional<\(name)>.bridgeJSStackPop()" + case .dictionary(.generic(let name)): return "Dictionary.bridgeJSStackPop()" + default: return nil + } + } + + func exportGenericStackPushStatement(value: String) -> String? { + switch self { + case .generic, .array(.generic), .nullable(.generic, _), .dictionary(.generic): + return "\(value).bridgeJSStackPush()" + default: return nil + } + } + var swiftType: String { switch self { case .bool: return "Bool" @@ -1768,9 +1990,7 @@ extension BridgeType { 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" - ) + return LiftingIntrinsicInfo(parameters: []) } } @@ -1825,9 +2045,7 @@ extension BridgeType { 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" - ) + return LoweringIntrinsicInfo(returnType: nil) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 378fe2012..afdd9ca80 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -346,7 +346,7 @@ public struct ImportTS { "\(tryKeyword) await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" ) } else { - let resolveSwiftType = returnType.closureSwiftType + let resolveSwiftType = returnType.usesGenericParameter ? "JSValue" : returnType.closureSwiftType let resolveFactory = "makeResolveClosure: { JSTypedClosure<(sending \(resolveSwiftType)) -> Void>.sending($0) }" body.write( @@ -359,7 +359,11 @@ public struct ImportTS { body.write("}") if returnType != .void { - body.write("return resolved") + if returnType.usesGenericParameter { + body.write("return \(tryKeyword) _bjs_async_result_\(returnType.mangleTypeName)(resolved)") + } else { + body.write("return resolved") + } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 0f9f79c06..a80313cab 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -300,6 +300,8 @@ public final class SwiftToSkeleton { collector.finalize(&exported) } + mergeExtensionDeclaredJSProtocolConformances(into: &exported) + perSourceErrors.append(contentsOf: diagnoseProtocolConformances(in: exported)) if !perSourceErrors.isEmpty { @@ -418,6 +420,74 @@ public final class SwiftToSkeleton { return diagnostics } + private func mergeExtensionDeclaredJSProtocolConformances(into exported: inout ExportedSkeleton) { + var targets: [(name: String, type: TypeSyntax, protocols: [String])] = [] + for declaration in typeDeclResolver.declarationsWithInheritance { + guard let extensionDecl = declaration.as(ExtensionDeclSyntax.self) else { continue } + let protocols = (extensionDecl.inheritanceClause?.inheritedTypes ?? []).compactMap { + resolveJSProtocolConstraint(for: $0.type) + } + if !protocols.isEmpty { + targets.append((extensionDecl.extendedType.trimmedDescription, extensionDecl.extendedType, protocols)) + } + } + guard !targets.isEmpty else { return } + var protocolsByTarget: [String: [String]] = [:] + for target in targets { + protocolsByTarget[target.name, default: []].append(contentsOf: target.protocols) + } + + func merge(_ existing: inout [String]?, additions: [String]) { + var result = existing ?? [] + for name in additions where !result.contains(name) { + result.append(name) + } + existing = result.isEmpty ? nil : result + } + + var matchedTargets: Set = [] + for index in exported.structs.indices { + if let additions = protocolsByTarget[exported.structs[index].swiftCallName] { + merge(&exported.structs[index].conformedJSProtocols, additions: additions) + matchedTargets.insert(exported.structs[index].swiftCallName) + } + } + for index in exported.classes.indices { + if let additions = protocolsByTarget[exported.classes[index].swiftCallName] { + merge(&exported.classes[index].conformedJSProtocols, additions: additions) + matchedTargets.insert(exported.classes[index].swiftCallName) + } + } + for index in exported.enums.indices { + if let additions = protocolsByTarget[exported.enums[index].swiftCallName] { + merge(&exported.enums[index].conformedJSProtocols, additions: additions) + matchedTargets.insert(exported.enums[index].swiftCallName) + } + } + + var externalConformances: [String: [String]] = [:] + for target in targets where !matchedTargets.contains(target.name) { + var scratchErrors: [DiagnosticError] = [] + guard let externalType = resolveExternal(for: target.type, errors: &scratchErrors) else { continue } + let externalName: String? + switch externalType { + case .swiftStruct(let name), .swiftHeapObject(let name), + .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name): + externalName = name + default: + externalName = nil + } + guard let externalName else { continue } + for protocolName in target.protocols + where !(externalConformances[externalName] ?? []).contains(protocolName) { + externalConformances[externalName, default: []].append(protocolName) + } + } + if !externalConformances.isEmpty { + exported.externalJSProtocolConformances = externalConformances + } + } + private static let jsTypedArrayTypealiasNames: [String: String] = [ "Int8": "JSInt8Array", "UInt8": "JSUint8Array", @@ -431,10 +501,31 @@ public final class SwiftToSkeleton { "Float64": "JSFloat64Array", ] - func lookupType(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { + func lookupType( + for type: TypeSyntax, + errors: inout [DiagnosticError], + genericParameterNames: [String] = [] + ) -> BridgeType? { + if !genericParameterNames.isEmpty, !type.is(FunctionTypeSyntax.self) { + switch resolveGenericTypeReference(for: type, genericParameterNames: genericParameterNames) { + case .resolved(let bridgeType): return bridgeType + case .rejected(let message): + if let message { + errors.append(DiagnosticError(node: type, message: message)) + return nil + } + } + } if let attributedType = type.as(AttributedTypeSyntax.self) { return lookupType(for: attributedType.baseType, errors: &errors) } + if let existential = type.as(SomeOrAnyTypeSyntax.self), + existential.someOrAnySpecifier.tokenKind == .keyword(.any), + let resolved = lookupType(for: existential.constraint, errors: &errors), + case .swiftProtocol = resolved + { + return resolved + } // JSTypedArray if let identifierType = type.as(IdentifierTypeSyntax.self), @@ -462,13 +553,25 @@ public final class SwiftToSkeleton { if let functionType = type.as(FunctionTypeSyntax.self) { var parameters: [BridgeType] = [] for param in functionType.parameters { - guard let paramType = lookupType(for: param.type, errors: &errors) else { + guard + let paramType = lookupType( + for: param.type, + errors: &errors, + genericParameterNames: genericParameterNames + ) + else { return nil } parameters.append(paramType) } - guard let returnType = lookupType(for: functionType.returnClause.type, errors: &errors) else { + guard + let returnType = lookupType( + for: functionType.returnClause.type, + errors: &errors, + genericParameterNames: genericParameterNames + ) + else { return nil } @@ -1555,15 +1658,103 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .array(elements) } + private func lookupTypeWithGenerics( + for type: TypeSyntax, + genericParameterNames: [String], + allowGenericCallback: Bool = false, + errors: inout [DiagnosticError] + ) -> BridgeType? { + if wrappedGenericParameter(in: type, genericParameterNames: genericParameterNames) != nil, + type.is(FunctionTypeSyntax.self) + || type.as(AttributedTypeSyntax.self)?.baseType.is(FunctionTypeSyntax.self) == true + { + var callbackType = type + if let attributed = type.as(AttributedTypeSyntax.self), + attributed.specifiers.isEmpty, + attributed.attributes.allSatisfy({ + $0.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "escaping" + }) + { + callbackType = attributed.baseType + } + guard allowGenericCallback, let functionType = callbackType.as(FunctionTypeSyntax.self) + else { + errors.append( + DiagnosticError( + node: type, + message: + "Generic callbacks must be parameters of @JS functions, optionally marked @escaping." + ) + ) + return nil + } + if functionType.parameters.contains(where: { + $0.type.as(AttributedTypeSyntax.self)?.specifiers.isEmpty == false || $0.ellipsis != nil + }) { + errors.append( + DiagnosticError( + node: type, + message: "Generic callbacks cannot have inout, ownership, or variadic parameters." + ) + ) + return nil + } + guard + let resolved = parent.lookupType( + for: callbackType, + errors: &errors, + genericParameterNames: genericParameterNames + ), + case .closure(let signature, _) = resolved + else { return nil } + guard !(signature.parameters + [signature.returnType]).contains(where: \.isClosureType) else { + errors.append( + DiagnosticError(node: type, message: "Generic callbacks cannot take or return other closures yet.") + ) + return nil + } + return resolved + } + 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 parent.lookupType(for: type, errors: &errors) + } + } + + private func collectConformedJSProtocols(from inheritanceClause: InheritanceClauseSyntax?) -> [String]? { + guard let inheritanceClause else { return nil } + var names: [String] = [] + for inherited in inheritanceClause.inheritedTypes { + if let name = parent.resolveJSProtocolConstraint(for: inherited.type), !names.contains(name) { + names.append(name) + } + } + return names.isEmpty ? nil : names + } + /// Shared parameter parsing logic used by functions, initializers, and protocol methods private func parseParameters( from parameterClause: FunctionParameterClauseSyntax, - allowDefaults: Bool = true + allowDefaults: Bool = true, + genericParameterNames: [String] = [] ) -> [Parameter] { var parameters: [Parameter] = [] for param in parameterClause.parameters { - let resolvedType = withLookupErrors { self.parent.lookupType(for: param.type, errors: &$0) } + let resolvedType = withLookupErrors { + self.lookupTypeWithGenerics( + for: param.type, + genericParameterNames: genericParameterNames, + allowGenericCallback: true, + errors: &$0 + ) + } guard let type = resolvedType else { continue // Skip unsupported types } @@ -1655,14 +1846,26 @@ 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 + var genericParameters: [GenericParameter] = [] + if let genericClause = node.genericParameterClause { + for genericParam in genericClause.parameters { + switch parent.parseGenericParameterConstraints(genericParam, attributeName: "@JS") { + case .failed(let message): + diagnose(node: node, message: message) + return nil + case .parsed(let genericParameter): + genericParameters.append(genericParameter) + } + } + if node.genericWhereClause != nil { + diagnose( + node: node, + message: "'where' clauses are not supported on generic @JS functions." + ) + return nil + } } + let genericParameterNames = genericParameters.map(\.name) let name = node.name.text let jsName = extractValidatedJSName(from: jsAttribute) @@ -1694,10 +1897,20 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { ) } - let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: true) + let parameters = parseParameters( + from: node.signature.parameterClause, + allowDefaults: true, + genericParameterNames: genericParameterNames + ) let returnType: BridgeType if let returnClause = node.signature.returnClause { - let resolvedType = withLookupErrors { self.parent.lookupType(for: returnClause.type, errors: &$0) } + let resolvedType = withLookupErrors { + self.lookupTypeWithGenerics( + for: returnClause.type, + genericParameterNames: genericParameterNames, + errors: &$0 + ) + } if let type = resolvedType, case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: returnClause.type, type: returnClause.type.trimmedDescription) @@ -1710,6 +1923,30 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { returnType = .void } + if !genericParameterNames.isEmpty { + if parameters.contains(where: { $0.defaultValue != nil }) { + diagnose( + node: node, + message: "Default parameter values are not supported on generic @JS functions.", + hint: + "JavaScript callers pass a trailing BridgeType token after the declared parameters, so a defaulted parameter could never be omitted. Remove the default value or provide a non-generic overload." + ) + return nil + } + for genericName in genericParameterNames { + let usedInParameter = parameters.contains { $0.type.referencedGenericNames.contains(genericName) } + let usedInReturn = returnType.referencedGenericName == genericName + if !usedInParameter && !usedInReturn { + diagnose( + node: node, + message: + "The generic parameter '\(genericName)' must be used in at least one parameter or the return type of a generic @JS function." + ) + return nil + } + } + } + let abiName: String let staticContext: StaticContext? @@ -1772,7 +2009,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { effects: effects, namespace: finalNamespace, staticContext: staticContext, - documentation: extractDocumentation(from: node) + documentation: extractDocumentation(from: node), + genericParameters: genericParameters.isEmpty ? nil : genericParameters ) } @@ -1932,6 +2170,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { diagnoseUnsupportedJSName(from: jsAttribute) + if node.genericParameterClause != nil || node.genericWhereClause != nil { + diagnose(node: node, message: "Generic @JS initializers are not supported.") + return .skipChildren + } + switch state { case .classBody(_, let classKey): if extractNamespace(from: jsAttribute) != nil { @@ -2151,7 +2394,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { jsNamespace: namespaceResult.jsNamespace, identityMode: classIdentityMode, documentation: extractDocumentation(from: node), - isFinal: isFinal + isFinal: isFinal, + conformedJSProtocols: collectConformedJSProtocols(from: node.inheritanceClause) ) let uniqueKey = makeKey(name: name, namespace: effectiveNamespace) @@ -2316,7 +2560,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { emitStyle: emitStyle, staticMethods: [], staticProperties: [], - documentation: extractDocumentation(from: node) + documentation: extractDocumentation(from: node), + conformedJSProtocols: collectConformedJSProtocols(from: node.inheritanceClause) ) let enumUniqueKey = makeKey(name: name, namespace: effectiveNamespace) @@ -2569,7 +2814,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { methods: [], namespace: effectiveNamespace, jsNamespace: namespaceResult.jsNamespace, - documentation: extractDocumentation(from: node) + documentation: extractDocumentation(from: node), + conformedJSProtocols: collectConformedJSProtocols(from: node.inheritanceClause) ) exportedStructByName[structUniqueKey] = exportedStruct @@ -2630,6 +2876,16 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { diagnoseUnsupportedJSName(from: jsAttribute) } + if node.genericParameterClause != nil || node.genericWhereClause != nil { + diagnose( + node: node, + message: "Generic requirements are not supported on @JS protocols yet.", + hint: + "Constrain a generic @JS function or method to the protocol instead: ''." + ) + return nil + } + let name = node.name.text let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: false) @@ -2649,6 +2905,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { returnType = .void } + guard + (parameters.map(\.type) + [returnType]).allSatisfy({ + validateProtocolRequirementType($0, node: node) + }) + else { return nil } + let abiName = ABINameGenerator.generateABIName( baseName: name, namespace: namespace, @@ -2697,6 +2959,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { else { continue } + guard validateProtocolRequirementType(propertyType, node: typeAnnotation.type) else { continue } guard let accessorBlock = binding.accessorBlock else { diagnose( @@ -2736,6 +2999,22 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + private func validateProtocolRequirementType(_ type: BridgeType, node: some SyntaxProtocol) -> Bool { + switch type { + case .swiftProtocol: + diagnose(node: node, message: "Protocol-valued requirements are not supported on @JS protocols yet.") + return false + case .nullable(let element, _), .array(let element), .dictionary(let element), .alias(_, let element): + return validateProtocolRequirementType(element, node: node) + case .closure(let signature, _): + return (signature.parameters + [signature.returnType]).allSatisfy { + validateProtocolRequirementType($0, node: node) + } + default: + return true + } + } + private func hasOnlyGetter(_ accessorBlock: AccessorBlockSyntax?) -> Bool { switch accessorBlock?.accessors { case .accessors(let accessors): @@ -3680,7 +3959,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { else { return nil } - let genericParameterNames = genericParameters.map(\.name) let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 40b1c13c3..001650746 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -28,8 +28,12 @@ public struct BridgeJSLink { skeletons.compactMap(\.exported).compactMap(\.identityMode).first ?? "none" } + var hasGenericExports: Bool { + skeletons.contains { $0.exported?.hasGenericDeclarations ?? false } + } + var hasGenerics: Bool { - skeletons.contains { $0.imported?.hasGenericDeclarations ?? false } + hasGenericExports || skeletons.contains { $0.imported?.hasGenericDeclarations ?? false } } /// Whether a class should use identity caching based on its annotation and the config default. @@ -249,6 +253,12 @@ public struct BridgeJSLink { } } + if hasGenericExports { + let tokens = try generateBridgeTypeTokens() + data.topLevelTypeLines.append(contentsOf: tokens.js) + data.topLevelDtsTypeLines.append(contentsOf: tokens.dts) + } + // Process imported skeletons for unified in skeletons { guard let imported = unified.imported else { continue } @@ -341,6 +351,9 @@ public struct BridgeJSLink { ] if hasGenerics { declarations.append("const \(JSGlueVariableScope.reservedCodecByTypeId) = new Map();") + if hasGenericExports { + declarations.append("const \(JSGlueVariableScope.reservedTypeIdByToken) = new Map();") + } declarations.append("let __bjs_typeHandlesRegistered = false;") declarations.append("function __bjs_registerTypeHandles() {") declarations.append(" if (__bjs_typeHandlesRegistered) {") @@ -357,6 +370,10 @@ public struct BridgeJSLink { } declarations.append("}") declarations.append(contentsOf: GenericJSCodegen.runtimeHelperDeclarations()) + if hasGenericExports { + declarations.append(generateTokenConformancesDeclaration()) + declarations.append(contentsOf: GenericJSCodegen.exportRuntimeHelperDeclarations()) + } } declarations.append(contentsOf: [ "", @@ -383,13 +400,14 @@ public struct BridgeJSLink { returnType: .void, intrinsicRegistry: intrinsicRegistry ) - try builder.liftParameter(param: Parameter(label: nil, name: "promise", type: .jsObject(nil))) + var parameters = [Parameter(label: nil, name: "promise", type: .jsObject(nil))] + if valueType != .void { parameters.append(Parameter(label: nil, name: "value", type: valueType)) } + try builder.liftParametersAndGenericTypeIds(parameters, genericParameters: valueType.referencedGenericNames) // `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( @@ -412,13 +430,19 @@ public struct BridgeJSLink { try ContainerCodecJS.codecExpression(for: type, context: makeCodecPrintContext(printer: printer)) } - private func writeTypeHandleRegistrationBody(into printer: CodeFragmentPrinter) { + private func writeTypeHandleRegistrationBody(tokens: [String]?, into printer: CodeFragmentPrinter) { + if let tokens { + printer.write("const tokens = [\(tokens.map { "\"\($0)\"" }.joined(separator: ", "))];") + } 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]);") + if tokens != nil { + printer.write("\(JSGlueVariableScope.reservedTypeIdByToken).set(tokens[i], typeIds[i]);") + } } printer.write("}") } @@ -439,7 +463,10 @@ public struct BridgeJSLink { } } printer.write("];") - writeTypeHandleRegistrationBody(into: printer) + writeTypeHandleRegistrationBody( + tokens: hasGenericExports ? BridgeType.genericBridgeablePrimitives.map(\.token) : nil, + into: printer + ) } printer.write("}") } @@ -465,12 +492,139 @@ public struct BridgeJSLink { } } printer.write("];") - writeTypeHandleRegistrationBody(into: printer) + writeTypeHandleRegistrationBody( + tokens: hasGenericExports ? moduleEntries.map(\.token) : nil, + into: printer + ) } printer.write("}") } } + private func generateTokenConformancesDeclaration() -> String { + var inheritedByProtocol: [String: [String]] = [:] + var tokenBySwiftCallName: [String: String] = [:] + for unified in skeletons { + guard let exported = unified.exported else { continue } + for structDef in exported.structs { tokenBySwiftCallName[structDef.swiftCallName] = structDef.abiName } + for klass in exported.classes { tokenBySwiftCallName[klass.swiftCallName] = klass.abiName } + for enumDef in exported.enums { tokenBySwiftCallName[enumDef.swiftCallName] = enumDef.abiName } + } + var externalByToken: [String: [String]] = [:] + for unified in skeletons { + for protocolDef in unified.exported?.protocols ?? [] { + if let inherited = protocolDef.inheritedJSProtocols, !inherited.isEmpty { + inheritedByProtocol[protocolDef.name] = inherited + } + } + for (swiftCallName, protocols) in unified.exported?.externalJSProtocolConformances ?? [:] { + guard let token = tokenBySwiftCallName[swiftCallName] else { continue } + for protocolName in protocols where !(externalByToken[token] ?? []).contains(protocolName) { + externalByToken[token, default: []].append(protocolName) + } + } + } + func transitiveClosure(of protocols: [String]) -> [String] { + var seen: [String] = [] + var worklist = protocols + while let name = worklist.popLast() { + guard !seen.contains(name) else { continue } + seen.append(name) + worklist.append(contentsOf: inheritedByProtocol[name] ?? []) + } + return seen + } + var entries: [String] = [] + func append(token: String, protocols: [String]?) { + var combined = protocols ?? [] + for protocolName in externalByToken[token] ?? [] where !combined.contains(protocolName) { + combined.append(protocolName) + } + guard !combined.isEmpty else { return } + let list = transitiveClosure(of: combined).map { "\"\($0)\"" }.joined(separator: ", ") + entries.append("\"\(token)\": [\(list)]") + } + for unified in skeletons { + guard let exported = unified.exported else { continue } + for structDef in exported.structs { + append(token: structDef.abiName, protocols: structDef.conformedJSProtocols) + } + for klass in exported.classes where klass.isFinal == true { + append(token: klass.abiName, protocols: klass.conformedJSProtocols) + } + for enumDef in exported.enums where enumDef.genericBridgeType != nil { + append(token: enumDef.abiName, protocols: enumDef.conformedJSProtocols) + } + for proto in exported.protocols where proto.isGenericBridgeable == true { + append(token: proto.abiName, protocols: [proto.name]) + } + } + return "const __bjs_tokenConformances = { \(entries.joined(separator: ", ")) };" + } + + private func bridgeTypeTokenEntries() throws -> [(token: String, tsType: String)] { + var entries: [(token: String, tsType: String)] = BridgeType.genericBridgeablePrimitives.map { + (token: $0.token, tsType: $0.type.tsType) + } + var definingModuleByToken: [String: String] = Dictionary( + uniqueKeysWithValues: BridgeType.genericBridgeablePrimitives.map { ($0.token, "JavaScriptKit") } + ) + var definingModuleBySwiftName: [String: String] = [:] + func claim(_ token: String, module: String) throws { + if let existing = definingModuleByToken[token] { + throw BridgeJSLinkError( + message: + "Generic type token '\(token)' is defined by both '\(existing)' and '\(module)'; type names used with generics must be unique across linked modules" + ) + } + definingModuleByToken[token] = module + } + for unified in skeletons { + guard let exported = unified.exported else { continue } + for entry in exported.genericBridgeableTypeEntries { + try claim(entry.token, module: unified.moduleName) + if let existing = definingModuleBySwiftName[entry.swiftName], existing != unified.moduleName { + throw BridgeJSLinkError( + message: + "Generic type '\(entry.swiftName)' is defined by both '\(existing)' and '\(unified.moduleName)'; distinct JavaScript namespaces do not disambiguate Swift type identities" + ) + } + definingModuleBySwiftName[entry.swiftName] = unified.moduleName + entries.append((token: entry.token, tsType: resolveTypeScriptType(entry.bridgeType))) + } + } + var definingModuleByProtocol: [String: String] = [:] + for unified in skeletons { + for protocolDef in unified.exported?.protocols ?? [] { + if let existing = definingModuleByProtocol[protocolDef.name], existing != unified.moduleName { + throw BridgeJSLinkError( + message: + "@JS protocol '\(protocolDef.name)' is defined by both '\(existing)' and '\(unified.moduleName)'; protocol names used as generic constraints must be unique across linked modules" + ) + } + definingModuleByProtocol[protocolDef.name] = unified.moduleName + } + } + return entries + } + + private func generateBridgeTypeTokens() throws -> (js: [String], dts: [String]) { + let entries = try bridgeTypeTokenEntries() + + let jsEntries = entries.map { "\($0.token): \"\($0.token)\"" } + let jsLines = ["export const BridgeTypes = { \(jsEntries.joined(separator: ", ")) };"] + + var dtsLines: [String] = [] + dtsLines.append("declare const bridgeTypeBrand: unique symbol;") + dtsLines.append( + "export type BridgeType = string & { readonly [bridgeTypeBrand]: (value: T) => T };" + ) + let dtsEntries = entries.map { "readonly \($0.token): BridgeType<\($0.tsType)>;" } + dtsLines.append("export const BridgeTypes: { \(dtsEntries.joined(separator: " ")) };") + + return (js: jsLines, dts: dtsLines) + } + private func generateAddImports(needsImportsObject: Bool) throws -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() let allStructs = skeletons.flatMap { unified in @@ -916,6 +1070,7 @@ public struct BridgeJSLink { } printer.write("}") + var asyncGenericResults = Set() for signature in closureSignatures.sorted(by: { $0.mangleName < $1.mangleName }) { let invokeFuncName = "invoke_js_callback_\(moduleName)_\(signature.mangleName)" let invokeLines = try generateInvokeFunction( @@ -924,6 +1079,27 @@ public struct BridgeJSLink { ) printer.write(lines: invokeLines) + let returnType = signature.returnType + if signature.isAsync, returnType.usesGenericParameter, + asyncGenericResults.insert(returnType).inserted + { + let builder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: returnType, + intrinsicRegistry: intrinsicRegistry + ) + try builder.liftParametersAndGenericTypeIds( + [Parameter(label: nil, name: "value", type: .jsValue)], + genericParameters: returnType.referencedGenericNames + ) + try builder.call(calleeExpr: "(value => value)") + var lines = builder.renderFunction(name: nil) + lines[0] = + "bjs[\"async_callback_result_\(moduleName)_\(returnType.mangleTypeName)\"] = " + + lines[0] + printer.write(lines: lines) + } + if !signature.genericParameterNames.isEmpty { continue } let lowerFuncName = "lower_closure_\(moduleName)_\(signature.mangleName)" let makeFuncName = "make_swift_closure_\(moduleName)_\(signature.mangleName)" printer.write("bjs[\"\(makeFuncName)\"] = function(boxPtr, file, line) {") @@ -959,10 +1135,12 @@ public struct BridgeJSLink { thunkBuilder.parameterNames.append("callbackId") thunkBuilder.body.write("const callback = \(JSGlueVariableScope.reservedSwift).memory.getObject(callbackId);") - for (index, paramType) in signature.parameters.enumerated() { - let paramName = "param\(index)" - try thunkBuilder.liftParameter(param: Parameter(label: nil, name: paramName, type: paramType)) - } + try thunkBuilder.liftParametersAndGenericTypeIds( + signature.parameters.enumerated().map { + Parameter(label: nil, name: "param\($0.offset)", type: $0.element) + }, + genericParameters: signature.genericParameterNames + ) try thunkBuilder.call(calleeExpr: "callback") @@ -1075,9 +1253,7 @@ public struct BridgeJSLink { parameters: function.parameters ) ) - printer.write( - "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - ) + printer.write("\(renderExportMemberTSSignature(function: function));") } for property in enumDefinition.staticProperties { let readonly = property.isReadonly ? "readonly " : "" @@ -1129,9 +1305,7 @@ public struct BridgeJSLink { }, renderFunctionEntry: { function in return self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) - + [ - "\(function.resolvedJSName)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - ] + + ["\(self.renderExportMemberTSSignature(function: function));"] }, renderPropertyEntry: { property in let readonly = property.isReadonly ? "readonly " : "" @@ -1560,10 +1734,14 @@ public struct BridgeJSLink { class ExportedThunkBuilder { var body: CodeFragmentPrinter + let returnBody = CodeFragmentPrinter() var parameterForwardings: [String] = [] let effects: Effects let scope: JSGlueVariableScope let context: IntrinsicJSFragment.PrintCodeContext + var genericCodecVariables: [String: String] = [:] + var genericTypeIdVariables: [String: String] = [:] + var genericTokenParameterNames: [String] = [] init(effects: Effects, hasDirectAccessToSwiftClass: Bool = true, intrinsicRegistry: JSIntrinsicRegistry) { self.effects = effects @@ -1594,6 +1772,80 @@ public struct BridgeJSLink { parameterForwardings.append(contentsOf: loweredValues) } + func lowerParametersAndGenericTokens( + parameters: [Parameter], + genericParameters: [GenericParameter], + selfType: BridgeType? = nil + ) throws { + guard !genericParameters.isEmpty else { + for param in parameters { + try lowerParameter(param: param) + } + return + } + genericTokenParameterNames = GenericJSCodegen.genericTokenParameterNames( + parameters: parameters, + genericNames: genericParameters.map(\.name), + scope: scope + ) + for (genericParam, tokenName) in zip(genericParameters, genericTokenParameterNames) { + let typeIdVariable = scope.variable("typeId\(genericParam.name)") + let codecVariable = scope.variable("codec\(genericParam.name)") + body.write( + "const \(typeIdVariable) = __bjs_typeIdForToken(\(tokenName)\(Self.requiredProtocolsArgument(genericParam)));" + ) + body.write("const \(codecVariable) = __bjs_codecForTypeId(\(typeIdVariable));") + genericTypeIdVariables[genericParam.name] = typeIdVariable + genericCodecVariables[genericParam.name] = codecVariable + } + if let selfType { + let fragment = try IntrinsicJSFragment.lowerParameter(type: selfType) + parameterForwardings.append(contentsOf: try fragment.printCode(["this"], context)) + } + for param in parameters { + if let genericName = param.type.referencedGenericName { + guard let codecVariable = genericCodecVariables[genericName], + let lowerStatement = GenericJSCodegen.genericCodecLowerStatement( + type: param.type, + codec: codecVariable, + value: param.name + ) + else { + throw BridgeJSLinkError( + message: + "Generic codec for '\(genericName)' was not declared before lowering parameter '\(param.name)'" + ) + } + body.write(lowerStatement) + } else { + let loweringFragment = try IntrinsicJSFragment.lowerParameter(type: param.type) + let loweredValues = try loweringFragment.printCode([param.name], context) + parameterForwardings.append(contentsOf: loweredValues) + } + } + for genericParam in genericParameters { + if let typeIdVariable = genericTypeIdVariables[genericParam.name] { + parameterForwardings.append(typeIdVariable) + } + } + } + + static func requiredProtocolsArgument(_ genericParameter: GenericParameter) -> String { + guard !genericParameter.constraints.isEmpty else { return "" } + let list = genericParameter.constraints.map { "\"\($0)\"" }.joined(separator: ", ") + return ", [\(list)]" + } + + func parameterList(_ parameters: [Parameter]) -> String { + let base = DefaultValueUtils.formatParameterList( + parameters, + resolveTypeName: context.defaultValueTypeName + ) + guard !genericTokenParameterNames.isEmpty else { return base } + let tokens = genericTokenParameterNames.joined(separator: ", ") + return base.isEmpty ? tokens : "\(base), \(tokens)" + } + func lowerSelf() { parameterForwardings.append("this.pointer") } @@ -1608,6 +1860,20 @@ public struct BridgeJSLink { private func _call(abiName: String, returnType: BridgeType) throws -> String? { let call = "instance.exports.\(abiName)(\(parameterForwardings.joined(separator: ", ")))" + if let genericName = returnType.referencedGenericName { + guard let codecVariable = genericCodecVariables[genericName], + let liftExpression = GenericJSCodegen.genericCodecLiftExpression( + type: returnType, + codec: codecVariable + ) + else { + throw BridgeJSLinkError( + message: "Generic codec for return type '\(genericName)' was not declared before the call" + ) + } + body.write("\(call);") + return liftExpression + } let liftingFragment = try IntrinsicJSFragment.liftReturn(type: returnType) assert( liftingFragment.parameters.count <= 1, @@ -1622,7 +1888,7 @@ public struct BridgeJSLink { body.write("const \(returnVariable) = \(call);") fragmentArguments = [returnVariable] } - let liftedValues = try liftingFragment.printCode(fragmentArguments, context) + let liftedValues = try liftingFragment.printCode(fragmentArguments, context.with(\.printer, returnBody)) assert(liftedValues.count <= 1, "Lifting fragment should produce at most one value") return liftedValues.first } @@ -1654,6 +1920,7 @@ public struct BridgeJSLink { func renderFunctionBody(into printer: CodeFragmentPrinter, returnExpr: String?) { printer.write(contentsOf: body) printer.write(lines: checkExceptionLines()) + printer.write(contentsOf: returnBody) if let returnExpr = returnExpr { printer.write("return \(returnExpr);") } @@ -1667,10 +1934,7 @@ public struct BridgeJSLink { ) -> [String] { let printer = CodeFragmentPrinter() - let parameterList = DefaultValueUtils.formatParameterList( - parameters, - resolveTypeName: context.defaultValueTypeName - ) + let parameterList = self.parameterList(parameters) printer.write( "\(declarationPrefixKeyword.map { "\($0) "} ?? "")\(name)(\(parameterList)) {" @@ -1797,6 +2061,30 @@ public struct BridgeJSLink { return "<\(renderedParameters.joined(separator: ", "))>" } + private func renderExportMemberTSSignature(function: ExportedFunction) -> String { + guard function.isGeneric else { + return + "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects))" + } + let genericNames = function.genericParameterNames + let tokenNames = GenericJSCodegen.genericTokenParameterNames( + parameters: function.parameters, + genericNames: genericNames, + scope: JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) + ) + var parameterSignatures = function.parameters.map { param in + "\(param.name): \(resolveTypeScriptType(param.type))" + } + for (genericName, tokenName) in zip(genericNames, tokenNames) { + parameterSignatures.append("\(tokenName): BridgeType<\(genericName)>") + } + let genericClause = renderGenericClause(function.genericParameters ?? []) + let returnType = resolveTypeScriptType(function.returnType) + let returnSignature = function.effects.isAsync ? "Promise<\(returnType)>" : returnType + return + "\(function.resolvedJSName)\(genericClause)(\(parameterSignatures.joined(separator: ", "))): \(returnSignature)" + } + 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 { @@ -1833,12 +2121,7 @@ public struct BridgeJSLink { parameters: method.parameters ) dtsTypePrinter.write(lines: jsDocLines) - let signature = renderTSSignature( - parameters: method.parameters, - returnType: method.returnType, - effects: method.effects - ) - dtsTypePrinter.write("\(method.resolvedJSName)\(signature);") + dtsTypePrinter.write("\(renderExportMemberTSSignature(function: method));") } } dtsTypePrinter.write("}") @@ -1866,9 +2149,7 @@ public struct BridgeJSLink { 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.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) + dtsExportEntryPrinter.write("\(renderExportMemberTSSignature(function: method));") } return dtsExportEntryPrinter.lines @@ -1893,10 +2174,7 @@ public struct BridgeJSLink { ) let constructorPrinter = CodeFragmentPrinter() - let paramList = DefaultValueUtils.formatParameterList( - constructor.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) + let paramList = thunkBuilder.parameterList(constructor.parameters) constructorPrinter.write("init: function(\(paramList)) {") constructorPrinter.indent { thunkBuilder.renderFunctionBody(into: constructorPrinter, returnExpr: returnExpr) @@ -2115,9 +2393,10 @@ extension BridgeJSLink { effects: function.effects, intrinsicRegistry: intrinsicRegistry ) - for param in function.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: function.parameters, + genericParameters: function.genericParameters ?? [] + ) let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let funcLines = thunkBuilder.renderFunction( name: function.abiName, @@ -2129,9 +2408,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) - dtsLines.append( - "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - ) + dtsLines.append("\(renderExportMemberTSSignature(function: function));") return (funcLines, dtsLines) } @@ -2165,9 +2442,10 @@ extension BridgeJSLink { effects: function.effects, intrinsicRegistry: intrinsicRegistry ) - for param in function.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: function.parameters, + genericParameters: function.genericParameters ?? [] + ) let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let funcLines = thunkBuilder.renderFunction( @@ -2181,9 +2459,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) - dtsLines.append( - "static \(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - ) + dtsLines.append("static \(renderExportMemberTSSignature(function: function));") return (funcLines, dtsLines) } @@ -2196,17 +2472,14 @@ extension BridgeJSLink { effects: function.effects, intrinsicRegistry: intrinsicRegistry ) - for param in function.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: function.parameters, + genericParameters: function.genericParameters ?? [] + ) 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(function.parameters))) {") printer.indent { thunkBuilder.renderFunctionBody(into: printer, returnExpr: returnExpr) } @@ -2216,9 +2489,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) - dtsLines.append( - "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" - ) + dtsLines.append("\(renderExportMemberTSSignature(function: function));") return (printer.lines, dtsLines) } @@ -2231,9 +2502,10 @@ extension BridgeJSLink { effects: function.effects, intrinsicRegistry: intrinsicRegistry ) - for param in function.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: function.parameters, + genericParameters: function.genericParameters ?? [] + ) let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let funcLines = thunkBuilder.renderFunction( @@ -2256,18 +2528,15 @@ extension BridgeJSLink { effects: method.effects, intrinsicRegistry: intrinsicRegistry ) - for param in method.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: method.parameters, + genericParameters: method.genericParameters ?? [] + ) 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(method.parameters))) {" ) methodPrinter.indent { thunkBuilder.renderFunctionBody(into: methodPrinter, returnExpr: returnExpr) @@ -2371,10 +2640,7 @@ extension BridgeJSLink { try thunkBuilder.lowerParameter(param: param) } - let constructorParamList = DefaultValueUtils.formatParameterList( - constructor.parameters, - resolveTypeName: thunkBuilder.context.defaultValueTypeName - ) + let constructorParamList = thunkBuilder.parameterList(constructor.parameters) jsPrinter.indent { jsPrinter.write("constructor(\(constructorParamList)) {") @@ -2396,9 +2662,10 @@ extension BridgeJSLink { effects: method.effects, intrinsicRegistry: intrinsicRegistry ) - for param in method.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: method.parameters, + genericParameters: method.genericParameters ?? [] + ) let returnExpr = try thunkBuilder.call(abiName: method.abiName, returnType: method.returnType) jsPrinter.indent { @@ -2417,9 +2684,10 @@ extension BridgeJSLink { intrinsicRegistry: intrinsicRegistry ) thunkBuilder.lowerSelf() - for param in method.parameters { - try thunkBuilder.lowerParameter(param: param) - } + try thunkBuilder.lowerParametersAndGenericTokens( + parameters: method.parameters, + genericParameters: method.genericParameters ?? [] + ) let returnExpr = try thunkBuilder.call(abiName: method.abiName, returnType: method.returnType) jsPrinter.indent { @@ -2440,9 +2708,7 @@ extension BridgeJSLink { ) { dtsTypePrinter.write(line) } - dtsTypePrinter.write( - "\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) + dtsTypePrinter.write("\(renderExportMemberTSSignature(function: method));") } } } @@ -2478,9 +2744,7 @@ extension BridgeJSLink { } for method in klass.methods where method.effects.isStatic { printer.write(lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters)) - printer.write( - "\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) + printer.write("\(renderExportMemberTSSignature(function: method));") } for property in klass.properties where property.isStatic { let readonly = property.isReadonly ? "readonly " : "" @@ -2510,9 +2774,7 @@ extension BridgeJSLink { 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.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) + printer.write("\(staticKeyword)\(renderExportMemberTSSignature(function: method));") } for property in klass.properties.sorted(by: { $0.resolvedJSName < $1.resolvedJSName }) { let staticKeyword = property.isStatic ? "static " : "" @@ -2761,7 +3023,11 @@ extension BridgeJSLink { private func call(callExpr: String) throws { if effects.isAsync { - body.write("\(callExpr).then(resolve, reject);") + if genericCodecVariables.isEmpty { + body.write("\(callExpr).then(resolve, reject);") + } else { + body.write("Promise.resolve().then(() => \(callExpr)).then(resolve, reject);") + } return } if let name = returnType.referencedGenericName { @@ -3332,11 +3598,7 @@ extension BridgeJSLink { let getterPrinter = CodeFragmentPrinter() 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);") - } + getterThunkBuilder.renderFunctionBody(into: getterPrinter, returnExpr: getterReturnExpr) } getterPrinter.write("},") @@ -3359,8 +3621,7 @@ extension BridgeJSLink { let setterPrinter = CodeFragmentPrinter() setterPrinter.write("set \(property.resolvedJSName)(value) {") setterPrinter.indent { - setterPrinter.write(contentsOf: setterThunkBuilder.body) - setterPrinter.write(lines: setterThunkBuilder.checkExceptionLines()) + setterThunkBuilder.renderFunctionBody(into: setterPrinter, returnExpr: nil) } setterPrinter.write("},") @@ -3774,10 +4035,9 @@ extension BridgeJSLink { returnType: function.returnType, intrinsicRegistry: intrinsicRegistry ) - let genericParameters = function.genericParameterNames try thunkBuilder.liftParametersAndGenericTypeIds( function.parameters, - genericParameters: genericParameters + genericParameters: function.genericParameterNames ) let jsName = function.resolvedJSName let calleeExpr = try importedModuleRegistry.memberExpression( @@ -4001,10 +4261,9 @@ extension BridgeJSLink { intrinsicRegistry: intrinsicRegistry ) thunkBuilder.liftSelf() - let genericParameters = method.genericParameterNames try thunkBuilder.liftParametersAndGenericTypeIds( method.parameters, - genericParameters: genericParameters + genericParameters: method.genericParameterNames ) try thunkBuilder.callMethod(name: method.resolvedJSName) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 747c9f532..08c102f69 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -36,6 +36,7 @@ final class JSGlueVariableScope { static let reservedMakeSwiftClosure = "makeClosure" static let reservedTaStack = "taStack" static let reservedCodecByTypeId = "__bjs_codecByTypeId" + static let reservedTypeIdByToken = "__bjs_typeIdByToken" static let reservedPrimitiveCodecs = "__bjs_primitiveCodecs" static let reservedStringCodec = "__bjs_stringCodec" static let reservedTypeHandlesRegistered = "__bjs_typeHandlesRegistered" @@ -71,6 +72,7 @@ final class JSGlueVariableScope { reservedMakeSwiftClosure, reservedTaStack, reservedCodecByTypeId, + reservedTypeIdByToken, reservedPrimitiveCodecs, reservedStringCodec, reservedTypeHandlesRegistered, @@ -226,6 +228,39 @@ enum GenericJSCodegen { genericCodecExpression(type: type, codec: codec).map { "\($0).lift()" } } + static func genericTokenParameterNames( + parameters: [Parameter], + genericNames: [String], + scope: JSGlueVariableScope + ) -> [String] { + for parameter in parameters { + _ = scope.variable(parameter.name) + } + return genericNames.map { scope.variable("type\($0)") } + } + + static func exportRuntimeHelperDeclarations() -> [String] { + let typeIdByToken = JSGlueVariableScope.reservedTypeIdByToken + return [ + "function __bjs_typeIdForToken(token, requiredProtocols) {", + " \(JSGlueVariableScope.reservedRegisterTypeHandles)();", + " const typeId = \(typeIdByToken).get(token);", + " if (typeId === undefined) {", + " throw new TypeError(\"BridgeJS: unknown BridgeType token '\" + token + \"'\");", + " }", + " if (requiredProtocols) {", + " const conformances = __bjs_tokenConformances[token] || [];", + " for (const requiredProtocol of requiredProtocols) {", + " if (!conformances.includes(requiredProtocol)) {", + " throw new TypeError(\"BridgeJS: type '\" + token + \"' does not conform to required protocol '\" + requiredProtocol + \"'\");", + " }", + " }", + " }", + " return typeId;", + "}", + ] + } + static func runtimeHelperDeclarations() -> [String] { let codecByTypeId = JSGlueVariableScope.reservedCodecByTypeId return [ @@ -2581,6 +2616,15 @@ struct IntrinsicJSFragment: Sendable { // Attach instance methods to the struct instance for method in structDef.methods where !method.effects.isStatic { + if method.isGeneric { + try attachGenericStructInstanceMethod( + method: method, + structDef: structDef, + instanceVar: instanceVar, + context: context + ) + continue + } let paramList = DefaultValueUtils.formatParameterList( method.parameters, resolveTypeName: context.defaultValueTypeName @@ -2611,6 +2655,28 @@ struct IntrinsicJSFragment: Sendable { } } + private static func attachGenericStructInstanceMethod( + method: ExportedFunction, + structDef: ExportedStruct, + instanceVar: String, + context: IntrinsicJSFragment.PrintCodeContext + ) throws { + let printer = context.printer + let builder = BridgeJSLink.ExportedThunkBuilder(effects: method.effects, context: context) + try builder.lowerParametersAndGenericTokens( + parameters: method.parameters, + genericParameters: method.genericParameters ?? [], + selfType: .swiftStruct(structDef.swiftCallName) + ) + let returnExpr = try builder.call(abiName: method.abiName, returnType: method.returnType) + let paramList = builder.parameterList(method.parameters) + printer.write("\(instanceVar).\(method.resolvedJSName) = function(\(paramList)) {") + printer.indent { + builder.renderFunctionBody(into: printer, returnExpr: returnExpr) + } + printer.write("}.bind(\(instanceVar));") + } + private static func structFieldLowerFragment( type: BridgeType, fieldName: String, diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 8da9f2e4e..57402dca7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -161,6 +161,12 @@ public struct ClosureSignature: Codable, Equatable, Hashable, Sendable { /// transferred through a continuation. public let sendingParameters: Bool + public var genericParameterNames: [String] { + (parameters + [returnType]).compactMap(\.referencedGenericName).reduce(into: []) { names, name in + if !names.contains(name) { names.append(name) } + } + } + public init( parameters: [BridgeType], returnType: BridgeType, @@ -312,6 +318,13 @@ extension BridgeType { } } + public var usesGenericParameter: Bool { referencedGenericName != nil } + + public var referencedGenericNames: [String] { + if case .closure(let signature, _) = self { return signature.genericParameterNames } + return referencedGenericName.map { [$0] } ?? [] + } + public static let genericBridgeablePrimitives: [(token: String, type: BridgeType)] = [ ("Bool", .bool), ("Int", .integer(.int)), @@ -335,10 +348,12 @@ extension BridgeType { public struct GenericBridgeableTypeEntry: Sendable { public let swiftName: String public let bridgeType: BridgeType + public let token: String - public init(swiftName: String, bridgeType: BridgeType) { + public init(swiftName: String, bridgeType: BridgeType, token: String) { self.swiftName = swiftName self.bridgeType = bridgeType + self.token = token } } @@ -366,7 +381,8 @@ extension ExportedSkeleton { entries.append( GenericBridgeableTypeEntry( swiftName: structDef.swiftCallName, - bridgeType: .swiftStruct(structDef.swiftCallName) + bridgeType: .swiftStruct(structDef.swiftCallName), + token: structDef.abiName ) ) } @@ -374,24 +390,39 @@ extension ExportedSkeleton { entries.append( GenericBridgeableTypeEntry( swiftName: klass.swiftCallName, - bridgeType: .swiftHeapObject(klass.swiftCallName) + bridgeType: .swiftHeapObject(klass.swiftCallName), + token: klass.abiName ) ) } for enumDef in enums { guard let bridgeType = enumDef.genericBridgeType else { continue } - entries.append(GenericBridgeableTypeEntry(swiftName: enumDef.swiftCallName, bridgeType: bridgeType)) + entries.append( + GenericBridgeableTypeEntry( + swiftName: enumDef.swiftCallName, + bridgeType: bridgeType, + token: enumDef.abiName + ) + ) } for proto in protocols where proto.isGenericBridgeable == true { entries.append( GenericBridgeableTypeEntry( swiftName: "Any\(proto.name)", - bridgeType: .swiftProtocol(proto.name) + bridgeType: .swiftProtocol(proto.name), + token: proto.abiName ) ) } return entries } + + public var hasGenericDeclarations: Bool { + functions.contains(where: \.isGeneric) + || classes.contains { $0.methods.contains(where: \.isGeneric) } + || structs.contains { $0.methods.contains(where: \.isGeneric) } + || enums.contains { $0.staticMethods.contains(where: \.isGeneric) } + } } extension BridgeJSSkeleton { @@ -840,6 +871,7 @@ public struct ExportedStruct: Codable, Equatable, Sendable, NamespacedExportedTy public let namespace: [String]? public let jsNamespace: [String]? public var documentation: String? + public var conformedJSProtocols: [String]? public init( name: String, @@ -851,7 +883,8 @@ public struct ExportedStruct: Codable, Equatable, Sendable, NamespacedExportedTy methods: [ExportedFunction] = [], namespace: [String]?, jsNamespace: [String]? = nil, - documentation: String? = nil + documentation: String? = nil, + conformedJSProtocols: [String]? = nil ) { self.name = name self.jsName = jsName @@ -863,6 +896,7 @@ public struct ExportedStruct: Codable, Equatable, Sendable, NamespacedExportedTy self.namespace = namespace self.jsNamespace = jsNamespace self.documentation = documentation + self.conformedJSProtocols = conformedJSProtocols } } @@ -935,6 +969,7 @@ public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType public var staticMethods: [ExportedFunction] public var staticProperties: [ExportedProperty] = [] public var documentation: String? + public var conformedJSProtocols: [String]? public var enumType: EnumType { if cases.isEmpty { return .namespace @@ -965,7 +1000,8 @@ public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType emitStyle: EnumEmitStyle, staticMethods: [ExportedFunction] = [], staticProperties: [ExportedProperty] = [], - documentation: String? = nil + documentation: String? = nil, + conformedJSProtocols: [String]? = nil ) { self.name = name self.jsName = jsName @@ -980,6 +1016,7 @@ public struct ExportedEnum: Codable, Equatable, Sendable, NamespacedExportedType self.staticMethods = staticMethods self.staticProperties = staticProperties self.documentation = documentation + self.conformedJSProtocols = conformedJSProtocols } } @@ -1055,6 +1092,9 @@ public struct ExportedFunction: Codable, Equatable, Sendable { public var namespace: [String]? public var staticContext: StaticContext? public var documentation: String? + public var genericParameters: [GenericParameter]? + public var genericParameterNames: [String] { (genericParameters ?? []).map(\.name) } + public var isGeneric: Bool { !genericParameterNames.isEmpty } public var resolvedJSName: String { jsName ?? name } @@ -1067,7 +1107,8 @@ public struct ExportedFunction: Codable, Equatable, Sendable { effects: Effects, namespace: [String]? = nil, staticContext: StaticContext? = nil, - documentation: String? = nil + documentation: String? = nil, + genericParameters: [GenericParameter]? = nil ) { self.name = name self.jsName = jsName @@ -1078,6 +1119,7 @@ public struct ExportedFunction: Codable, Equatable, Sendable { self.namespace = namespace self.staticContext = staticContext self.documentation = documentation + self.genericParameters = genericParameters } } @@ -1094,6 +1136,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { public var identityMode: Bool? // nil = use config default, true/false = override public var documentation: String? public var isFinal: Bool? + public var conformedJSProtocols: [String]? public init( name: String, @@ -1107,7 +1150,8 @@ public struct ExportedClass: Codable, NamespacedExportedType { jsNamespace: [String]? = nil, identityMode: Bool? = nil, documentation: String? = nil, - isFinal: Bool? = nil + isFinal: Bool? = nil, + conformedJSProtocols: [String]? = nil ) { self.name = name self.jsName = jsName @@ -1121,6 +1165,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { self.identityMode = identityMode self.documentation = documentation self.isFinal = isFinal + self.conformedJSProtocols = conformedJSProtocols } } @@ -1243,6 +1288,8 @@ public struct ExportedSkeleton: Codable { /// When `"none"` or `nil`, no identity tracking is performed. public var identityMode: String? + public var externalJSProtocolConformances: [String: [String]]? + public init( functions: [ExportedFunction], classes: [ExportedClass], @@ -1840,7 +1887,7 @@ public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { if signature.isAsync { recordInjectedSignatures( - forReturnType: signature.returnType, + forReturnType: signature.returnType.usesGenericParameter ? .jsValue : signature.returnType, accessLevel: accessLevel ) } From 69eec9018d464d10b13ceb6f8783f54faed5ce48 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 22 Sep 2026 16:20:29 +0200 Subject: [PATCH 2/3] BridgeJS: Test generic exports and regenerate bindings --- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 78 + .../BridgeJSToolTests/DiagnosticsTests.swift | 3 +- .../GenericExportDiagnosticsTests.swift | 197 +- .../Inputs/MacroSwift/GenericExports.swift | 105 + .../BridgeJSCodegenTests/GenericExports.json | 867 +++++ .../BridgeJSCodegenTests/GenericExports.swift | 962 +++++ .../__Snapshots__/BridgeJSLinkTests/Async.js | 8 +- .../GenericExports.callsites.check.ts | 31 + .../BridgeJSLinkTests/GenericExports.d.ts | 75 + .../BridgeJSLinkTests/GenericExports.js | 1111 ++++++ .../ImportedTypeInExportedInterface.js | 4 +- .../BridgeJSLinkTests/ProtocolInClosure.js | 16 +- .../BridgeJSLinkTests/SwiftClosure.js | 64 +- .../BridgeJSLinkTests/SwiftClosureImports.js | 4 +- .../BridgeJSLinkTests/tsconfig.json | 5 +- .../ExportGenericAPIs.swift | 226 ++ .../Generated/BridgeJS.swift | 1521 +++++++- .../Generated/JavaScript/BridgeJS.json | 3340 ++++++++++++----- .../JavaScript/ExportGenericTests.mjs | 186 + Tests/prelude.mjs | 11 + 20 files changed, 7720 insertions(+), 1094 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericExports.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.callsites.check.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.js create mode 100644 Tests/BridgeJSRuntimeTests/ExportGenericAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/ExportGenericTests.mjs diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index f96ec2d8d..0a07ff8b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -157,6 +157,84 @@ import Testing return try bridgeJSLink.link().0 } + @Test + func genericRuntimeIsGatedToGenericBuilds() throws { + let genericJS = try linkedJS(forFixture: "GenericImports.swift") + #expect(genericJS.contains("__bjs_codecByTypeId")) + #expect(genericJS.contains("function __bjs_codecForTypeId(typeId) {")) + #expect(genericJS.contains("bjs[\"bjs_TestModule_register_type_handles\"] = function(base, count) {")) + #expect(genericJS.contains("instance.exports[\"bjs_TestModule_register_type_handles\"]();")) + + let nonGenericJS = try linkedJS(forFixture: "SwiftStructImports.swift") + #expect(!nonGenericJS.contains("__bjs_codecByTypeId")) + #expect(!nonGenericJS.contains("__bjs_codecForTypeId")) + #expect(nonGenericJS.contains("bjs[\"bjs_core_register_type_handles\"] = function() {};")) + #expect(nonGenericJS.contains("bjs[\"bjs_TestModule_register_type_handles\"] = function() {};")) + #expect(!nonGenericJS.contains("instance.exports[\"bjs_TestModule_register_type_handles\"]();")) + } + + @Test(arguments: [ + "@JS func identity(_ value: T) -> T { value }", + "@JS class Box { @JS func identity(_ value: T) -> T { value } }", + ]) + func genericExportsEnableCoreTypeRegistration(source: String) throws { + let js = try BridgeJSLink(skeletons: [makeSkeleton(source)]).link().outputJs + #expect(js.contains("__bjs_typeIdByToken.set(tokens[i], typeIds[i]);")) + #expect(js.contains("instance.exports[\"bjs_core_register_type_handles\"]();")) + } + + @Test + func sameTypeNameAcrossModulesLinksWithHandleIdentity() throws { + let structSource = """ + @JS public struct Point { + public var x: Int + @JS public init(x: Int) { self.x = x } + } + """ + let first = try makeSkeleton( + structSource + """ + + @JSFunction func identity(_ value: T) throws(JSException) -> T + """, + moduleName: "FirstModule" + ) + let second = try makeSkeleton(structSource, moduleName: "SecondModule") + let bridgeJSLink = BridgeJSLink(skeletons: [first, second]) + let js = try bridgeJSLink.link().outputJs + #expect(js.contains("bjs[\"bjs_FirstModule_register_type_handles\"] = function(base, count) {")) + #expect(js.contains("bjs[\"bjs_SecondModule_register_type_handles\"] = function(base, count) {")) + } + + @Test(arguments: [false, true]) + func sameTypeNameAcrossModulesFailsWithGenericExports(distinctNamespaces: Bool) throws { + let structSource = """ + @JS public struct Point { + public var x: Int + @JS public init(x: Int) { self.x = x } + } + """ + let first = try makeSkeleton( + structSource + """ + + @JS public func identity(_ value: T) -> T { value } + """, + moduleName: "FirstModule" + ) + let second = try makeSkeleton( + distinctNamespaces + ? structSource.replacingOccurrences( + of: "@JS public struct", + with: "@JS(namespace: \"Other\") public struct" + ) + : structSource, + moduleName: "SecondModule" + ) + let bridgeJSLink = BridgeJSLink(skeletons: [first, second]) + #expect(throws: BridgeJSLinkError.self) { + _ = try bridgeJSLink.link() + } + } + @Test func perClassIdentityModeFromAnnotation() throws { let url = Self.inputsDirectory.appendingPathComponent("IdentityModeClass.swift") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 580360bb7..bcd95e150 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -792,7 +792,8 @@ import Testing struct MyImpl: P { func ok() -> Int { 42 } } \(declaration) """, - contains: "'MyImpl' conforms to 'P'" + contains: declaration.hasPrefix("@JS protocol") + ? "Protocol-valued requirements" : "'MyImpl' conforms to 'P'" ) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift index 37f2a0318..e225aaa89 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift @@ -1,63 +1,186 @@ +import Foundation import Testing +@testable import BridgeJSCore +@testable import BridgeJSLink +@testable import BridgeJSSkeleton + @Suite struct GenericExportDiagnosticsTests { - @Test - func genericExportedFunctionRejected() { + @Test(arguments: [ + ( + "@JS public func identity(_ value: T) -> T { value }", + "Generic parameter 'T' must be constrained to 'BridgedSwiftGenericBridgeable'" + ), + ( + "@JS public func tag(_ value: T, label: Int = 5) -> T { value }", + "Default parameter values are not supported on generic @JS functions." + ), + ( + """ + @JS protocol GraphNode { var id: String { get } } + @JS public func store(_ node: T) -> T { node } + """, + "Generic parameter 'T' is missing the 'BridgedSwiftGenericBridgeable' constraint. " + + "Write 'T: BridgedSwiftGenericBridgeable & GraphNode'" + ), + ( + "@JS public func store(_ node: T) -> T { node }", + "Generic parameter 'T' has unsupported constraint 'Nonexistent'" + ), + ( + "@JS public func identity(_ value: T) -> T where T: Sendable { value }", + "'where' clauses are not supported" + ), + ( + "@JS public func f(_ v: [[T]]) {}", + "may only be used as a bare type" + ), + ( + "@JS public func f(_ v: T) -> [[T]] { [[v]] }", + "may only be used as a bare type" + ), + ( + "@JS public func combine(_ a: T) -> T { a }", + "must be used in at least one parameter or the return type" + ), + ( + """ + @JS enum E { + case a + @JS func f(_ v: T) -> T { v } + } + """, + "Only static functions are supported in enums" + ), + ]) + func unsupportedGenericExport(source: String, message: String) { + expectDiagnostic(source: source, contains: message) + } + + @Test(arguments: [ + ("func map(_ value: T) -> T", "Generic requirements"), + ("func link(_ other: any Node) -> any Node", "Protocol-valued requirements"), + ("var parent: Optional { get }", "Protocol-valued requirements"), + ]) + func unsupportedProtocolRequirement(requirement: String, message: String) { expectDiagnostic( source: """ - @JS public func identity(_ value: T) -> T { value } + @JS protocol Node: BridgedSwiftGenericBridgeable { \(requirement) } """, - contains: "Generic parameters on exported @JS functions are not supported yet" + contains: message ) } - @Test - func genericMethodOnExportedClassRejected() { + @Test(arguments: ["class", "struct"]) + func unsupportedGenericInitializer(kind: String) { 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" + source: "@JS \(kind) Box { @JS init(_ value: T) {} }", + contains: "Generic @JS initializers are not supported." ) } @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" + func sameNamedJSProtocolsAcrossModulesFailTheLink() throws { + let moduleA = try makeSkeleton( + """ + @JS protocol GraphNode { var id: String { get } } + @JS public struct Building: GraphNode { + public var id: String + @JS public init(id: String) { self.id = id } + } + """, + moduleName: "ModuleA" ) + let moduleB = try makeSkeleton( + """ + @JS protocol GraphNode { var label: String { get } } + @JS public func store(_ n: T) -> T { n } + """, + moduleName: "ModuleB" + ) + var link = BridgeJSLink() + let encoder = JSONEncoder() + try link.addSkeletonFile(data: encoder.encode(moduleA)) + try link.addSkeletonFile(data: encoder.encode(moduleB)) + #expect(throws: BridgeJSLinkError.self) { + _ = try link.link() + } } @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" + func crossModuleExtensionConformanceReachesTokenConformances() throws { + let moduleA = try makeSkeleton( + """ + @JS public struct Building { + public var id: String + @JS public init(id: String) { self.id = id } + } + @JS(namespace: "Models") public struct Site { + public var id: String + @JS public init(id: String) { self.id = id } + } + """, + moduleName: "ModuleA" + ) + let moduleB = try makeSkeleton( + """ + @JS protocol GraphNode { var id: String { get } } + extension Building: GraphNode {} + extension Site: GraphNode {} + @JS public func store(_ n: T) -> T { n } + """, + moduleName: "ModuleB", + dependencies: [(moduleName: "ModuleA", skeleton: moduleA)] + ) + var link = BridgeJSLink() + let encoder = JSONEncoder() + try link.addSkeletonFile(data: encoder.encode(moduleA)) + try link.addSkeletonFile(data: encoder.encode(moduleB)) + let js = try link.link().outputJs + #expect( + js.contains( + #"const __bjs_tokenConformances = { "Building": ["GraphNode"], "Models_Site": ["GraphNode"] };"# + ) ) } @Test - func unconstrainedGenericExportedFunctionRejected() { - expectDiagnostic( - source: """ - @JS public func identity(_ value: T) -> T { value } - """, - contains: "Generic parameters on exported @JS functions are not supported yet" + func inheritedBridgeabilityRegistersProtocolAdapter() throws { + let source = """ + @JS protocol Base: BridgedSwiftGenericBridgeable { var id: String { get } } + @JS protocol Node: Base {} + @JS func identity(_ value: T) -> T { value } + @JS func read(_ value: any Node) -> String { value.id } + """ + let linked = try BridgeJSLink(skeletons: [makeSkeleton(source)]).link() + #expect(linked.outputJs.contains(#""Node": ["Node", "Base"]"#)) + #expect(linked.outputDts.contains("Node: BridgeType")) + } + + @Test(arguments: [ + "@JS func f(_ body: @Sendable (T) -> Bool) {}", + "@JS func f(_ body: inout (T) -> T) { body = { $0 } }", + "@JS func f(_ body: (T, inout Int) -> Bool) {}", + "@JS func f(_ value: T) -> (T) -> Bool { fatalError() }", + "@JS func f(_ body: ((T) -> Bool) -> T) {}", + ]) + func unsupportedGenericCallback(source: String) { + expectDiagnostic(source: source, contains: "Generic callbacks") + } + + @Test + func extensionDeclaredConformanceReachesTokenConformances() throws { + let skeleton = try makeSkeleton( + """ + @JS protocol GraphNode { var id: String { get } } + @JS struct Building { var id: String } + extension Building: GraphNode {} + @JS public func store(_ node: T) -> T { node } + """ ) + let structDef = try #require(skeleton.exported?.structs.first { $0.name == "Building" }) + #expect(structDef.conformedJSProtocols == ["GraphNode"]) } + } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericExports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericExports.swift new file mode 100644 index 000000000..dc3263c10 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericExports.swift @@ -0,0 +1,105 @@ +@JS struct ExportPoint { + var x: Int + var y: Int +} + +@JS public func genericExportIdentity(_ value: T) -> T { + return value +} + +@JS public func genericExportContainers( + _ values: [T], + _ optional: T?, + _ dictionary: [String: T] +) -> [String: T] { + dictionary +} + +@JS public func genericExportTransform( + _ value: T, + _ transform: (T) throws(JSException) -> U +) throws(JSException) -> U { + try transform(value) +} + +@JS public func genericExportTransformAsync( + _ value: T, + _ transform: @escaping (T) async throws(JSException) -> U +) async throws(JSException) -> U { + try await transform(value) +} + +@JS public func genericExportLoad(_ key: String) -> T? { + return nil +} + +@JS public func genericExportStructAndScalar(_ p: ExportPoint, tag: Int, _ v: T) -> T +{ + return v +} + +@JS +public func genericExportCaseDistinct< + T: BridgedSwiftGenericBridgeable, + t: BridgedSwiftGenericBridgeable +>(_ a: T, _ b: t) -> T { + return a +} + +@JS final class GenericBox { + @JS init() {} + + @JS func wrap(_ value: T) -> T { + return value + } + + @JS static func produce(_ body: () -> T) -> T { + body() + } +} + +@JS struct GenericPair { + @JS init() {} + + @JS static func wrap(_ value: T) -> [T] { + return [value] + } + + @JS("summarize") func summary(_ values: [T]) throws(JSException) -> ExportPoint { + ExportPoint(x: values.count, y: 0) + } + + @JS func map( + _ values: [T], + _ transform: (T, Int) -> U + ) -> [U] { + values.enumerated().map { transform($0.element, $0.offset) } + } +} + +@JS enum GenericFactory { + case primary + + @JS static func one(_ value: T) -> T { + return value + } +} + +@JS enum GenericNamespace { + @JS static func make(_ value: T) -> T { + return value + } +} + +@JS("ExportNode") protocol ExportGraphNode: BridgedSwiftGenericBridgeable { + var id: String { get } +} + +@JS struct ExportGraphBuilding: ExportGraphNode { + var id: String + var floors: Int +} + +@JS public func storeGraphNode(_ node: T) -> T { + return node +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.json new file mode 100644 index 000000000..fa5068c93 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.json @@ -0,0 +1,867 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_GenericBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "isFinal" : true, + "methods" : [ + { + "abiName" : "bjs_GenericBox_wrap", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "wrap", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "abiName" : "bjs_GenericBox_static_produce", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "produce", + "parameters" : [ + { + "label" : "_", + "name" : "body", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuley_1TT", + "moduleName" : "TestModule", + "parameters" : [ + + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "className" : { + "_0" : "GenericBox" + } + } + } + ], + "name" : "GenericBox", + "properties" : [ + + ], + "swiftCallName" : "GenericBox" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "primary" + } + ], + "emitStyle" : "const", + "name" : "GenericFactory", + "staticMethods" : [ + { + "abiName" : "bjs_GenericFactory_static_one", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "one", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "enumName" : { + "_0" : "GenericFactory" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericFactory", + "tsFullPath" : "GenericFactory" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "GenericNamespace", + "staticMethods" : [ + { + "abiName" : "bjs_GenericNamespace_static_make", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "make", + "namespace" : [ + "GenericNamespace" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GenericNamespace" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericNamespace", + "tsFullPath" : "GenericNamespace" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_genericExportIdentity", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "genericExportIdentity", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "abiName" : "bjs_genericExportContainers", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "genericExportContainers", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "optional", + "type" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "label" : "_", + "name" : "dictionary", + "type" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "abiName" : "bjs_genericExportTransform", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "genericExportTransform", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "10TestModuleK1TT_1UT", + "moduleName" : "TestModule", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + } + }, + { + "abiName" : "bjs_genericExportTransformAsync", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "genericExportTransformAsync", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "10TestModuleYaK1TT_1UT", + "moduleName" : "TestModule", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + } + }, + { + "abiName" : "bjs_genericExportLoad", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "genericExportLoad", + "parameters" : [ + { + "label" : "_", + "name" : "key", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_genericExportStructAndScalar", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "genericExportStructAndScalar", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "swiftStruct" : { + "_0" : "ExportPoint" + } + } + }, + { + "label" : "tag", + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "_", + "name" : "v", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "abiName" : "bjs_genericExportCaseDistinct", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "t" + } + ], + "name" : "genericExportCaseDistinct", + "parameters" : [ + { + "label" : "_", + "name" : "a", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "b", + "type" : { + "generic" : { + "_0" : "t" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "abiName" : "bjs_storeGraphNode", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "constraints" : [ + "ExportGraphNode" + ], + "name" : "T" + } + ], + "name" : "storeGraphNode", + "parameters" : [ + { + "label" : "_", + "name" : "node", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "protocols" : [ + { + "isGenericBridgeable" : true, + "jsName" : "ExportNode", + "methods" : [ + + ], + "name" : "ExportGraphNode", + "properties" : [ + { + "isReadonly" : true, + "name" : "id", + "type" : { + "string" : { + + } + } + } + ] + } + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "ExportPoint", + "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" : "ExportPoint" + }, + { + "constructor" : { + "abiName" : "bjs_GenericPair_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_GenericPair_static_wrap", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "wrap", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + }, + "staticContext" : { + "structName" : { + "_0" : "GenericPair" + } + } + }, + { + "abiName" : "bjs_GenericPair_summarize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "jsName" : "summarize", + "name" : "summary", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ExportPoint" + } + } + }, + { + "abiName" : "bjs_GenericPair_map", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "map", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule1TTSi_1UT", + "moduleName" : "TestModule", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + }, + { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "U" + } + } + } + } + } + ], + "name" : "GenericPair", + "properties" : [ + + ], + "swiftCallName" : "GenericPair" + }, + { + "conformedJSProtocols" : [ + "ExportGraphNode" + ], + "methods" : [ + + ], + "name" : "ExportGraphBuilding", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "floors", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "ExportGraphBuilding" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.swift new file mode 100644 index 000000000..0d6d068d0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericExports.swift @@ -0,0 +1,962 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule1TTSi_1UT") +fileprivate func invoke_js_callback_TestModule_10TestModule1TTSi_1UT_extern(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModule1TTSi_1UT_extern(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule1TTSi_1UT(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModule1TTSi_1UT_extern(callback, param1, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_10TestModule1TTSi_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T, Int) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0, param1) in + #if arch(wasm32) + let param1Value = param1.bridgeJSLowerParameter() + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModule1TTSi_1UT(callbackValue, param1Value, T.bridgeJSTypeID, U.bridgeJSTypeID) + return U.bridgeJSStackPop() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleK1TT_1UT") +fileprivate func invoke_js_callback_TestModule_10TestModuleK1TT_1UT_extern(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleK1TT_1UT_extern(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleK1TT_1UT(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleK1TT_1UT_extern(callback, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_10TestModuleK1TT_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T) throws(JSException) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: T) throws(JSException) -> U in + #if arch(wasm32) + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleK1TT_1UT(callbackValue, T.bridgeJSTypeID, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT_extern(resolveRef, rejectRef, callback, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_10TestModuleYaK1TT_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T) async throws(JSException) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: T) async throws(JSException) -> U in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT(resolveRef, rejectRef, callbackValue, T.bridgeJSTypeID, U.bridgeJSTypeID) + } + return try _bjs_async_result_1UT(resolved) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "async_callback_result_TestModule_1UT") +fileprivate func async_callback_result_TestModule_1UT_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func async_callback_result_TestModule_1UT_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func async_callback_result_TestModule_1UT(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void { + return async_callback_result_TestModule_1UT_extern(valueKind, valuePayload1, valuePayload2, _generic0TypeId) +} + +func _bjs_async_result_1UT(_ value: JSValue) throws(JSException) -> U { + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + async_callback_result_TestModule_1UT(valueKind, valuePayload1, valuePayload2, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() +} + +#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_10TestModuley_1TT") +fileprivate func invoke_js_callback_TestModule_10TestModuley_1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_1TT(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuley_1TT_extern(callback, _generic0TypeId) +} + +private enum _BJS_Closure_10TestModuley_1TT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type) -> () -> T { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuley_1TT(callbackValue, T.bridgeJSTypeID) + return T.bridgeJSStackPop() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension ExportGraphNode where Self: _BridgedSwiftProtocolWrapper { + var id: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_ExportGraphNode_id_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyExportGraphNode: ExportGraphNode, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyExportGraphNode(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ExportGraphNode_id_get") +fileprivate func bjs_ExportGraphNode_id_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_ExportGraphNode_id_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ExportGraphNode_id_get(_ jsObject: Int32) -> Int32 { + return bjs_ExportGraphNode_id_get_extern(jsObject) +} + +extension GenericFactory: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> GenericFactory { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> GenericFactory { + return GenericFactory(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .primary + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .primary: + return 0 + } + } +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericFactory_static_one") +@_cdecl("bjs_GenericFactory_static_one") +public func _bjs_GenericFactory_static_one(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericFactory_static_one") +@_cdecl("bjs_GenericFactory_static_one") +public func _bjs_GenericFactory_static_one(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_GenericFactory_static_one_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericFactory_static_one_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = GenericFactory.one(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericNamespace_static_make") +@_cdecl("bjs_GenericNamespace_static_make") +public func _bjs_GenericNamespace_static_make(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericNamespace_static_make") +@_cdecl("bjs_GenericNamespace_static_make") +public func _bjs_GenericNamespace_static_make(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_GenericNamespace_static_make_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericNamespace_static_make_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = GenericNamespace.make(_: value) + ret.bridgeJSStackPush() +} +#endif + +extension ExportPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ExportPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return ExportPoint(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ExportPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ExportPoint())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ExportPoint") +fileprivate func _bjs_struct_lower_ExportPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ExportPoint_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ExportPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ExportPoint_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ExportPoint") +fileprivate func _bjs_struct_lift_ExportPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ExportPoint_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ExportPoint() -> Int32 { + return _bjs_struct_lift_ExportPoint_extern() +} + +extension GenericPair: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericPair { + return GenericPair() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_GenericPair(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_GenericPair())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_GenericPair") +fileprivate func _bjs_struct_lower_GenericPair_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_GenericPair_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_GenericPair(_ objectId: Int32) -> Void { + return _bjs_struct_lower_GenericPair_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_GenericPair") +fileprivate func _bjs_struct_lift_GenericPair_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_GenericPair_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_GenericPair() -> Int32 { + return _bjs_struct_lift_GenericPair_extern() +} + +@_expose(wasm, "bjs_GenericPair_init") +@_cdecl("bjs_GenericPair_init") +public func _bjs_GenericPair_init() -> Void { + #if arch(wasm32) + let ret = GenericPair() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericPair_static_wrap") +@_cdecl("bjs_GenericPair_static_wrap") +public func _bjs_GenericPair_static_wrap(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericPair_static_wrap") +@_cdecl("bjs_GenericPair_static_wrap") +public func _bjs_GenericPair_static_wrap(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_GenericPair_static_wrap_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericPair_static_wrap_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: [T] = GenericPair.wrap(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericPair_summarize") +@_cdecl("bjs_GenericPair_summarize") +public func _bjs_GenericPair_summarize(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericPair_summarize") +@_cdecl("bjs_GenericPair_summarize") +public func _bjs_GenericPair_summarize(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + do { + try _bjs_GenericPair_summarize_open1(_generic0Type) + } 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 +} +private func _bjs_GenericPair_summarize_open1(_ _generic0Type: T.Type) throws(JSException) { + let values = Array.bridgeJSStackPop() + let _self = GenericPair.bridgeJSLiftParameter() + let ret = try _self.summary(_: values) + return ret.bridgeJSLowerReturn() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericPair_map") +@_cdecl("bjs_GenericPair_map") +public func _bjs_GenericPair_map(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericPair_map") +@_cdecl("bjs_GenericPair_map") +public func _bjs_GenericPair_map(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + _bjs_GenericPair_map_open1(_generic0Type, _generic1Type, transform) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericPair_map_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) { + _bjs_GenericPair_map_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_GenericPair_map_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) { + let transform = _BJS_Closure_10TestModule1TTSi_1UT.bridgeJSLift(transform, T.self, U.self) + let values = Array.bridgeJSStackPop() + let _self = GenericPair.bridgeJSLiftParameter() + let ret: [U] = _self.map(_: values, _: transform) + ret.bridgeJSStackPush() +} +#endif + +extension ExportGraphBuilding: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ExportGraphBuilding { + let floors = Int.bridgeJSStackPop() + let id = String.bridgeJSStackPop() + return ExportGraphBuilding(id: id, floors: floors) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.floors.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ExportGraphBuilding(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ExportGraphBuilding())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ExportGraphBuilding") +fileprivate func _bjs_struct_lower_ExportGraphBuilding_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ExportGraphBuilding_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ExportGraphBuilding(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ExportGraphBuilding_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ExportGraphBuilding") +fileprivate func _bjs_struct_lift_ExportGraphBuilding_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ExportGraphBuilding_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ExportGraphBuilding() -> Int32 { + return _bjs_struct_lift_ExportGraphBuilding_extern() +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportIdentity") +@_cdecl("bjs_genericExportIdentity") +public func _bjs_genericExportIdentity(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportIdentity") +@_cdecl("bjs_genericExportIdentity") +public func _bjs_genericExportIdentity(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_genericExportIdentity_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportIdentity_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = genericExportIdentity(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportContainers") +@_cdecl("bjs_genericExportContainers") +public func _bjs_genericExportContainers(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportContainers") +@_cdecl("bjs_genericExportContainers") +public func _bjs_genericExportContainers(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_genericExportContainers_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportContainers_open1(_ _generic0Type: T.Type) { + let dictionary = Dictionary.bridgeJSStackPop() + let optional = Optional.bridgeJSStackPop() + let values = Array.bridgeJSStackPop() + let ret: [String: T] = genericExportContainers(_: values, _: optional, _: dictionary) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportTransform") +@_cdecl("bjs_genericExportTransform") +public func _bjs_genericExportTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportTransform") +@_cdecl("bjs_genericExportTransform") +public func _bjs_genericExportTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + do { + try _bjs_genericExportTransform_open1(_generic0Type, _generic1Type, transform) + } 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 +} +private func _bjs_genericExportTransform_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) throws(JSException) { + try _bjs_genericExportTransform_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_genericExportTransform_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) throws(JSException) { + let transform = _BJS_Closure_10TestModuleK1TT_1UT.bridgeJSLift(transform, T.self, U.self) + let value = T.bridgeJSStackPop() + let ret: U = try genericExportTransform(_: value, _: transform) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportTransformAsync") +@_cdecl("bjs_genericExportTransformAsync") +public func _bjs_genericExportTransformAsync(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportTransformAsync") +@_cdecl("bjs_genericExportTransformAsync") +public func _bjs_genericExportTransformAsync(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + return _bjs_genericExportTransformAsync_open1(_generic0Type, _generic1Type, transform) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportTransformAsync_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) -> Int32 { + return _bjs_genericExportTransformAsync_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_genericExportTransformAsync_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) -> Int32 { + let transform = _BJS_Closure_10TestModuleYaK1TT_1UT.bridgeJSLift(transform, T.self, U.self) + let value = T.bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_1UT, reject: Promise_reject) { () async throws(JSException) -> U in + return try await genericExportTransformAsync(_: value, _: transform) + } +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportLoad") +@_cdecl("bjs_genericExportLoad") +public func _bjs_genericExportLoad(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportLoad") +@_cdecl("bjs_genericExportLoad") +public func _bjs_genericExportLoad(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_genericExportLoad_open1(_generic0Type, keyBytes, keyLength) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportLoad_open1(_ _generic0Type: T.Type, _ keyBytes: Int32, _ keyLength: Int32) { + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + let ret: Optional = genericExportLoad(_: key) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportStructAndScalar") +@_cdecl("bjs_genericExportStructAndScalar") +public func _bjs_genericExportStructAndScalar(_ tag: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportStructAndScalar") +@_cdecl("bjs_genericExportStructAndScalar") +public func _bjs_genericExportStructAndScalar(_ tag: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_genericExportStructAndScalar_open1(_generic0Type, tag) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportStructAndScalar_open1(_ _generic0Type: T.Type, _ tag: Int32) { + let v = T.bridgeJSStackPop() + let tag = Int.bridgeJSLiftParameter(tag) + let p = ExportPoint.bridgeJSLiftParameter() + let ret: T = genericExportStructAndScalar(_: p, tag: tag, _: v) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_genericExportCaseDistinct") +@_cdecl("bjs_genericExportCaseDistinct") +public func _bjs_genericExportCaseDistinct(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_genericExportCaseDistinct") +@_cdecl("bjs_genericExportCaseDistinct") +public func _bjs_genericExportCaseDistinct(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + _bjs_genericExportCaseDistinct_open1(_generic0Type, _generic1Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_genericExportCaseDistinct_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type) { + _bjs_genericExportCaseDistinct_open2(_generic1Type, asT: T.self) +} +private func _bjs_genericExportCaseDistinct_open2(_ _generic1Type: t.Type, asT _generic0Type: T.Type) { + let b = t.bridgeJSStackPop() + let a = T.bridgeJSStackPop() + let ret: T = genericExportCaseDistinct(_: a, _: b) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_storeGraphNode") +@_cdecl("bjs_storeGraphNode") +public func _bjs_storeGraphNode(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_storeGraphNode") +@_cdecl("bjs_storeGraphNode") +public func _bjs_storeGraphNode(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0TypeBase = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + guard let _generic0Type = _generic0TypeBase as? any (BridgedSwiftGenericBridgeable & ExportGraphNode).Type else { + fatalError("BridgeJS: type '\(_generic0TypeBase)' does not conform to required protocol(s): ExportGraphNode") + } + _bjs_storeGraphNode_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_storeGraphNode_open1(_ _generic0Type: T.Type) { + let node = T.bridgeJSStackPop() + let ret: T = storeGraphNode(_: node) + ret.bridgeJSStackPush() +} +#endif + +@_expose(wasm, "bjs_GenericBox_init") +@_cdecl("bjs_GenericBox_init") +public func _bjs_GenericBox_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = GenericBox() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericBox_wrap") +@_cdecl("bjs_GenericBox_wrap") +public func _bjs_GenericBox_wrap(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericBox_wrap") +@_cdecl("bjs_GenericBox_wrap") +public func _bjs_GenericBox_wrap(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_GenericBox_wrap_open1(_generic0Type, _self) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericBox_wrap_open1(_ _generic0Type: T.Type, _ _self: UnsafeMutableRawPointer) { + let value = T.bridgeJSStackPop() + let _self = GenericBox.bridgeJSLiftParameter(_self) + let ret: T = _self.wrap(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_GenericBox_static_produce") +@_cdecl("bjs_GenericBox_static_produce") +public func _bjs_GenericBox_static_produce(_ body: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_GenericBox_static_produce") +@_cdecl("bjs_GenericBox_static_produce") +public func _bjs_GenericBox_static_produce(_ body: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_GenericBox_static_produce_open1(_generic0Type, body) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_GenericBox_static_produce_open1(_ _generic0Type: T.Type, _ body: Int32) { + let body = _BJS_Closure_10TestModuley_1TT.bridgeJSLift(body, T.self) + let ret: T = GenericBox.produce(_: body) + ret.bridgeJSStackPush() +} +#endif + +@_expose(wasm, "bjs_GenericBox_deinit") +@_cdecl("bjs_GenericBox_deinit") +public func _bjs_GenericBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension GenericBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_GenericBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GenericBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericBox_wrap") +fileprivate func _bjs_GenericBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_GenericBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_GenericBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GenericBox_wrap_extern(pointer) +} + +extension ExportPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportPoint.bridgeJSMakeTypeHandle() +} + +extension GenericPair: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericPair.bridgeJSMakeTypeHandle() +} + +extension ExportGraphBuilding: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGraphBuilding.bridgeJSMakeTypeHandle() +} + +extension GenericBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericBox.bridgeJSMakeTypeHandle() +} + +extension GenericFactory: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericFactory.bridgeJSMakeTypeHandle() +} + +extension AnyExportGraphNode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyExportGraphNode.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_1UT(_ promise: JSObject, _ value: U) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_1UT") +fileprivate func promise_resolve_TestModule_1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_1UT(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + return promise_resolve_TestModule_1UT_extern(promise, _generic0TypeId) +} + +func _$Promise_resolve_1UT(_ promise: JSObject, _ value: U) throws(JSException) -> Void { + value.bridgeJSStackPush() + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_TestModule_1UT(promiseValue, U.bridgeJSTypeID) + 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) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + ExportPoint.bridgeJSTypeID, + GenericPair.bridgeJSTypeID, + ExportGraphBuilding.bridgeJSTypeID, + GenericBox.bridgeJSTypeID, + GenericFactory.bridgeJSTypeID, + AnyExportGraphNode.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/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index c025cf4f0..9935162cc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -794,26 +794,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/GenericExports.callsites.check.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.callsites.check.ts new file mode 100644 index 000000000..7867ab3db --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.callsites.check.ts @@ -0,0 +1,31 @@ +import type { BridgeTypes as ExportTokens, Exports as GenericExports } from "./GenericExports.d.ts"; + +declare const exports: GenericExports; +declare const BridgeTypes: typeof ExportTokens; + +const n: number = exports.genericExportIdentity(42, BridgeTypes.Int); +const s: string = exports.genericExportIdentity("hi", BridgeTypes.String); +const input = { x: 1, y: 2, label: "not part of ExportPoint" }; +const p = exports.genericExportIdentity(input, BridgeTypes.ExportPoint); +const px: number = p.x; +// @ts-expect-error +exports.genericExportIdentity(input, BridgeTypes.ExportPoint); +const transformed: string = exports.genericExportTransform(42, value => value.toString(), BridgeTypes.Int, BridgeTypes.String); +const produced: string = exports.GenericBox.produce(() => "value", BridgeTypes.String); + +// @ts-expect-error +exports.genericExportTransform(42, value => value + 1, BridgeTypes.Int, BridgeTypes.String); + +// @ts-expect-error +exports.genericExportIdentity(42, "Int"); + +// @ts-expect-error +exports.genericExportIdentity("hi", BridgeTypes.Int); + +const b = exports.storeGraphNode({ id: "b", floors: 3 }, BridgeTypes.ExportGraphBuilding); +const bid: string = b.id; + +// @ts-expect-error +exports.storeGraphNode(5, BridgeTypes.Int); + +export { n, s, px, bid, transformed, produced }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.d.ts new file mode 100644 index 000000000..8f13d675c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.d.ts @@ -0,0 +1,75 @@ +// 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 ExportNode { + readonly id: string; +} + +export const GenericFactoryValues: { + readonly Primary: 0; +}; +export type GenericFactoryTag = typeof GenericFactoryValues[keyof typeof GenericFactoryValues]; + +export interface ExportPoint { + x: number; + y: number; +} +export interface GenericPair { + summarize(values: T[], typeT: BridgeType): ExportPoint; + map(values: T[], transform: (arg0: T, arg1: number) => U, typeT: BridgeType, typeU: BridgeType): U[]; +} +export interface ExportGraphBuilding { + id: string; + floors: number; +} +declare const bridgeTypeBrand: unique symbol; +export type BridgeType = string & { readonly [bridgeTypeBrand]: (value: T) => T }; +export const BridgeTypes: { readonly Bool: BridgeType; readonly Int: BridgeType; readonly Int8: BridgeType; readonly UInt8: BridgeType; readonly Int16: BridgeType; readonly UInt16: BridgeType; readonly Int32: BridgeType; readonly UInt32: BridgeType; readonly UInt: BridgeType; readonly Int64: BridgeType; readonly UInt64: BridgeType; readonly Float: BridgeType; readonly Double: BridgeType; readonly String: BridgeType; readonly JSValue: BridgeType; readonly ExportPoint: BridgeType; readonly GenericPair: BridgeType; readonly ExportGraphBuilding: BridgeType; readonly GenericBox: BridgeType; readonly GenericFactory: BridgeType; readonly ExportGraphNode: BridgeType; }; +export type GenericFactoryObject = typeof GenericFactoryValues & { + one(value: T, typeT: BridgeType): T; +}; + +/// 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 GenericBox extends SwiftHeapObject { + wrap(value: T, typeT: BridgeType): T; +} +export type Exports = { + genericExportIdentity(value: T, typeT: BridgeType): T; + genericExportContainers(values: T[], optional: T | null, dictionary: Record, typeT: BridgeType): Record; + genericExportTransform(value: T, transform: (arg0: T) => U, typeT: BridgeType, typeU: BridgeType): U; + genericExportTransformAsync(value: T, transform: (arg0: T) => Promise, typeT: BridgeType, typeU: BridgeType): Promise; + genericExportLoad(key: string, typeT: BridgeType): T | null; + genericExportStructAndScalar(p: ExportPoint, tag: number, v: T, typeT: BridgeType): T; + genericExportCaseDistinct(a: T, b: t, typeT: BridgeType, typet: BridgeType): T; + storeGraphNode(node: T, typeT: BridgeType): T; + GenericFactory: GenericFactoryObject + GenericBox: { + new(): GenericBox; + produce(body: () => T, typeT: BridgeType): T; + }, + GenericNamespace: { + make(value: T, typeT: BridgeType): T; + }, + GenericPair: { + init(): GenericPair; + wrap(value: T, typeT: BridgeType): T[]; + }, +} +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/GenericExports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.js new file mode 100644 index 000000000..cf7eee474 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericExports.js @@ -0,0 +1,1111 @@ +// 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 GenericFactoryValues = { + Primary: 0, +}; + +export const BridgeTypes = { Bool: "Bool", Int: "Int", Int8: "Int8", UInt8: "UInt8", Int16: "Int16", UInt16: "UInt16", Int32: "Int32", UInt32: "UInt32", UInt: "UInt", Int64: "Int64", UInt64: "UInt64", Float: "Float", Double: "Double", String: "String", JSValue: "JSValue", ExportPoint: "ExportPoint", GenericPair: "GenericPair", ExportGraphBuilding: "ExportGraphBuilding", GenericBox: "GenericBox", GenericFactory: "GenericFactory", ExportGraphNode: "ExportGraphNode" }; +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(); + const __bjs_typeIdByToken = new Map(); + let __bjs_typeHandlesRegistered = false; + function __bjs_registerTypeHandles() { + if (__bjs_typeHandlesRegistered) { + return; + } + __bjs_typeHandlesRegistered = true; + instance.exports["bjs_core_register_type_handles"](); + 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; + } + const __bjs_tokenConformances = { "ExportGraphBuilding": ["ExportGraphNode"], "ExportGraphNode": ["ExportGraphNode"] }; + function __bjs_typeIdForToken(token, requiredProtocols) { + __bjs_registerTypeHandles(); + const typeId = __bjs_typeIdByToken.get(token); + if (typeId === undefined) { + throw new TypeError("BridgeJS: unknown BridgeType token '" + token + "'"); + } + if (requiredProtocols) { + const conformances = __bjs_tokenConformances[token] || []; + for (const requiredProtocol of requiredProtocols) { + if (!conformances.includes(requiredProtocol)) { + throw new TypeError("BridgeJS: type '" + token + "' does not conform to required protocol '" + requiredProtocol + "'"); + } + } + } + return typeId; + } + + let _exports = null; + let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); + function __bjs_arrayCodec(elementCodec) { + 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]); + } + 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; + }, + }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; + } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + 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) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + cache.set(elementCodec, codec); + return codec; + } + const __bjs_dictCodecCache = new WeakMap(); + function __bjs_dictCodec(valueCodec) { + 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++) { + __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; + }, + }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; + } + + 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 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); + }; + + const __bjs_codec_M10TestModuleT11ExportPoint = { + lower: (v) => { + structHelpers.M10TestModuleT11ExportPoint.lower(v); + }, + lift: () => { + const struct = structHelpers.M10TestModuleT11ExportPoint.lift(); + return struct; + }, + }; + const __bjs_codec_M10TestModuleT11GenericPair = { + lower: (v) => { + structHelpers.M10TestModuleT11GenericPair.lower(v); + }, + lift: () => { + const struct = structHelpers.M10TestModuleT11GenericPair.lift(); + return struct; + }, + }; + const __bjs_codec_M10TestModuleT19ExportGraphBuilding = { + lower: (v) => { + structHelpers.M10TestModuleT19ExportGraphBuilding.lower(v); + }, + lift: () => { + const struct = structHelpers.M10TestModuleT19ExportGraphBuilding.lift(); + return struct; + }, + }; + const __bjs_codec_M10TestModuleT10GenericBox = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['GenericBox'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_M10TestModuleT14GenericFactory = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const __bjs_codec_M10TestModuleT15ExportGraphNode = { + 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_M10TestModuleT11ExportPoint = () => ({ + 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_createStructHelpers_M10TestModuleT11GenericPair = () => ({ + lower: (value) => { + }, + lift: () => { + const instance1 = { }; + instance1.summarize = function(values, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + structHelpers.M10TestModuleT11GenericPair.lower(this); + __bjs_arrayCodec(codecT).lower(values); + instance.exports.bjs_GenericPair_summarize(typeIdT); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + const structValue = structHelpers.M10TestModuleT11ExportPoint.lift(); + return structValue; + }.bind(instance1); + instance1.map = function(values, transform, typeT, typeU) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const typeIdU = __bjs_typeIdForToken(typeU); + const codecU = __bjs_codecForTypeId(typeIdU); + structHelpers.M10TestModuleT11GenericPair.lower(this); + __bjs_arrayCodec(codecT).lower(values); + const callbackId = swift.memory.retain(transform); + instance.exports.bjs_GenericPair_map(callbackId, typeIdT, typeIdU); + return __bjs_arrayCodec(codecU).lift(); + }.bind(instance1); + return instance1; + } + }); + const __bjs_createStructHelpers_M10TestModuleT19ExportGraphBuilding = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.id); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value.floors | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + const string = strStack.pop(); + return { id: string, floors: 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_ExportPoint"] = function(objectId) { + structHelpers.M10TestModuleT11ExportPoint.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_ExportPoint"] = function() { + const value = structHelpers.M10TestModuleT11ExportPoint.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_GenericPair"] = function(objectId) { + structHelpers.M10TestModuleT11GenericPair.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_GenericPair"] = function() { + const value = structHelpers.M10TestModuleT11GenericPair.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_ExportGraphBuilding"] = function(objectId) { + structHelpers.M10TestModuleT19ExportGraphBuilding.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_ExportGraphBuilding"] = function() { + const value = structHelpers.M10TestModuleT19ExportGraphBuilding.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_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, + ]; + const tokens = ["Bool", "Int", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "UInt", "Int64", "UInt64", "Float", "Double", "String", "JSValue"]; + 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_typeIdByToken.set(tokens[i], typeIds[i]); + } + } + bjs["bjs_TestModule_register_type_handles"] = function(base, count) { + const codecs = [ + __bjs_codec_M10TestModuleT11ExportPoint, + __bjs_codec_M10TestModuleT11GenericPair, + __bjs_codec_M10TestModuleT19ExportGraphBuilding, + __bjs_codec_M10TestModuleT10GenericBox, + __bjs_codec_M10TestModuleT14GenericFactory, + __bjs_codec_M10TestModuleT15ExportGraphNode, + ]; + const tokens = ["ExportPoint", "GenericPair", "ExportGraphBuilding", "GenericBox", "GenericFactory", "ExportGraphNode"]; + 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_typeIdByToken.set(tokens[i], typeIds[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["promise_resolve_TestModule_1UT"] = function(promise, uTypeId) { + try { + const codecU = __bjs_codecForTypeId(uTypeId); + const value = codecU.lift(); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value); + } 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) {} + bjs["swift_js_closure_unregister"] = function(funcRef) { + const func = swift.memory.getObject(funcRef); + func.__unregister(); + } + bjs["invoke_js_callback_TestModule_10TestModule1TTSi_1UT"] = function(callbackId, param1, tTypeId, uTypeId) { + try { + const callback = swift.memory.getObject(callbackId); + const codecT = __bjs_codecForTypeId(tTypeId); + const codecU = __bjs_codecForTypeId(uTypeId); + const param0 = codecT.lift(); + let ret = callback(param0, param1); + codecU.lower(ret); + } catch (error) { + setException(error); + } + } + bjs["invoke_js_callback_TestModule_10TestModuleK1TT_1UT"] = function(callbackId, tTypeId, uTypeId) { + try { + const callback = swift.memory.getObject(callbackId); + const codecT = __bjs_codecForTypeId(tTypeId); + const codecU = __bjs_codecForTypeId(uTypeId); + const param0 = codecT.lift(); + let ret = callback(param0); + codecU.lower(ret); + } catch (error) { + setException(error); + } + } + bjs["invoke_js_callback_TestModule_10TestModuleYaK1TT_1UT"] = function(resolveRef, rejectRef, callbackId, tTypeId, uTypeId) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + const codecT = __bjs_codecForTypeId(tTypeId); + const codecU = __bjs_codecForTypeId(uTypeId); + const param0 = codecT.lift(); + Promise.resolve().then(() => callback(param0)).then(resolve, reject); + } + bjs["async_callback_result_TestModule_1UT"] = function(valueKind, valuePayload1, valuePayload2, uTypeId) { + try { + const codecU = __bjs_codecForTypeId(uTypeId); + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + let ret = (value => value)(jsValue); + codecU.lower(ret); + } catch (error) { + setException(error); + } + } + 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_10TestModuley_1TT"] = function(callbackId, tTypeId) { + try { + const callback = swift.memory.getObject(callbackId); + const codecT = __bjs_codecForTypeId(tTypeId); + let ret = callback(); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_GenericBox_wrap"] = function(pointer) { + const obj = _exports['GenericBox'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_ExportGraphNode_id_get"] = function bjs_ExportGraphNode_id_get(self) { + try { + let ret = swift.memory.getObject(self).id; + 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.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 GenericBox extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GenericBox_deinit, GenericBox.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_GenericBox_init(); + return GenericBox.__construct(ret); + } + wrap(value, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(value); + instance.exports.bjs_GenericBox_wrap(this.pointer, typeIdT); + return codecT.lift(); + } + static produce(body, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const callbackId = swift.memory.retain(body); + instance.exports.bjs_GenericBox_static_produce(callbackId, typeIdT); + return codecT.lift(); + } + } + const __bjs_helpers_M10TestModuleT11ExportPoint = __bjs_createStructHelpers_M10TestModuleT11ExportPoint(); + structHelpers.M10TestModuleT11ExportPoint = __bjs_helpers_M10TestModuleT11ExportPoint; + + const __bjs_helpers_M10TestModuleT11GenericPair = __bjs_createStructHelpers_M10TestModuleT11GenericPair(); + structHelpers.M10TestModuleT11GenericPair = __bjs_helpers_M10TestModuleT11GenericPair; + + const __bjs_helpers_M10TestModuleT19ExportGraphBuilding = __bjs_createStructHelpers_M10TestModuleT19ExportGraphBuilding(); + structHelpers.M10TestModuleT19ExportGraphBuilding = __bjs_helpers_M10TestModuleT19ExportGraphBuilding; + + const exports = { + genericExportIdentity: function bjs_genericExportIdentity(value, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(value); + instance.exports.bjs_genericExportIdentity(typeIdT); + return codecT.lift(); + }, + genericExportContainers: function bjs_genericExportContainers(values, optional, dictionary, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + __bjs_arrayCodec(codecT).lower(values); + __bjs_optionalCodec(codecT).lower(optional); + __bjs_dictCodec(codecT).lower(dictionary); + instance.exports.bjs_genericExportContainers(typeIdT); + return __bjs_dictCodec(codecT).lift(); + }, + genericExportTransform: function bjs_genericExportTransform(value, transform, typeT, typeU) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const typeIdU = __bjs_typeIdForToken(typeU); + const codecU = __bjs_codecForTypeId(typeIdU); + codecT.lower(value); + const callbackId = swift.memory.retain(transform); + instance.exports.bjs_genericExportTransform(callbackId, typeIdT, typeIdU); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return codecU.lift(); + }, + genericExportTransformAsync: function bjs_genericExportTransformAsync(value, transform, typeT, typeU) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const typeIdU = __bjs_typeIdForToken(typeU); + const codecU = __bjs_codecForTypeId(typeIdU); + codecT.lower(value); + const callbackId = swift.memory.retain(transform); + const ret = instance.exports.bjs_genericExportTransformAsync(callbackId, typeIdT, typeIdU); + 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; + }, + genericExportLoad: function bjs_genericExportLoad(key, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const keyBytes = textEncoder.encode(key); + const keyId = swift.memory.retain(keyBytes); + instance.exports.bjs_genericExportLoad(keyId, keyBytes.length, typeIdT); + return __bjs_optionalCodec(codecT).lift(); + }, + genericExportStructAndScalar: function bjs_genericExportStructAndScalar(p, tag, v, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + structHelpers.M10TestModuleT11ExportPoint.lower(p); + codecT.lower(v); + instance.exports.bjs_genericExportStructAndScalar(tag, typeIdT); + return codecT.lift(); + }, + genericExportCaseDistinct: function bjs_genericExportCaseDistinct(a, b, typeT, typet) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + const typeIdt = __bjs_typeIdForToken(typet); + const codect = __bjs_codecForTypeId(typeIdt); + codecT.lower(a); + codect.lower(b); + instance.exports.bjs_genericExportCaseDistinct(typeIdT, typeIdt); + return codecT.lift(); + }, + storeGraphNode: function bjs_storeGraphNode(node, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT, ["ExportGraphNode"]); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(node); + instance.exports.bjs_storeGraphNode(typeIdT); + return codecT.lift(); + }, + GenericFactory: { + ...GenericFactoryValues, + one: function(value, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(value); + instance.exports.bjs_GenericFactory_static_one(typeIdT); + return codecT.lift(); + } + }, + GenericBox, + GenericNamespace: { + make: function bjs_GenericNamespace_static_make(value, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(value); + instance.exports.bjs_GenericNamespace_static_make(typeIdT); + return codecT.lift(); + }, + }, + GenericPair: { + init: function() { + instance.exports.bjs_GenericPair_init(); + const structValue = structHelpers.M10TestModuleT11GenericPair.lift(); + return structValue; + }, + wrap: function(value, typeT) { + const typeIdT = __bjs_typeIdForToken(typeT); + const codecT = __bjs_codecForTypeId(typeIdT); + codecT.lower(value); + instance.exports.bjs_GenericPair_static_wrap(typeIdT); + return __bjs_arrayCodec(codecT).lift(); + }, + }, + }; + _exports = exports; + 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 363f6c595..47a2bf107 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -605,14 +605,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/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index eed26c581..1c6801702 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -246,14 +246,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); @@ -271,14 +271,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); @@ -303,14 +303,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); @@ -328,14 +328,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 279a9d3c6..fe458add2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -749,14 +749,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); @@ -775,13 +775,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); @@ -824,13 +824,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); @@ -926,14 +926,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); @@ -1044,14 +1044,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); @@ -1087,14 +1087,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); @@ -1113,13 +1113,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); @@ -1144,15 +1144,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); @@ -1190,14 +1190,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); @@ -1216,14 +1216,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); @@ -1259,14 +1259,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); @@ -1285,14 +1285,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); @@ -1311,14 +1311,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); @@ -1337,14 +1337,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); @@ -1363,14 +1363,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); @@ -1387,14 +1387,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); @@ -1408,14 +1408,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 96c78dd22..e34591aec 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -400,14 +400,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/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json index 277b2c578..d16161ca2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json @@ -6,7 +6,8 @@ "target": "ES2020", "module": "ES2020", "moduleResolution": "node", - "lib": ["ES2020", "DOM"] + "lib": ["ES2020", "DOM"], + "allowImportingTsExtensions": true }, - "include": ["*.d.ts"] + "include": ["*.d.ts", "*.check.ts"] } diff --git a/Tests/BridgeJSRuntimeTests/ExportGenericAPIs.swift b/Tests/BridgeJSRuntimeTests/ExportGenericAPIs.swift new file mode 100644 index 000000000..9ed2728dc --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ExportGenericAPIs.swift @@ -0,0 +1,226 @@ +import Testing +import JavaScriptKit + +@JS public struct ExportGenericPoint { + public var x: Int + public var y: Int + + public init(x: Int, y: Int) { + self.x = x + self.y = y + } +} + +@JS public func exportGenericIdentity(_ value: T) -> T { + value +} + +@JS public func exportGenericArrayIdentity(_ values: [T]) -> [T] { + values +} + +@JS public func exportGenericOptionalIdentity(_ value: T?) -> T? { + value +} + +@JS public func exportGenericDictIdentity(_ values: [String: T]) -> [String: T] { + values +} + +@JS +public func exportGenericCount< + T: BridgedSwiftGenericBridgeable, + U: BridgedSwiftGenericBridgeable, + V: BridgedSwiftGenericBridgeable +>( + _ values: [T], + _ other: U, + _ extra: V, + _ fail: Bool +) throws(JSException) -> Int64 { + if fail { throw JSException(message: "count failed") } + return Int64(values.count) +} + +@JS public func exportGenericOptionalCount(_ values: [T]) -> Int? { + values.isEmpty ? nil : values.count +} + +@JS public func exportGenericTransform( + _ value: T, + _ transform: (T) throws(JSException) -> U +) throws(JSException) -> U { + try transform(value) +} + +@JS public func exportGenericSelect( + _ values: [T], + _ select: ([T]) -> T? +) -> T? { + select(values) +} + +@JS public func exportGenericAsyncTransform( + _ value: T, + _ transform: @escaping (T) async throws(JSException) -> U +) async throws(JSException) -> U { + try await transform(value) +} + +nonisolated(unsafe) var _lastWrappedPoint = ExportGenericPoint(x: 0, y: 0) +nonisolated(unsafe) var _lastTag = 0 + +@JS public func exportGenericWrapPointAndTag( + _ p: ExportGenericPoint, + tag: Int, + _ value: T +) -> T { + _lastWrappedPoint = p + _lastTag = tag + return value +} + +@JS public final class ExportGenericMethodBox { + @JS public var value: Int = 0 + private var stored: (() throws(JSException) -> any BridgedSwiftGenericBridgeable)? + private var storedAsync: (() async throws(JSException) -> any BridgedSwiftGenericBridgeable)? + + @JS public init() {} + + @JS public func store( + _ value: T, + _ callback: @escaping (T) throws(JSException) -> U + ) { + stored = { () throws(JSException) -> any BridgedSwiftGenericBridgeable in try callback(value) } + } + + @JS public func invoke() throws(JSException) -> T? { + try stored?() as? T + } + + @JS public func storeAsync( + _ value: T, + _ callback: @escaping (T) async throws(JSException) -> U + ) { + storedAsync = { () async throws(JSException) -> any BridgedSwiftGenericBridgeable in try await callback(value) } + } + + @JS public func run() async throws(JSException) -> T? { + try await storedAsync?() as? T + } + + @JS public func clear() { + stored = nil + storedAsync = nil + } + @JS public static func produce(_ body: () -> T) -> T { + body() + } +} + +@JS public struct ExportGenericMethodPair { + @JS public init() {} + @JS public static func wrap(_ value: T) -> [T] { + [value] + } + + @JS public func summary( + _ values: [T], + _ fail: Bool + ) throws(JSException) -> ExportGenericPoint { + if fail { throw JSException(message: "summary failed") } + return ExportGenericPoint(x: values.count, y: values.count * 2) + } + + @JS public func map( + _ values: [T], + _ transform: (T, Int) -> U + ) -> [U] { + values.enumerated().map { transform($0.element, $0.offset) } + } + + @JS public func mapAsync( + _ values: [T], + _ transform: (T) async -> U + ) async -> [U] { + var result: [U] = [] + for value in values { result.append(await transform(value)) } + return result + } +} + +@JS public enum ExportGenericMethodFactory { + case primary + @JS public static func one(_ value: T) -> T { + value + } +} + +@JS public enum ExportGenericMethodNamespace { + @JS public static func make(_ value: T) -> T { + value + } +} + +@JS public func lastWrappedPointX() -> Int { _lastWrappedPoint.x } +@JS public func lastWrappedPointY() -> Int { _lastWrappedPoint.y } +@JS public func lastTag() -> Int { _lastTag } + +@JS public protocol ExportGenericGraphNode: BridgedSwiftGenericBridgeable { + var id: String { get } +} + +nonisolated(unsafe) var _lastStoredNodeID = "" + +@JS public func exportGenericStoreNode(_ node: T) -> T { + _lastStoredNodeID = node.id + return node +} + +nonisolated(unsafe) private var _nodeStore: [String: any BridgedSwiftGenericBridgeable] = [:] + +@JS +public func exportGenericLoadNode< + T: BridgedSwiftGenericBridgeable & ExportGenericGraphNode +>(_ key: String) -> T? { + _nodeStore[key] as? T +} + +@JS +public func exportGenericSaveNode< + T: BridgedSwiftGenericBridgeable & ExportGenericGraphNode +>(_ key: String, _ node: T) { + _nodeStore[key] = node +} + +@JS public func lastStoredNodeID() -> String { _lastStoredNodeID } + +@JS("ExportSite") public protocol ExportGenericSite: ExportGenericGraphNode { + var region: String { get } +} + +@JS public struct ExportGenericCampus: ExportGenericSite { + public var id: String + public var region: String + + public init(id: String, region: String) { + self.id = id + self.region = region + } +} + +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "runExportGenericTests") +@_extern(c) +func runExportGenericTests() -> Void + +@JSFunction func runExportGenericAsyncTests() async throws(JSException) + +@Suite struct ExportGenericAPITests { + @Test func exportGenerics() { + runExportGenericTests() + } + + @Test func exportAsyncGenerics() async throws { + try await runExportGenericAsyncTests() + } +} diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index acb3e23f1..5c7481135 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -200,6 +200,35 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13D #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT_extern(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT_extern(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT(_ callback: Int32, _ param1: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT_extern(callback, param1, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests1TTSi_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T, Int) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0, param1) in + #if arch(wasm32) + let param1Value = param1.bridgeJSLowerParameter() + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests1TTSi_1UT(callbackValue, param1Value, T.bridgeJSTypeID, U.bridgeJSTypeID) + return U.bridgeJSStackPop() + #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 @@ -844,6 +873,37 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7 #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT_extern(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT_extern(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT(_ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT_extern(callback, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsK1TT_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T) throws(JSException) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: T) throws(JSException) -> U in + #if arch(wasm32) + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsK1TT_1UT(callbackValue, T.bridgeJSTypeID, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() + #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 @@ -1146,6 +1206,34 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT_extern(callback, _generic0TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSa1TT_Sq1TT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type) -> ([T]) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSa1TT_Sq1TT(callbackValue, T.bridgeJSTypeID) + return Optional.bridgeJSStackPop() + #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 @@ -2578,6 +2666,95 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT_extern(resolveRef, rejectRef, callback, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYa1TT_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T) async -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: T) async -> U in + #if arch(wasm32) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYa1TT_1UT(resolveRef, rejectRef, callbackValue, T.bridgeJSTypeID, U.bridgeJSTypeID) + } + return try! _bjs_async_result_1UT(resolved) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "async_callback_result_BridgeJSRuntimeTests_1UT") +fileprivate func async_callback_result_BridgeJSRuntimeTests_1UT_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func async_callback_result_BridgeJSRuntimeTests_1UT_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func async_callback_result_BridgeJSRuntimeTests_1UT(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ _generic0TypeId: Int32) -> Void { + return async_callback_result_BridgeJSRuntimeTests_1UT_extern(valueKind, valuePayload1, valuePayload2, _generic0TypeId) +} + +func _bjs_async_result_1UT(_ value: JSValue) throws(JSException) -> U { + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + async_callback_result_BridgeJSRuntimeTests_1UT(valueKind, valuePayload1, valuePayload2, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT_extern(resolveRef, rejectRef, callback, _generic0TypeId, _generic1TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaK1TT_1UT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type, _: U.Type) -> (T) async throws(JSException) -> U { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: T) async throws(JSException) -> U in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + param0.bridgeJSStackPush() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaK1TT_1UT(resolveRef, rejectRef, callbackValue, T.bridgeJSTypeID, U.bridgeJSTypeID) + } + return try _bjs_async_result_1UT(resolved) + #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 @@ -3295,7 +3472,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { } extension JSTypedClosure where Signature == (sending JSValue) -> Void { - static func sending(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) -> Self { + public 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, @@ -4063,6 +4240,33 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1 #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT_extern(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT(_ callback: Int32, _ _generic0TypeId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT_extern(callback, _generic0TypeId) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_1TT { + static func bridgeJSLift(_ callbackId: Int32, _: T.Type) -> () -> T { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_1TT(callbackValue, T.bridgeJSTypeID) + return T.bridgeJSStackPop() + #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 @@ -4862,6 +5066,66 @@ fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) } +extension ExportGenericGraphNode where Self: _BridgedSwiftProtocolWrapper { + var id: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_ExportGenericGraphNode_id_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyExportGenericGraphNode: ExportGenericGraphNode, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyExportGenericGraphNode(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ExportGenericGraphNode_id_get") +fileprivate func bjs_ExportGenericGraphNode_id_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_ExportGenericGraphNode_id_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ExportGenericGraphNode_id_get(_ jsObject: Int32) -> Int32 { + return bjs_ExportGenericGraphNode_id_get_extern(jsObject) +} + +extension ExportGenericSite where Self: _BridgedSwiftProtocolWrapper { + var region: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_ExportGenericSite_region_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } +} + +struct AnyExportGenericSite: ExportGenericSite, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyExportGenericSite(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ExportGenericSite_region_get") +fileprivate func bjs_ExportGenericSite_region_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_ExportGenericSite_region_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ExportGenericSite_region_get(_ jsObject: Int32) -> Int32 { + return bjs_ExportGenericSite_region_get_extern(jsObject) +} + extension GenericRTPosition where Self: _BridgedSwiftProtocolWrapper { func sum() -> Int { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -6864,6 +7128,85 @@ public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { extension NestedTypeHost.Variant: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } +extension ExportGenericMethodFactory: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> ExportGenericMethodFactory { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> ExportGenericMethodFactory { + return ExportGenericMethodFactory(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .primary + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .primary: + return 0 + } + } +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodFactory_static_one") +@_cdecl("bjs_ExportGenericMethodFactory_static_one") +public func _bjs_ExportGenericMethodFactory_static_one(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodFactory_static_one") +@_cdecl("bjs_ExportGenericMethodFactory_static_one") +public func _bjs_ExportGenericMethodFactory_static_one(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodFactory_static_one_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodFactory_static_one_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = ExportGenericMethodFactory.one(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodNamespace_static_make") +@_cdecl("bjs_ExportGenericMethodNamespace_static_make") +public func _bjs_ExportGenericMethodNamespace_static_make(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodNamespace_static_make") +@_cdecl("bjs_ExportGenericMethodNamespace_static_make") +public func _bjs_ExportGenericMethodNamespace_static_make(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodNamespace_static_make_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodNamespace_static_make_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = ExportGenericMethodNamespace.make(_: value) + ret.bridgeJSStackPush() +} +#endif + extension Message: _BridgedSwiftAssociatedValueEnum { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Message { switch caseId { @@ -7909,57 +8252,333 @@ 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) +extension ExportGenericPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ExportGenericPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return ExportGenericPoint(x: x, y: y) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.label.bridgeJSStackPush() + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() } - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Library_Shelf(jsObject.bridgeJSLowerParameter()) + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ExportGenericPoint(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } - func toJSObject() -> JSObject { + public func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ExportGenericPoint())) } } #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 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ExportGenericPoint") +fileprivate func _bjs_struct_lower_ExportGenericPoint_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_ExportGenericPoint_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) +@inline(never) fileprivate func _bjs_struct_lower_ExportGenericPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ExportGenericPoint_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 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ExportGenericPoint") +fileprivate func _bjs_struct_lift_ExportGenericPoint_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { +fileprivate func _bjs_struct_lift_ExportGenericPoint_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() +@inline(never) fileprivate func _bjs_struct_lift_ExportGenericPoint() -> Int32 { + return _bjs_struct_lift_ExportGenericPoint_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 label = String.bridgeJSLiftParameter(labelBytes, labelLength) +extension ExportGenericMethodPair: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ExportGenericMethodPair { + return ExportGenericMethodPair() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ExportGenericMethodPair(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + public func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ExportGenericMethodPair())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ExportGenericMethodPair") +fileprivate func _bjs_struct_lower_ExportGenericMethodPair_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ExportGenericMethodPair_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ExportGenericMethodPair(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ExportGenericMethodPair_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ExportGenericMethodPair") +fileprivate func _bjs_struct_lift_ExportGenericMethodPair_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ExportGenericMethodPair_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ExportGenericMethodPair() -> Int32 { + return _bjs_struct_lift_ExportGenericMethodPair_extern() +} + +@_expose(wasm, "bjs_ExportGenericMethodPair_init") +@_cdecl("bjs_ExportGenericMethodPair_init") +public func _bjs_ExportGenericMethodPair_init() -> Void { + #if arch(wasm32) + let ret = ExportGenericMethodPair() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodPair_static_wrap") +@_cdecl("bjs_ExportGenericMethodPair_static_wrap") +public func _bjs_ExportGenericMethodPair_static_wrap(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodPair_static_wrap") +@_cdecl("bjs_ExportGenericMethodPair_static_wrap") +public func _bjs_ExportGenericMethodPair_static_wrap(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodPair_static_wrap_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodPair_static_wrap_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: [T] = ExportGenericMethodPair.wrap(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodPair_summary") +@_cdecl("bjs_ExportGenericMethodPair_summary") +public func _bjs_ExportGenericMethodPair_summary(_ fail: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodPair_summary") +@_cdecl("bjs_ExportGenericMethodPair_summary") +public func _bjs_ExportGenericMethodPair_summary(_ fail: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + do { + try _bjs_ExportGenericMethodPair_summary_open1(_generic0Type, fail) + } 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 +} +private func _bjs_ExportGenericMethodPair_summary_open1(_ _generic0Type: T.Type, _ fail: Int32) throws(JSException) { + let fail = Bool.bridgeJSLiftParameter(fail) + let values = Array.bridgeJSStackPop() + let _self = ExportGenericMethodPair.bridgeJSLiftParameter() + let ret = try _self.summary(_: values, _: fail) + return ret.bridgeJSLowerReturn() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodPair_map") +@_cdecl("bjs_ExportGenericMethodPair_map") +public func _bjs_ExportGenericMethodPair_map(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodPair_map") +@_cdecl("bjs_ExportGenericMethodPair_map") +public func _bjs_ExportGenericMethodPair_map(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodPair_map_open1(_generic0Type, _generic1Type, transform) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodPair_map_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) { + _bjs_ExportGenericMethodPair_map_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_ExportGenericMethodPair_map_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) { + let transform = _BJS_Closure_20BridgeJSRuntimeTests1TTSi_1UT.bridgeJSLift(transform, T.self, U.self) + let values = Array.bridgeJSStackPop() + let _self = ExportGenericMethodPair.bridgeJSLiftParameter() + let ret: [U] = _self.map(_: values, _: transform) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodPair_mapAsync") +@_cdecl("bjs_ExportGenericMethodPair_mapAsync") +public func _bjs_ExportGenericMethodPair_mapAsync(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodPair_mapAsync") +@_cdecl("bjs_ExportGenericMethodPair_mapAsync") +public func _bjs_ExportGenericMethodPair_mapAsync(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + return _bjs_ExportGenericMethodPair_mapAsync_open1(_generic0Type, _generic1Type, transform) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodPair_mapAsync_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) -> Int32 { + return _bjs_ExportGenericMethodPair_mapAsync_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_ExportGenericMethodPair_mapAsync_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) -> Int32 { + let transform = _BJS_Closure_20BridgeJSRuntimeTestsYa1TT_1UT.bridgeJSLift(transform, T.self, U.self) + let values = Array.bridgeJSStackPop() + let _self = ExportGenericMethodPair.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Sa1UT, reject: Promise_reject) { () async -> [U] in + return await _self.mapAsync(_: values, _: transform) + } +} +#endif + +extension ExportGenericCampus: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ExportGenericCampus { + let region = String.bridgeJSStackPop() + let id = String.bridgeJSStackPop() + return ExportGenericCampus(id: id, region: region) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.region.bridgeJSStackPush() + } + + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ExportGenericCampus(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + public func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ExportGenericCampus())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ExportGenericCampus") +fileprivate func _bjs_struct_lower_ExportGenericCampus_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ExportGenericCampus_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ExportGenericCampus(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ExportGenericCampus_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ExportGenericCampus") +fileprivate func _bjs_struct_lift_ExportGenericCampus_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ExportGenericCampus_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ExportGenericCampus() -> Int32 { + return _bjs_struct_lift_ExportGenericCampus_extern() +} + +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 label = String.bridgeJSLiftParameter(labelBytes, labelLength) let ret = Library.Shelf(label: label) return ret.bridgeJSLowerReturn() #else @@ -11414,96 +12033,514 @@ public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { @_cdecl("bjs_roundTripTypedPayloadResult") public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let result = TypedPayloadResult.bridgeJSLiftParameter(result) - let ret = roundTripTypedPayloadResult(_: result) - return ret.bridgeJSLowerReturn() + let result = TypedPayloadResult.bridgeJSLiftParameter(result) + let ret = roundTripTypedPayloadResult(_: 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 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") + #endif +} + +@_expose(wasm, "bjs_testPropertyHolder") +@_cdecl("bjs_testPropertyHolder") +public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let holder = PropertyHolder.bridgeJSLiftParameter(holder) + let ret = testPropertyHolder(holder: 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 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") + #endif +} + +@_expose(wasm, "bjs_makeFormatter") +@_cdecl("bjs_makeFormatter") +public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + #if arch(wasm32) + let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) + let ret = makeFormatter(prefix: prefix) + 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 base = Int.bridgeJSLiftParameter(base) + let ret = makeAdder(base: base) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericIdentity") +@_cdecl("bjs_exportGenericIdentity") +public func _bjs_exportGenericIdentity(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericIdentity") +@_cdecl("bjs_exportGenericIdentity") +public func _bjs_exportGenericIdentity(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericIdentity_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericIdentity_open1(_ _generic0Type: T.Type) { + let value = T.bridgeJSStackPop() + let ret: T = exportGenericIdentity(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericArrayIdentity") +@_cdecl("bjs_exportGenericArrayIdentity") +public func _bjs_exportGenericArrayIdentity(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericArrayIdentity") +@_cdecl("bjs_exportGenericArrayIdentity") +public func _bjs_exportGenericArrayIdentity(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericArrayIdentity_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericArrayIdentity_open1(_ _generic0Type: T.Type) { + let values = Array.bridgeJSStackPop() + let ret: [T] = exportGenericArrayIdentity(_: values) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericOptionalIdentity") +@_cdecl("bjs_exportGenericOptionalIdentity") +public func _bjs_exportGenericOptionalIdentity(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericOptionalIdentity") +@_cdecl("bjs_exportGenericOptionalIdentity") +public func _bjs_exportGenericOptionalIdentity(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericOptionalIdentity_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericOptionalIdentity_open1(_ _generic0Type: T.Type) { + let value = Optional.bridgeJSStackPop() + let ret: Optional = exportGenericOptionalIdentity(_: value) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericDictIdentity") +@_cdecl("bjs_exportGenericDictIdentity") +public func _bjs_exportGenericDictIdentity(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericDictIdentity") +@_cdecl("bjs_exportGenericDictIdentity") +public func _bjs_exportGenericDictIdentity(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericDictIdentity_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericDictIdentity_open1(_ _generic0Type: T.Type) { + let values = Dictionary.bridgeJSStackPop() + let ret: [String: T] = exportGenericDictIdentity(_: values) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericCount") +@_cdecl("bjs_exportGenericCount") +public func _bjs_exportGenericCount(_ fail: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32, _ _generic2TypeId: Int32) -> Int64 { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericCount") +@_cdecl("bjs_exportGenericCount") +public func _bjs_exportGenericCount(_ fail: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32, _ _generic2TypeId: Int32) -> Int64 { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + let _generic2Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic2TypeId)))!).takeUnretainedValue().type + do { + return try _bjs_exportGenericCount_open1(_generic0Type, _generic1Type, _generic2Type, fail) + } 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 +} +private func _bjs_exportGenericCount_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ _generic2Type: any BridgedSwiftGenericBridgeable.Type, _ fail: Int32) throws(JSException) -> Int64 { + return try _bjs_exportGenericCount_open2(_generic1Type, asT: T.self, _generic2Type, fail) +} +private func _bjs_exportGenericCount_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ _generic2Type: any BridgedSwiftGenericBridgeable.Type, _ fail: Int32) throws(JSException) -> Int64 { + return try _bjs_exportGenericCount_open3(_generic2Type, asT: T.self, asU: U.self, fail) +} +private func _bjs_exportGenericCount_open3(_ _generic2Type: V.Type, asT _generic0Type: T.Type, asU _generic1Type: U.Type, _ fail: Int32) throws(JSException) -> Int64 { + let fail = Bool.bridgeJSLiftParameter(fail) + let extra = V.bridgeJSStackPop() + let other = U.bridgeJSStackPop() + let values = Array.bridgeJSStackPop() + let ret = try exportGenericCount(_: values, _: other, _: extra, _: fail) + return ret.bridgeJSLowerReturn() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericOptionalCount") +@_cdecl("bjs_exportGenericOptionalCount") +public func _bjs_exportGenericOptionalCount(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericOptionalCount") +@_cdecl("bjs_exportGenericOptionalCount") +public func _bjs_exportGenericOptionalCount(_ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericOptionalCount_open1(_generic0Type) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericOptionalCount_open1(_ _generic0Type: T.Type) { + let values = Array.bridgeJSStackPop() + let ret = exportGenericOptionalCount(_: values) + return ret.bridgeJSLowerReturn() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericTransform") +@_cdecl("bjs_exportGenericTransform") +public func _bjs_exportGenericTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericTransform") +@_cdecl("bjs_exportGenericTransform") +public func _bjs_exportGenericTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + do { + try _bjs_exportGenericTransform_open1(_generic0Type, _generic1Type, transform) + } 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 +} +private func _bjs_exportGenericTransform_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) throws(JSException) { + try _bjs_exportGenericTransform_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_exportGenericTransform_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) throws(JSException) { + let transform = _BJS_Closure_20BridgeJSRuntimeTestsK1TT_1UT.bridgeJSLift(transform, T.self, U.self) + let value = T.bridgeJSStackPop() + let ret: U = try exportGenericTransform(_: value, _: transform) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericSelect") +@_cdecl("bjs_exportGenericSelect") +public func _bjs_exportGenericSelect(_ select: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericSelect") +@_cdecl("bjs_exportGenericSelect") +public func _bjs_exportGenericSelect(_ select: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericSelect_open1(_generic0Type, select) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericSelect_open1(_ _generic0Type: T.Type, _ select: Int32) { + let select = _BJS_Closure_20BridgeJSRuntimeTestsSa1TT_Sq1TT.bridgeJSLift(select, T.self) + let values = Array.bridgeJSStackPop() + let ret: Optional = exportGenericSelect(_: values, _: select) + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericAsyncTransform") +@_cdecl("bjs_exportGenericAsyncTransform") +public func _bjs_exportGenericAsyncTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericAsyncTransform") +@_cdecl("bjs_exportGenericAsyncTransform") +public func _bjs_exportGenericAsyncTransform(_ transform: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + return _bjs_exportGenericAsyncTransform_open1(_generic0Type, _generic1Type, transform) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_exportGenericAsyncTransform_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ transform: Int32) -> Int32 { + return _bjs_exportGenericAsyncTransform_open2(_generic1Type, asT: T.self, transform) +} +private func _bjs_exportGenericAsyncTransform_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ transform: Int32) -> Int32 { + let transform = _BJS_Closure_20BridgeJSRuntimeTestsYaK1TT_1UT.bridgeJSLift(transform, T.self, U.self) + let value = T.bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_1UT, reject: Promise_reject) { () async throws(JSException) -> U in + return try await exportGenericAsyncTransform(_: value, _: transform) + } +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericWrapPointAndTag") +@_cdecl("bjs_exportGenericWrapPointAndTag") +public func _bjs_exportGenericWrapPointAndTag(_ tag: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericWrapPointAndTag") +@_cdecl("bjs_exportGenericWrapPointAndTag") +public func _bjs_exportGenericWrapPointAndTag(_ tag: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_exportGenericWrapPointAndTag_open1(_generic0Type, tag) #else fatalError("Only available on WebAssembly") #endif } +private func _bjs_exportGenericWrapPointAndTag_open1(_ _generic0Type: T.Type, _ tag: Int32) { + let value = T.bridgeJSStackPop() + let tag = Int.bridgeJSLiftParameter(tag) + let p = ExportGenericPoint.bridgeJSLiftParameter() + let ret: T = exportGenericWrapPointAndTag(_: p, tag: tag, _: value) + ret.bridgeJSStackPush() +} +#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_lastWrappedPointX") +@_cdecl("bjs_lastWrappedPointX") +public func _bjs_lastWrappedPointX() -> Int32 { #if arch(wasm32) - 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) + let ret = lastWrappedPointX() 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_lastWrappedPointY") +@_cdecl("bjs_lastWrappedPointY") +public func _bjs_lastWrappedPointY() -> Int32 { #if arch(wasm32) - let holder = PropertyHolder.bridgeJSLiftParameter(holder) - let ret = testPropertyHolder(holder: holder) + let ret = lastWrappedPointY() 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_lastTag") +@_cdecl("bjs_lastTag") +public func _bjs_lastTag() -> Int32 { #if arch(wasm32) - resetObserverCounts() + let ret = lastTag() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getObserverStats") -@_cdecl("bjs_getObserverStats") -public func _bjs_getObserverStats() -> Void { +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericStoreNode") +@_cdecl("bjs_exportGenericStoreNode") +public func _bjs_exportGenericStoreNode(_ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericStoreNode") +@_cdecl("bjs_exportGenericStoreNode") +public func _bjs_exportGenericStoreNode(_ _generic0TypeId: Int32) -> Void { #if arch(wasm32) - let ret = getObserverStats() - return ret.bridgeJSLowerReturn() + let _generic0TypeBase = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + guard let _generic0Type = _generic0TypeBase as? any (BridgedSwiftGenericBridgeable & ExportGenericGraphNode).Type else { + fatalError("BridgeJS: type '\(_generic0TypeBase)' does not conform to required protocol(s): ExportGenericGraphNode") + } + _bjs_exportGenericStoreNode_open1(_generic0Type) #else fatalError("Only available on WebAssembly") #endif } +private func _bjs_exportGenericStoreNode_open1(_ _generic0Type: T.Type) { + let node = T.bridgeJSStackPop() + let ret: T = exportGenericStoreNode(_: node) + ret.bridgeJSStackPush() +} +#endif -@_expose(wasm, "bjs_formatName") -@_cdecl("bjs_formatName") -public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericLoadNode") +@_cdecl("bjs_exportGenericLoadNode") +public func _bjs_exportGenericLoadNode(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericLoadNode") +@_cdecl("bjs_exportGenericLoadNode") +public func _bjs_exportGenericLoadNode(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { #if arch(wasm32) - let transform = _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform) - let name = String.bridgeJSLiftParameter(nameBytes, nameLength) - let ret = formatName(_: name, transform: transform) - return ret.bridgeJSLowerReturn() + let _generic0TypeBase = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + guard let _generic0Type = _generic0TypeBase as? any (BridgedSwiftGenericBridgeable & ExportGenericGraphNode).Type else { + fatalError("BridgeJS: type '\(_generic0TypeBase)' does not conform to required protocol(s): ExportGenericGraphNode") + } + _bjs_exportGenericLoadNode_open1(_generic0Type, keyBytes, keyLength) #else fatalError("Only available on WebAssembly") #endif } +private func _bjs_exportGenericLoadNode_open1(_ _generic0Type: T.Type, _ keyBytes: Int32, _ keyLength: Int32) { + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + let ret: Optional = exportGenericLoadNode(_: key) + ret.bridgeJSStackPush() +} +#endif -@_expose(wasm, "bjs_makeFormatter") -@_cdecl("bjs_makeFormatter") -public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +#if hasFeature(Embedded) +@_expose(wasm, "bjs_exportGenericSaveNode") +@_cdecl("bjs_exportGenericSaveNode") +public func _bjs_exportGenericSaveNode(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_exportGenericSaveNode") +@_cdecl("bjs_exportGenericSaveNode") +public func _bjs_exportGenericSaveNode(_ keyBytes: Int32, _ keyLength: Int32, _ _generic0TypeId: Int32) -> Void { #if arch(wasm32) - let prefix = String.bridgeJSLiftParameter(prefixBytes, prefixLength) - let ret = makeFormatter(prefix: prefix) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let _generic0TypeBase = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + guard let _generic0Type = _generic0TypeBase as? any (BridgedSwiftGenericBridgeable & ExportGenericGraphNode).Type else { + fatalError("BridgeJS: type '\(_generic0TypeBase)' does not conform to required protocol(s): ExportGenericGraphNode") + } + _bjs_exportGenericSaveNode_open1(_generic0Type, keyBytes, keyLength) #else fatalError("Only available on WebAssembly") #endif } +private func _bjs_exportGenericSaveNode_open1(_ _generic0Type: T.Type, _ keyBytes: Int32, _ keyLength: Int32) { + let node = T.bridgeJSStackPop() + let key = String.bridgeJSLiftParameter(keyBytes, keyLength) + exportGenericSaveNode(_: key, _: node) +} +#endif -@_expose(wasm, "bjs_makeAdder") -@_cdecl("bjs_makeAdder") -public func _bjs_makeAdder(_ base: Int32) -> Int32 { +@_expose(wasm, "bjs_lastStoredNodeID") +@_cdecl("bjs_lastStoredNodeID") +public func _bjs_lastStoredNodeID() -> Void { #if arch(wasm32) - let base = Int.bridgeJSLiftParameter(base) - let ret = makeAdder(base: base) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = lastStoredNodeID() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -15289,6 +16326,228 @@ fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_NestedTypeHost_wrap_extern(pointer) } +@_expose(wasm, "bjs_ExportGenericMethodBox_init") +@_cdecl("bjs_ExportGenericMethodBox_init") +public func _bjs_ExportGenericMethodBox_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ExportGenericMethodBox() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodBox_store") +@_cdecl("bjs_ExportGenericMethodBox_store") +public func _bjs_ExportGenericMethodBox_store(_ _self: UnsafeMutableRawPointer, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodBox_store") +@_cdecl("bjs_ExportGenericMethodBox_store") +public func _bjs_ExportGenericMethodBox_store(_ _self: UnsafeMutableRawPointer, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodBox_store_open1(_generic0Type, _generic1Type, _self, callback) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodBox_store_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ _self: UnsafeMutableRawPointer, _ callback: Int32) { + _bjs_ExportGenericMethodBox_store_open2(_generic1Type, asT: T.self, _self, callback) +} +private func _bjs_ExportGenericMethodBox_store_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ _self: UnsafeMutableRawPointer, _ callback: Int32) { + let callback = _BJS_Closure_20BridgeJSRuntimeTestsK1TT_1UT.bridgeJSLift(callback, T.self, U.self) + let value = T.bridgeJSStackPop() + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + _self.store(_: value, _: callback) +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodBox_invoke") +@_cdecl("bjs_ExportGenericMethodBox_invoke") +public func _bjs_ExportGenericMethodBox_invoke(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodBox_invoke") +@_cdecl("bjs_ExportGenericMethodBox_invoke") +public func _bjs_ExportGenericMethodBox_invoke(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + do { + try _bjs_ExportGenericMethodBox_invoke_open1(_generic0Type, _self) + } 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 +} +private func _bjs_ExportGenericMethodBox_invoke_open1(_ _generic0Type: T.Type, _ _self: UnsafeMutableRawPointer) throws(JSException) { + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + let ret: Optional = try _self.invoke() + ret.bridgeJSStackPush() +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodBox_storeAsync") +@_cdecl("bjs_ExportGenericMethodBox_storeAsync") +public func _bjs_ExportGenericMethodBox_storeAsync(_ _self: UnsafeMutableRawPointer, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodBox_storeAsync") +@_cdecl("bjs_ExportGenericMethodBox_storeAsync") +public func _bjs_ExportGenericMethodBox_storeAsync(_ _self: UnsafeMutableRawPointer, _ callback: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + let _generic1Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic1TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodBox_storeAsync_open1(_generic0Type, _generic1Type, _self, callback) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodBox_storeAsync_open1(_ _generic0Type: T.Type, _ _generic1Type: any BridgedSwiftGenericBridgeable.Type, _ _self: UnsafeMutableRawPointer, _ callback: Int32) { + _bjs_ExportGenericMethodBox_storeAsync_open2(_generic1Type, asT: T.self, _self, callback) +} +private func _bjs_ExportGenericMethodBox_storeAsync_open2(_ _generic1Type: U.Type, asT _generic0Type: T.Type, _ _self: UnsafeMutableRawPointer, _ callback: Int32) { + let callback = _BJS_Closure_20BridgeJSRuntimeTestsYaK1TT_1UT.bridgeJSLift(callback, T.self, U.self) + let value = T.bridgeJSStackPop() + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + _self.storeAsync(_: value, _: callback) +} +#endif + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodBox_run") +@_cdecl("bjs_ExportGenericMethodBox_run") +public func _bjs_ExportGenericMethodBox_run(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Int32 { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodBox_run") +@_cdecl("bjs_ExportGenericMethodBox_run") +public func _bjs_ExportGenericMethodBox_run(_ _self: UnsafeMutableRawPointer, _ _generic0TypeId: Int32) -> Int32 { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + return _bjs_ExportGenericMethodBox_run_open1(_generic0Type, _self) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodBox_run_open1(_ _generic0Type: T.Type, _ _self: UnsafeMutableRawPointer) -> Int32 { + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + return _bjs_makePromise(resolve: Promise_resolve_Sq1TT, reject: Promise_reject) { () async throws(JSException) -> Optional in + return try await _self.run() + } +} +#endif + +@_expose(wasm, "bjs_ExportGenericMethodBox_clear") +@_cdecl("bjs_ExportGenericMethodBox_clear") +public func _bjs_ExportGenericMethodBox_clear(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + _self.clear() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if hasFeature(Embedded) +@_expose(wasm, "bjs_ExportGenericMethodBox_static_produce") +@_cdecl("bjs_ExportGenericMethodBox_static_produce") +public func _bjs_ExportGenericMethodBox_static_produce(_ body: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Generic @JS exported functions are not supported in Embedded Swift") +} +#else +@_expose(wasm, "bjs_ExportGenericMethodBox_static_produce") +@_cdecl("bjs_ExportGenericMethodBox_static_produce") +public func _bjs_ExportGenericMethodBox_static_produce(_ body: Int32, _ _generic0TypeId: Int32) -> Void { + #if arch(wasm32) + let _generic0Type = Unmanaged.fromOpaque(UnsafeRawPointer(bitPattern: UInt(UInt32(bitPattern: _generic0TypeId)))!).takeUnretainedValue().type + _bjs_ExportGenericMethodBox_static_produce_open1(_generic0Type, body) + #else + fatalError("Only available on WebAssembly") + #endif +} +private func _bjs_ExportGenericMethodBox_static_produce_open1(_ _generic0Type: T.Type, _ body: Int32) { + let body = _BJS_Closure_20BridgeJSRuntimeTestsy_1TT.bridgeJSLift(body, T.self) + let ret: T = ExportGenericMethodBox.produce(_: body) + ret.bridgeJSStackPush() +} +#endif + +@_expose(wasm, "bjs_ExportGenericMethodBox_value_get") +@_cdecl("bjs_ExportGenericMethodBox_value_get") +public func _bjs_ExportGenericMethodBox_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + let ret = _self.value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ExportGenericMethodBox_value_set") +@_cdecl("bjs_ExportGenericMethodBox_value_set") +public func _bjs_ExportGenericMethodBox_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + let value = Int.bridgeJSLiftParameter(value) + let _self = ExportGenericMethodBox.bridgeJSLiftParameter(_self) + _self.value = value + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ExportGenericMethodBox_deinit") +@_cdecl("bjs_ExportGenericMethodBox_deinit") +public func _bjs_ExportGenericMethodBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ExportGenericMethodBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ExportGenericMethodBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ExportGenericMethodBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ExportGenericMethodBox_wrap") +fileprivate func _bjs_ExportGenericMethodBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ExportGenericMethodBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ExportGenericMethodBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ExportGenericMethodBox_wrap_extern(pointer) +} + @_expose(wasm, "bjs_Library_init") @_cdecl("bjs_Library_init") public func _bjs_Library_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { @@ -15921,6 +17180,18 @@ extension NestedTypeHost.Label: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Label.bridgeJSMakeTypeHandle() } +extension ExportGenericPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGenericPoint.bridgeJSMakeTypeHandle() +} + +extension ExportGenericMethodPair: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGenericMethodPair.bridgeJSMakeTypeHandle() +} + +extension ExportGenericCampus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGenericCampus.bridgeJSMakeTypeHandle() +} + extension Library.Shelf: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.bridgeJSMakeTypeHandle() } @@ -16037,6 +17308,10 @@ extension PriorityReference: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PriorityReference.bridgeJSMakeTypeHandle() } +extension ExportGenericMethodBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGenericMethodBox.bridgeJSMakeTypeHandle() +} + extension ImportGenericBox: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = ImportGenericBox.bridgeJSMakeTypeHandle() } @@ -16157,6 +17432,10 @@ extension NestedTypeHost.Variant: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Variant.bridgeJSMakeTypeHandle() } +extension ExportGenericMethodFactory: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExportGenericMethodFactory.bridgeJSMakeTypeHandle() +} + extension Message: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Message.bridgeJSMakeTypeHandle() } @@ -16201,6 +17480,14 @@ extension APIOptionalResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIOptionalResult.bridgeJSMakeTypeHandle() } +extension AnyExportGenericGraphNode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyExportGenericGraphNode.bridgeJSMakeTypeHandle() +} + +extension AnyExportGenericSite: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyExportGenericSite.bridgeJSMakeTypeHandle() +} + extension AnyGenericRTPosition: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = AnyGenericRTPosition.bridgeJSMakeTypeHandle() } @@ -16652,6 +17939,27 @@ func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Opt if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_1UT(_ promise: JSObject, _ value: U) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_1UT") +fileprivate func promise_resolve_BridgeJSRuntimeTests_1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_1UT(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_1UT_extern(promise, _generic0TypeId) +} + +func _$Promise_resolve_1UT(_ promise: JSObject, _ value: U) throws(JSException) -> Void { + value.bridgeJSStackPush() + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_1UT(promiseValue, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { throw error } +} + @JSFunction func Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) #if arch(wasm32) @@ -16757,6 +18065,48 @@ func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: P if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_Sq1TT(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq1TT") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq1TT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq1TT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq1TT(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq1TT_extern(promise, _generic0TypeId) +} + +func _$Promise_resolve_Sq1TT(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + value.bridgeJSStackPush() + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq1TT(promiseValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa1UT(_ promise: JSObject, _ value: [U]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa1UT") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa1UT_extern(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa1UT(_ promise: Int32, _ _generic0TypeId: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa1UT_extern(promise, _generic0TypeId) +} + +func _$Promise_resolve_Sa1UT(_ promise: JSObject, _ value: [U]) throws(JSException) -> Void { + let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa1UT(promiseValue, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { throw error } +} + @JSFunction func Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) #if arch(wasm32) @@ -18429,6 +19779,28 @@ func _$Foo_value_get(_ self: JSObject) throws(JSException) -> String { return String.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runExportGenericAsyncTests") +fileprivate func bjs_runExportGenericAsyncTests_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_runExportGenericAsyncTests_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_runExportGenericAsyncTests(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_runExportGenericAsyncTests_extern(resolveRef, rejectRef) +} + +func _$runExportGenericAsyncTests() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>.sending($0) + }) { resolveRef, rejectRef in + bjs_runExportGenericAsyncTests(resolveRef, rejectRef) + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_globalObject1_get") fileprivate func bjs_globalObject1_get_extern() -> Void @@ -21296,6 +22668,9 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { NestedStructGroupA.Metadata.bridgeJSTypeID, NestedStructGroupB.Metadata.bridgeJSTypeID, NestedTypeHost.Label.bridgeJSTypeID, + ExportGenericPoint.bridgeJSTypeID, + ExportGenericMethodPair.bridgeJSTypeID, + ExportGenericCampus.bridgeJSTypeID, Library.Shelf.bridgeJSTypeID, Library.Shelf.Divider.bridgeJSTypeID, GenericRTPoint.bridgeJSTypeID, @@ -21325,6 +22700,7 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { TagReference.bridgeJSTypeID, TagHolderReference.bridgeJSTypeID, PriorityReference.bridgeJSTypeID, + ExportGenericMethodBox.bridgeJSTypeID, ImportGenericBox.bridgeJSTypeID, Severity.bridgeJSTypeID, Shape.bridgeJSTypeID, @@ -21355,6 +22731,7 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { StaticCalculator.bridgeJSTypeID, StaticPropertyEnum.bridgeJSTypeID, NestedTypeHost.Variant.bridgeJSTypeID, + ExportGenericMethodFactory.bridgeJSTypeID, Message.bridgeJSTypeID, Library.Genre.bridgeJSTypeID, Message.Update.bridgeJSTypeID, @@ -21366,6 +22743,8 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { GenericRTOutcome.bridgeJSTypeID, OptionalAllTypesResult.bridgeJSTypeID, APIOptionalResult.bridgeJSTypeID, + AnyExportGenericGraphNode.bridgeJSTypeID, + AnyExportGenericSite.bridgeJSTypeID, AnyGenericRTPosition.bridgeJSTypeID, AnyGenericRTNode.bridgeJSTypeID, ] diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 4749c6eb3..9f6645670 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -3052,6 +3052,9 @@ "swiftCallName" : "DataProcessorManager" }, { + "conformedJSProtocols" : [ + "DataProcessor" + ], "constructor" : { "abiName" : "bjs_SwiftDataProcessor_init", "effects" : { @@ -4952,6 +4955,283 @@ ], "swiftCallName" : "NestedTypeHost" }, + { + "constructor" : { + "abiName" : "bjs_ExportGenericMethodBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "explicitAccessControl" : "public", + "isFinal" : true, + "methods" : [ + { + "abiName" : "bjs_ExportGenericMethodBox_store", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "store", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsK1TT_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_ExportGenericMethodBox_invoke", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "invoke", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_ExportGenericMethodBox_storeAsync", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "storeAsync", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaK1TT_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_ExportGenericMethodBox_run", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "run", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_ExportGenericMethodBox_clear", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "clear", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_ExportGenericMethodBox_static_produce", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "produce", + "parameters" : [ + { + "label" : "_", + "name" : "body", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_1TT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "className" : { + "_0" : "ExportGenericMethodBox" + } + } + } + ], + "name" : "ExportGenericMethodBox", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "ExportGenericMethodBox" + }, { "constructor" : { "abiName" : "bjs_Library_init", @@ -10576,17 +10856,125 @@ "cases" : [ { "associatedValues" : [ - { - "type" : { - "caseEnum" : { - "_0" : "Message.Update" - } - } - } + ], - "name" : "update" - }, - { + "name" : "primary" + } + ], + "emitStyle" : "const", + "explicitAccessControl" : "public", + "name" : "ExportGenericMethodFactory", + "staticMethods" : [ + { + "abiName" : "bjs_ExportGenericMethodFactory_static_one", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "one", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "enumName" : { + "_0" : "ExportGenericMethodFactory" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ExportGenericMethodFactory", + "tsFullPath" : "ExportGenericMethodFactory" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "explicitAccessControl" : "public", + "name" : "ExportGenericMethodNamespace", + "staticMethods" : [ + { + "abiName" : "bjs_ExportGenericMethodNamespace_static_make", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "make", + "namespace" : [ + "ExportGenericMethodNamespace" + ], + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "ExportGenericMethodNamespace" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ExportGenericMethodNamespace", + "tsFullPath" : "ExportGenericMethodNamespace" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "Message.Update" + } + } + } + ], + "name" : "update" + }, + { "associatedValues" : [ ], @@ -17647,952 +18035,1206 @@ } }, { - "abiName" : "bjs_roundTripMessage", + "abiName" : "bjs_exportGenericIdentity", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripMessage", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericIdentity", "parameters" : [ { "label" : "_", - "name" : "message", + "name" : "value", "type" : { - "associatedValueEnum" : { - "_0" : "Message" + "generic" : { + "_0" : "T" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "Message" + "generic" : { + "_0" : "T" } } }, { - "abiName" : "bjs_describeRefinedEntity", + "abiName" : "bjs_exportGenericArrayIdentity", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "describeRefinedEntity", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericArrayIdentity", "parameters" : [ { "label" : "_", - "name" : "entity", + "name" : "values", "type" : { - "swiftProtocol" : { - "_0" : "RefineEntity" + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } } }, { - "abiName" : "bjs_describeTaggedEntity", + "abiName" : "bjs_exportGenericOptionalIdentity", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "describeTaggedEntity", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericOptionalIdentity", "parameters" : [ { "label" : "_", - "name" : "entity", + "name" : "value", "type" : { - "swiftProtocol" : { - "_0" : "RefineTagged" + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { - + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_renamedEcho", + "abiName" : "bjs_exportGenericDictIdentity", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "jsName" : "renamedEcho", - "name" : "jsNameEcho", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericDictIdentity", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "values", "type" : { - "string" : { - + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } } } ], "returnType" : { - "string" : { - + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } } }, { - "abiName" : "bjs_greetName", + "abiName" : "bjs_exportGenericCount", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "jsName" : "greetName", - "name" : "greet", + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + }, + { + "name" : "V" + } + ], + "name" : "exportGenericCount", "parameters" : [ { "label" : "_", - "name" : "name", + "name" : "values", "type" : { - "string" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "other", + "type" : { + "generic" : { + "_0" : "U" + } + } + }, + { + "label" : "_", + "name" : "extra", + "type" : { + "generic" : { + "_0" : "V" + } + } + }, + { + "label" : "_", + "name" : "fail", + "type" : { + "bool" : { } } } ], "returnType" : { - "string" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } } } }, { - "abiName" : "bjs_greetCount", + "abiName" : "bjs_exportGenericOptionalCount", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "jsName" : "greetCount", - "name" : "greet", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericOptionalCount", "parameters" : [ { "label" : "_", - "name" : "count", + "name" : "values", "type" : { - "integer" : { + "array" : { "_0" : { - "isSigned" : true, - "width" : "word" + "generic" : { + "_0" : "T" + } } } } } ], "returnType" : { - "string" : { - - } + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "_1" : "null" + } } }, { - "abiName" : "bjs_roundTripPointerFields", + "abiName" : "bjs_exportGenericTransform", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripPointerFields", + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "exportGenericTransform", "parameters" : [ { "label" : "_", "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "PointerFields" + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsK1TT_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PointerFields" + "generic" : { + "_0" : "U" } } }, { - "abiName" : "bjs_testStructDefault", + "abiName" : "bjs_exportGenericSelect", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testStructDefault", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericSelect", "parameters" : [ { - "defaultValue" : { - "structLiteral" : { - "_0" : "DataPoint", - "_1" : [ - { - "name" : "x", - "value" : { - "float" : { - "_0" : 1 - } - } - }, - { - "name" : "y", - "value" : { - "float" : { - "_0" : 2 - } - } - }, - { - "name" : "label", - "value" : { - "string" : { - "_0" : "default" + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "select", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSa1TT_Sq1TT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } } - }, - { - "name" : "optCount", - "value" : { - "null" : { - - } + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" } }, - { - "name" : "optFlag", - "value" : { - "null" : { - - } - } - } - ] - } - }, - "label" : "point", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "string" : { - + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_cartToJSObject", + "abiName" : "bjs_exportGenericAsyncTransform", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "cartToJSObject", + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "exportGenericAsyncTransform", "parameters" : [ { "label" : "_", - "name" : "cart", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "CopyableCart" + "generic" : { + "_0" : "T" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaK1TT_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "jsObject" : { - + "generic" : { + "_0" : "U" } } }, { - "abiName" : "bjs_nestedCartToJSObject", + "abiName" : "bjs_exportGenericWrapPointAndTag", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "nestedCartToJSObject", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "exportGenericWrapPointAndTag", "parameters" : [ { "label" : "_", - "name" : "cart", + "name" : "p", "type" : { "swiftStruct" : { - "_0" : "CopyableNestedCart" + "_0" : "ExportGenericPoint" + } + } + }, + { + "label" : "tag", + "name" : "tag", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" } } } ], "returnType" : { - "jsObject" : { - + "generic" : { + "_0" : "T" } } }, { - "abiName" : "bjs_roundTripDataPoint", + "abiName" : "bjs_lastWrappedPointX", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataPoint", + "name" : "lastWrappedPointX", "parameters" : [ - { - "label" : "_", - "name" : "data", - "type" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } + ], "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_roundTripPublicPoint", + "abiName" : "bjs_lastWrappedPointY", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripPublicPoint", + "name" : "lastWrappedPointY", "parameters" : [ - { - "label" : "_", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - } + ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_asyncRoundTripPublicPoint", + "abiName" : "bjs_lastTag", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripPublicPoint", + "name" : "lastTag", "parameters" : [ - { - "label" : "_", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - } + ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_asyncRoundTripPublicPointThrows", + "abiName" : "bjs_exportGenericStoreNode", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "asyncRoundTripPublicPointThrows", + "genericParameters" : [ + { + "constraints" : [ + "ExportGenericGraphNode" + ], + "name" : "T" + } + ], + "name" : "exportGenericStoreNode", "parameters" : [ { "label" : "_", - "name" : "point", + "name" : "node", "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "generic" : { + "_0" : "T" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "generic" : { + "_0" : "T" } } }, { - "abiName" : "bjs_asyncStructOrThrow", + "abiName" : "bjs_exportGenericLoadNode", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "asyncStructOrThrow", + "genericParameters" : [ + { + "constraints" : [ + "ExportGenericGraphNode" + ], + "name" : "T" + } + ], + "name" : "exportGenericLoadNode", "parameters" : [ { "label" : "_", - "name" : "shouldThrow", + "name" : "key", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncCombinePublicPoints", + "abiName" : "bjs_exportGenericSaveNode", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncCombinePublicPoints", + "genericParameters" : [ + { + "constraints" : [ + "ExportGenericGraphNode" + ], + "name" : "T" + } + ], + "name" : "exportGenericSaveNode", "parameters" : [ { "label" : "_", - "name" : "a", + "name" : "key", "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "string" : { + } } }, { "label" : "_", - "name" : "b", + "name" : "node", "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "generic" : { + "_0" : "T" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "void" : { + } } }, { - "abiName" : "bjs_asyncRoundTripContact", + "abiName" : "bjs_lastStoredNodeID", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripContact", + "name" : "lastStoredNodeID", "parameters" : [ - { - "label" : "_", - "name" : "contact", - "type" : { - "swiftStruct" : { - "_0" : "Contact" - } - } - } + ], "returnType" : { - "swiftStruct" : { - "_0" : "Contact" + "string" : { + } } }, { - "abiName" : "bjs_asyncRoundTripPublicPointArray", + "abiName" : "bjs_roundTripMessage", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripPublicPointArray", + "name" : "roundTripMessage", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "message", "type" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "associatedValueEnum" : { + "_0" : "Message" } } } ], "returnType" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "associatedValueEnum" : { + "_0" : "Message" } } }, { - "abiName" : "bjs_asyncRoundTripOptionalPublicPoint", + "abiName" : "bjs_describeRefinedEntity", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalPublicPoint", + "name" : "describeRefinedEntity", "parameters" : [ { "label" : "_", - "name" : "point", + "name" : "entity", "type" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - }, - "_1" : "null" + "swiftProtocol" : { + "_0" : "RefineEntity" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - }, - "_1" : "null" + "string" : { + } } }, { - "abiName" : "bjs_asyncRoundTripPublicPointDict", + "abiName" : "bjs_describeTaggedEntity", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripPublicPointDict", + "name" : "describeTaggedEntity", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "entity", "type" : { - "dictionary" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "swiftProtocol" : { + "_0" : "RefineTagged" } } } ], "returnType" : { - "dictionary" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripContact", + "abiName" : "bjs_renamedEcho", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripContact", + "jsName" : "renamedEcho", + "name" : "jsNameEcho", "parameters" : [ { "label" : "_", - "name" : "contact", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "Contact" + "string" : { + } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "Contact" + "string" : { + } } }, { - "abiName" : "bjs_roundTripConfig", + "abiName" : "bjs_greetName", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripConfig", + "jsName" : "greetName", + "name" : "greet", "parameters" : [ { "label" : "_", - "name" : "config", + "name" : "name", "type" : { - "swiftStruct" : { - "_0" : "Config" + "string" : { + } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "Config" + "string" : { + } } }, { - "abiName" : "bjs_roundTripSessionData", + "abiName" : "bjs_greetCount", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripSessionData", + "jsName" : "greetCount", + "name" : "greet", "parameters" : [ { "label" : "_", - "name" : "session", + "name" : "count", "type" : { - "swiftStruct" : { - "_0" : "SessionData" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "SessionData" + "string" : { + } } }, { - "abiName" : "bjs_roundTripValidationReport", + "abiName" : "bjs_roundTripPointerFields", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripValidationReport", + "name" : "roundTripPointerFields", "parameters" : [ { "label" : "_", - "name" : "report", + "name" : "value", "type" : { "swiftStruct" : { - "_0" : "ValidationReport" + "_0" : "PointerFields" } } } ], "returnType" : { "swiftStruct" : { - "_0" : "ValidationReport" + "_0" : "PointerFields" } } }, { - "abiName" : "bjs_roundTripAdvancedConfig", + "abiName" : "bjs_testStructDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripAdvancedConfig", + "name" : "testStructDefault", "parameters" : [ { - "label" : "_", - "name" : "config", - "type" : { - "swiftStruct" : { - "_0" : "AdvancedConfig" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "AdvancedConfig" - } - } + "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_roundTripMeasurementConfig", + "abiName" : "bjs_cartToJSObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripMeasurementConfig", + "name" : "cartToJSObject", "parameters" : [ { "label" : "_", - "name" : "config", + "name" : "cart", "type" : { "swiftStruct" : { - "_0" : "MeasurementConfig" + "_0" : "CopyableCart" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "MeasurementConfig" + "jsObject" : { + } } }, { - "abiName" : "bjs_updateValidationReport", + "abiName" : "bjs_nestedCartToJSObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "updateValidationReport", + "name" : "nestedCartToJSObject", "parameters" : [ { "label" : "_", - "name" : "newResult", + "name" : "cart", "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "swiftStruct" : { + "_0" : "CopyableNestedCart" } } - }, + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDataPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDataPoint", + "parameters" : [ { "label" : "_", - "name" : "report", + "name" : "data", "type" : { "swiftStruct" : { - "_0" : "ValidationReport" + "_0" : "DataPoint" } } } ], "returnType" : { "swiftStruct" : { - "_0" : "ValidationReport" + "_0" : "DataPoint" } } }, { - "abiName" : "bjs_testContainerWithStruct", + "abiName" : "bjs_roundTripPublicPoint", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testContainerWithStruct", + "name" : "roundTripPublicPoint", "parameters" : [ { "label" : "_", "name" : "point", "type" : { "swiftStruct" : { - "_0" : "DataPoint" + "_0" : "PublicPoint" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Container" + "swiftStruct" : { + "_0" : "PublicPoint" } } }, { - "abiName" : "bjs_roundTripJSObjectContainer", + "abiName" : "bjs_asyncRoundTripPublicPoint", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSObjectContainer", + "name" : "asyncRoundTripPublicPoint", "parameters" : [ { "label" : "_", - "name" : "container", + "name" : "point", "type" : { "swiftStruct" : { - "_0" : "JSObjectContainer" + "_0" : "PublicPoint" } } } ], "returnType" : { "swiftStruct" : { - "_0" : "JSObjectContainer" + "_0" : "PublicPoint" } } }, { - "abiName" : "bjs_roundTripFooContainer", + "abiName" : "bjs_asyncRoundTripPublicPointThrows", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripFooContainer", + "name" : "asyncRoundTripPublicPointThrows", "parameters" : [ { "label" : "_", - "name" : "container", + "name" : "point", "type" : { "swiftStruct" : { - "_0" : "FooContainer" + "_0" : "PublicPoint" } } } ], "returnType" : { "swiftStruct" : { - "_0" : "FooContainer" + "_0" : "PublicPoint" } } }, { - "abiName" : "bjs_roundTripArrayMembers", + "abiName" : "bjs_asyncStructOrThrow", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripArrayMembers", + "name" : "asyncStructOrThrow", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "shouldThrow", "type" : { - "swiftStruct" : { - "_0" : "ArrayMembers" + "bool" : { + } } } ], "returnType" : { "swiftStruct" : { - "_0" : "ArrayMembers" + "_0" : "PublicPoint" } } }, { - "abiName" : "bjs_arrayMembersSum", + "abiName" : "bjs_asyncCombinePublicPoints", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "arrayMembersSum", + "name" : "asyncCombinePublicPoints", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "a", "type" : { "swiftStruct" : { - "_0" : "ArrayMembers" + "_0" : "PublicPoint" } } }, { "label" : "_", - "name" : "values", + "name" : "b", "type" : { - "array" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } + "swiftStruct" : { + "_0" : "PublicPoint" } } } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftStruct" : { + "_0" : "PublicPoint" } } }, { - "abiName" : "bjs_arrayMembersFirst", + "abiName" : "bjs_asyncRoundTripContact", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "arrayMembersFirst", + "name" : "asyncRoundTripContact", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "contact", "type" : { "swiftStruct" : { - "_0" : "ArrayMembers" + "_0" : "Contact" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointArray", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPointArray", + "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "points", "type" : { "array" : { "_0" : { - "string" : { - + "swiftStruct" : { + "_0" : "PublicPoint" } } } @@ -18600,27 +19242,470 @@ } ], "returnType" : { - "nullable" : { + "array" : { "_0" : { - "string" : { - + "swiftStruct" : { + "_0" : "PublicPoint" } - }, - "_1" : "null" + } } } - } - ], - "protocols" : [ + }, { - "methods" : [ - - ], - "name" : "ArrayElementProtocol", - "properties" : [ + "abiName" : "bjs_asyncRoundTripOptionalPublicPoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalPublicPoint", + "parameters" : [ { - "isReadonly" : false, - "name" : "value", + "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" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripContact", + "parameters" : [ + { + "label" : "_", + "name" : "contact", + "type" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + }, + { + "abiName" : "bjs_roundTripConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripConfig", + "parameters" : [ + { + "label" : "_", + "name" : "config", + "type" : { + "swiftStruct" : { + "_0" : "Config" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Config" + } + } + }, + { + "abiName" : "bjs_roundTripSessionData", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripSessionData", + "parameters" : [ + { + "label" : "_", + "name" : "session", + "type" : { + "swiftStruct" : { + "_0" : "SessionData" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "SessionData" + } + } + }, + { + "abiName" : "bjs_roundTripValidationReport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripValidationReport", + "parameters" : [ + { + "label" : "_", + "name" : "report", + "type" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } + }, + { + "abiName" : "bjs_roundTripAdvancedConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripAdvancedConfig", + "parameters" : [ + { + "label" : "_", + "name" : "config", + "type" : { + "swiftStruct" : { + "_0" : "AdvancedConfig" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "AdvancedConfig" + } + } + }, + { + "abiName" : "bjs_roundTripMeasurementConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMeasurementConfig", + "parameters" : [ + { + "label" : "_", + "name" : "config", + "type" : { + "swiftStruct" : { + "_0" : "MeasurementConfig" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "MeasurementConfig" + } + } + }, + { + "abiName" : "bjs_updateValidationReport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "updateValidationReport", + "parameters" : [ + { + "label" : "_", + "name" : "newResult", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + { + "label" : "_", + "name" : "report", + "type" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } + }, + { + "abiName" : "bjs_testContainerWithStruct", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testContainerWithStruct", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Container" + } + } + }, + { + "abiName" : "bjs_roundTripJSObjectContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSObjectContainer", + "parameters" : [ + { + "label" : "_", + "name" : "container", + "type" : { + "swiftStruct" : { + "_0" : "JSObjectContainer" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "JSObjectContainer" + } + } + }, + { + "abiName" : "bjs_roundTripFooContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripFooContainer", + "parameters" : [ + { + "label" : "_", + "name" : "container", + "type" : { + "swiftStruct" : { + "_0" : "FooContainer" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "FooContainer" + } + } + }, + { + "abiName" : "bjs_roundTripArrayMembers", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripArrayMembers", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "swiftStruct" : { + "_0" : "ArrayMembers" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ArrayMembers" + } + } + }, + { + "abiName" : "bjs_arrayMembersSum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "arrayMembersSum", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "swiftStruct" : { + "_0" : "ArrayMembers" + } + } + }, + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_arrayMembersFirst", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "arrayMembersFirst", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "swiftStruct" : { + "_0" : "ArrayMembers" + } + } + }, + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + { + "methods" : [ + + ], + "name" : "ArrayElementProtocol", + "properties" : [ + { + "isReadonly" : false, + "name" : "value", "type" : { "integer" : { "_0" : { @@ -18629,83 +19714,241 @@ } } } - } - ] - }, - { - "methods" : [ + } + ] + }, + { + "methods" : [ + { + "abiName" : "bjs_DataProcessor_increment", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "increment", + "parameters" : [ + { + "label" : "by", + "name" : "amount", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_getValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getValue", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_DataProcessor_setLabelElements", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setLabelElements", + "parameters" : [ + { + "label" : "_", + "name" : "labelPrefix", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "labelSuffix", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_getLabel", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getLabel", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_isEven", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "isEven", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_processGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processGreeter", + "parameters" : [ + { + "label" : "_", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_createGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createGreeter", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, { - "abiName" : "bjs_DataProcessor_increment", + "abiName" : "bjs_DataProcessor_processOptionalGreeter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "increment", + "name" : "processOptionalGreeter", "parameters" : [ { - "label" : "by", - "name" : "amount", + "label" : "_", + "name" : "greeter", "type" : { - "integer" : { + "nullable" : { "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } } ], "returnType" : { - "void" : { + "string" : { } } }, { - "abiName" : "bjs_DataProcessor_getValue", + "abiName" : "bjs_DataProcessor_createOptionalGreeter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getValue", + "name" : "createOptionalGreeter", "parameters" : [ ], "returnType" : { - "integer" : { + "nullable" : { "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_DataProcessor_setLabelElements", + "abiName" : "bjs_DataProcessor_handleAPIResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "setLabelElements", + "name" : "handleAPIResult", "parameters" : [ { "label" : "_", - "name" : "labelPrefix", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "labelSuffix", + "name" : "result", "type" : { - "string" : { - + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } } } @@ -18717,192 +19960,406 @@ } }, { - "abiName" : "bjs_DataProcessor_getLabel", + "abiName" : "bjs_DataProcessor_getAPIResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getLabel", + "name" : "getAPIResult", "parameters" : [ - ], - "returnType" : { + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "DataProcessor", + "properties" : [ + { + "isReadonly" : false, + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "name" : "optionalTag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalCount", + "type" : { + "nullable" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "direction", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalTheme", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "httpStatus", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "apiResult", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "helper", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalHelper", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ] + }, + { + "isGenericBridgeable" : true, + "methods" : [ + + ], + "name" : "ExportGenericGraphNode", + "properties" : [ + { + "isReadonly" : true, + "name" : "id", + "type" : { + "string" : { + + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "ExportGenericGraphNode" + ], + "isGenericBridgeable" : true, + "jsName" : "ExportSite", + "methods" : [ + + ], + "name" : "ExportGenericSite", + "properties" : [ + { + "isReadonly" : true, + "name" : "region", + "type" : { "string" : { } } - }, + } + ] + }, + { + "isGenericBridgeable" : true, + "methods" : [ { - "abiName" : "bjs_DataProcessor_isEven", + "abiName" : "bjs_GenericRTPosition_sum", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "isEven", + "name" : "sum", "parameters" : [ ], "returnType" : { - "bool" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } - }, + } + ], + "name" : "GenericRTPosition", + "properties" : [ { - "abiName" : "bjs_DataProcessor_processGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processGreeter", - "parameters" : [ - { - "label" : "_", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } + "isReadonly" : true, + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" } } - ], - "returnType" : { - "string" : { + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "GenericRTPosition" + ], + "isGenericBridgeable" : true, + "methods" : [ + ], + "name" : "GenericRTNode", + "properties" : [ + { + "isReadonly" : true, + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } - }, + } + ] + }, + { + "methods" : [ + + ], + "name" : "RefineIdentified", + "properties" : [ { - "abiName" : "bjs_DataProcessor_createGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createGreeter", - "parameters" : [ + "isReadonly" : true, + "name" : "id", + "type" : { + "string" : { - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" } } }, { - "abiName" : "bjs_DataProcessor_processOptionalGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalGreeter", - "parameters" : [ - { - "label" : "_", - "name" : "greeter", - "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" - } + "isReadonly" : false, + "name" : "score", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" } } - ], - "returnType" : { - "string" : { - - } } - }, + } + ] + }, + { + "methods" : [ { - "abiName" : "bjs_DataProcessor_createOptionalGreeter", + "abiName" : "bjs_RefineNamed_label", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createOptionalGreeter", + "name" : "label", "parameters" : [ ], "returnType" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } - }, + } + ], + "name" : "RefineNamed", + "properties" : [ { - "abiName" : "bjs_DataProcessor_handleAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "handleAPIResult", - "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "void" : { + "isReadonly" : true, + "name" : "name", + "type" : { + "string" : { } } - }, + } + ] + }, + { + "inheritedJSProtocols" : [ + "RefineIdentified", + "RefineNamed" + ], + "methods" : [ { - "abiName" : "bjs_DataProcessor_getAPIResult", + "abiName" : "bjs_RefineEntity_label", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getAPIResult", + "name" : "label", "parameters" : [ ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "string" : { + } } } ], - "name" : "DataProcessor", + "name" : "RefineEntity", "properties" : [ { - "isReadonly" : false, - "name" : "count", + "isReadonly" : true, + "name" : "id", "type" : { + "string" : { + + } + } + } + ] + }, + { + "inheritedJSProtocols" : [ + "RefineEntity" + ], + "methods" : [ + + ], + "name" : "RefineTagged", + "properties" : [ + + ] + }, + { + "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, @@ -18910,159 +20367,222 @@ } } } - }, - { - "isReadonly" : true, - "name" : "name", - "type" : { - "string" : { + } + ], + "name" : "JSNameTransformer", + "properties" : [ - } - } + ] + } + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_JSCoordinate_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false }, - { - "isReadonly" : false, - "name" : "optionalTag", - "type" : { - "nullable" : { - "_0" : { - "string" : { + "parameters" : [ + { + "label" : "latitude", + "name" : "latitude", + "type" : { + "double" : { - } - }, - "_1" : "null" + } } - } - }, - { - "isReadonly" : false, - "name" : "optionalCount", - "type" : { - "nullable" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - }, - "_1" : "null" + }, + { + "label" : "longitude", + "name" : "longitude", + "type" : { + "double" : { + + } } } - }, + ] + }, + "methods" : [ + + ], + "name" : "JSCoordinate", + "properties" : [ { - "isReadonly" : false, - "name" : "direction", + "isReadonly" : true, + "isStatic" : false, + "name" : "latitude", "type" : { - "nullable" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" + "double" : { + } } }, { - "isReadonly" : false, - "name" : "optionalTheme", + "isReadonly" : true, + "isStatic" : false, + "name" : "longitude", "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - }, - "_1" : "null" + "double" : { + } } - }, + } + ], + "swiftCallName" : "JSCoordinate" + }, + { + "methods" : [ + + ], + "name" : "Metadata", + "namespace" : [ + "NestedStructGroupA" + ], + "properties" : [ { - "isReadonly" : false, - "name" : "httpStatus", + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "NestedStructGroupA" + ], "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - }, - "_1" : "null" + "string" : { + } } }, { - "isReadonly" : false, - "name" : "apiResult", + "isReadonly" : true, + "isStatic" : false, + "name" : "count", + "namespace" : [ + "NestedStructGroupA" + ], "type" : { - "nullable" : { + "integer" : { "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "_1" : "null" + "isSigned" : true, + "width" : "word" + } } } - }, + } + ], + "swiftCallName" : "NestedStructGroupA.Metadata" + }, + { + "methods" : [ + + ], + "name" : "Metadata", + "namespace" : [ + "NestedStructGroupB" + ], + "properties" : [ { - "isReadonly" : false, - "name" : "helper", + "isReadonly" : true, + "isStatic" : false, + "name" : "tag", + "namespace" : [ + "NestedStructGroupB" + ], "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "string" : { + } } }, { - "isReadonly" : false, - "name" : "optionalHelper", + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "namespace" : [ + "NestedStructGroupB" + ], "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "double" : { + } } } - ] + ], + "swiftCallName" : "NestedStructGroupB.Metadata" }, { - "isGenericBridgeable" : true, + "constructor" : { + "abiName" : "bjs_NestedTypeHost_Label_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "text", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ] + }, "methods" : [ { - "abiName" : "bjs_GenericRTPosition_sum", + "abiName" : "bjs_NestedTypeHost_Label_static_untitled", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "sum", + "name" : "untitled", "parameters" : [ ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftStruct" : { + "_0" : "NestedTypeHost.Label" + } + }, + "staticContext" : { + "structName" : { + "_0" : "NestedTypeHost_Label" } } } ], - "name" : "GenericRTPosition", + "name" : "Label", + "namespace" : [ + "NestedTypeHost" + ], "properties" : [ { "isReadonly" : true, - "name" : "x", + "isStatic" : false, + "name" : "text", + "namespace" : [ + "NestedTypeHost" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "maxLength", + "staticContext" : { + "structName" : { + "_0" : "NestedTypeHost_Label" + } + }, "type" : { "integer" : { "_0" : { @@ -19072,21 +20592,20 @@ } } } - ] + ], + "swiftCallName" : "NestedTypeHost.Label" }, { - "inheritedJSProtocols" : [ - "GenericRTPosition" - ], - "isGenericBridgeable" : true, + "explicitAccessControl" : "public", "methods" : [ ], - "name" : "GenericRTNode", + "name" : "ExportGenericPoint", "properties" : [ { "isReadonly" : true, - "name" : "y", + "isStatic" : false, + "name" : "x", "type" : { "integer" : { "_0" : { @@ -19095,27 +20614,11 @@ } } } - } - ] - }, - { - "methods" : [ - - ], - "name" : "RefineIdentified", - "properties" : [ - { - "isReadonly" : true, - "name" : "id", - "type" : { - "string" : { - - } - } }, { - "isReadonly" : false, - "name" : "score", + "isReadonly" : true, + "isStatic" : false, + "name" : "y", "type" : { "integer" : { "_0" : { @@ -19125,246 +20628,272 @@ } } } - ] + ], + "swiftCallName" : "ExportGenericPoint" }, { + "constructor" : { + "abiName" : "bjs_ExportGenericMethodPair_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "explicitAccessControl" : "public", "methods" : [ { - "abiName" : "bjs_RefineNamed_label", + "abiName" : "bjs_ExportGenericMethodPair_static_wrap", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "label", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "wrap", "parameters" : [ - + { + "label" : "_", + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } } - } - } - ], - "name" : "RefineNamed", - "properties" : [ - { - "isReadonly" : true, - "name" : "name", - "type" : { - "string" : { - + }, + "staticContext" : { + "structName" : { + "_0" : "ExportGenericMethodPair" } } - } - ] - }, - { - "inheritedJSProtocols" : [ - "RefineIdentified", - "RefineNamed" - ], - "methods" : [ + }, { - "abiName" : "bjs_RefineEntity_label", + "abiName" : "bjs_ExportGenericMethodPair_summary", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "label", + "genericParameters" : [ + { + "name" : "T" + } + ], + "name" : "summary", "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "fail", + "type" : { + "bool" : { + } + } + } ], "returnType" : { - "string" : { - + "swiftStruct" : { + "_0" : "ExportGenericPoint" } } - } - ], - "name" : "RefineEntity", - "properties" : [ + }, { - "isReadonly" : true, - "name" : "id", - "type" : { - "string" : { - + "abiName" : "bjs_ExportGenericMethodPair_map", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "map", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests1TTSi_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + }, + { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "U" + } + } } } - } - ] - }, - { - "inheritedJSProtocols" : [ - "RefineEntity" - ], - "methods" : [ - - ], - "name" : "RefineTagged", - "properties" : [ - - ] - }, - { - "jsName" : "CounterTransform", - "methods" : [ + }, { - "abiName" : "bjs_JSNameTransformer_apply", + "abiName" : "bjs_ExportGenericMethodPair_mapAsync", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "apply", + "genericParameters" : [ + { + "name" : "T" + }, + { + "name" : "U" + } + ], + "name" : "mapAsync", "parameters" : [ { "label" : "_", - "name" : "value", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "label" : "_", + "name" : "transform", "type" : { - "integer" : { + "closure" : { "_0" : { - "isSigned" : true, - "width" : "word" - } + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYa1TT_1UT", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "generic" : { + "_0" : "T" + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "integer" : { + "array" : { "_0" : { - "isSigned" : true, - "width" : "word" + "generic" : { + "_0" : "U" + } } } } } ], - "name" : "JSNameTransformer", - "properties" : [ - - ] - } - ], - "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", + "name" : "ExportGenericMethodPair", "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "latitude", - "type" : { - "double" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "longitude", - "type" : { - "double" : { - - } - } - } ], - "swiftCallName" : "JSCoordinate" + "swiftCallName" : "ExportGenericMethodPair" }, { - "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" - } - } - } - } + "conformedJSProtocols" : [ + "ExportGenericSite" ], - "swiftCallName" : "NestedStructGroupA.Metadata" - }, - { + "explicitAccessControl" : "public", "methods" : [ ], - "name" : "Metadata", - "namespace" : [ - "NestedStructGroupB" - ], + "name" : "ExportGenericCampus", "properties" : [ { "isReadonly" : true, "isStatic" : false, - "name" : "tag", - "namespace" : [ - "NestedStructGroupB" - ], + "name" : "id", "type" : { "string" : { @@ -19374,101 +20903,15 @@ { "isReadonly" : true, "isStatic" : false, - "name" : "value", - "namespace" : [ - "NestedStructGroupB" - ], - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "NestedStructGroupB.Metadata" - }, - { - "constructor" : { - "abiName" : "bjs_NestedTypeHost_Label_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "text", - "name" : "text", - "type" : { - "string" : { - - } - } - } - ] - }, - "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" : [ - "NestedTypeHost" - ], - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "text", - "namespace" : [ - "NestedTypeHost" - ], + "name" : "region", "type" : { "string" : { } } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "maxLength", - "staticContext" : { - "structName" : { - "_0" : "NestedTypeHost_Label" - } - }, - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } } ], - "swiftCallName" : "NestedTypeHost.Label" + "swiftCallName" : "ExportGenericCampus" }, { "constructor" : { @@ -19601,6 +21044,9 @@ "swiftCallName" : "Library.Shelf.Divider" }, { + "conformedJSProtocols" : [ + "GenericRTNode" + ], "methods" : [ { "abiName" : "bjs_GenericRTPoint_sum", @@ -24404,6 +25850,30 @@ } ] }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runExportGenericAsyncTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + }, { "functions" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ExportGenericTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ExportGenericTests.mjs new file mode 100644 index 000000000..a72d8ec53 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ExportGenericTests.mjs @@ -0,0 +1,186 @@ +// @ts-check + +import assert from 'node:assert'; +import { BridgeTypes, GenericRTOutcomeValues } from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export async function runExportGenericAsyncTests(exports) { + let startFirst, startSecond, finishFirst, finishSecond; + const firstStarted = new Promise(resolve => { startFirst = resolve; }); + const secondStarted = new Promise(resolve => { startSecond = resolve; }); + const first = exports.exportGenericAsyncTransform(21, value => new Promise(resolve => { + finishFirst = () => resolve(String(value * 2)); + startFirst(); + }), BridgeTypes.Int, BridgeTypes.String); + const second = exports.exportGenericAsyncTransform("abc", value => new Promise(resolve => { + finishSecond = () => resolve({ x: value.length, y: 9 }); + startSecond(); + }), BridgeTypes.String, BridgeTypes.ExportGenericPoint); + await Promise.all([firstStarted, secondStarted]); + finishSecond(); + assert.deepEqual(await second, { x: 3, y: 9 }); + finishFirst(); + assert.equal(await first, "42"); + await assert.rejects( + exports.exportGenericAsyncTransform(1, async () => { throw new Error("async callback failed"); }, BridgeTypes.Int, BridgeTypes.String), + /async callback failed/ + ); + await assert.rejects( + exports.exportGenericAsyncTransform(1, () => { throw new Error("synchronous callback failed"); }, BridgeTypes.Int, BridgeTypes.String), + /synchronous callback failed/ + ); + assert.equal( + await exports.exportGenericAsyncTransform(5, async value => exports.exportGenericAsyncTransform( + "inner", async text => `${text}:${value}`, BridgeTypes.String, BridgeTypes.String + ), BridgeTypes.Int, BridgeTypes.String), + "inner:5" + ); + const pair = exports.ExportGenericMethodPair.init(); + assert.deepEqual(await pair.mapAsync([1, 2], async value => `item-${value}`, BridgeTypes.Int, BridgeTypes.String), ["item-1", "item-2"]); + const methodBox = new exports.ExportGenericMethodBox(); + methodBox.storeAsync(21, async value => String(value * 2), BridgeTypes.Int, BridgeTypes.String); + assert.equal(await methodBox.run(BridgeTypes.String), "42"); + assert.equal(await methodBox.run(BridgeTypes.Int), null); + assert.equal(await methodBox.run(BridgeTypes.String), "42"); + methodBox.clear(); + assert.equal(await methodBox.run(BridgeTypes.String), null); + methodBox.release(); +} + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export function runExportGenericTests(exports) { + assert.equal(exports.exportGenericIdentity(42, BridgeTypes.Int), 42); + assert.equal(exports.exportGenericIdentity(undefined, BridgeTypes.JSValue), undefined); + assert.equal(exports.exportGenericIdentity(2, BridgeTypes.GenericRTColor), 2); + assert.equal(exports.exportGenericIdentity("dark", BridgeTypes.GenericRTMode), "dark"); + + const outcome = { tag: GenericRTOutcomeValues.Tag.Ok, code: 42 }; + assert.deepEqual(exports.exportGenericIdentity(outcome, BridgeTypes.GenericRTOutcome), outcome); + + assert.deepEqual(exports.exportGenericArrayIdentity([1, 2, 3], BridgeTypes.Int), [1, 2, 3]); + assert.deepEqual(exports.exportGenericArrayIdentity([], BridgeTypes.Int), []); + assert.equal(exports.exportGenericOptionalIdentity(7, BridgeTypes.Int), 7); + assert.equal(exports.exportGenericOptionalIdentity(null, BridgeTypes.Int), null); + assert.deepEqual(exports.exportGenericDictIdentity({ x: 1, y: 2 }, BridgeTypes.Int), { x: 1, y: 2 }); + + assert.equal(exports.exportGenericCount([1, 2], "tag", true, false, BridgeTypes.Int, BridgeTypes.String, BridgeTypes.Bool), 2n); + assert.throws( + () => exports.exportGenericCount([1], "tag", true, true, BridgeTypes.Int, BridgeTypes.String, BridgeTypes.Bool), + /count failed/ + ); + assert.equal(exports.exportGenericCount(["a"], 1, false, false, BridgeTypes.String, BridgeTypes.Int, BridgeTypes.Bool), 1n); + assert.equal(exports.exportGenericOptionalCount([], BridgeTypes.Int), null); + assert.equal(exports.exportGenericOptionalCount(["a", "b"], BridgeTypes.String), 2); + assert.deepEqual( + exports.exportGenericTransform("abc", value => ({ x: value.length, y: 9 }), BridgeTypes.String, BridgeTypes.ExportGenericPoint), + { x: 3, y: 9 } + ); + assert.throws( + () => exports.exportGenericTransform({ x: 1, y: 2 }, () => { throw new Error("callback failed"); }, BridgeTypes.ExportGenericPoint, BridgeTypes.String), + /callback failed/ + ); + assert.equal(exports.exportGenericTransform(21, value => value * 2, BridgeTypes.Int, BridgeTypes.Int), 42); + assert.equal( + exports.exportGenericTransform(5, value => exports.exportGenericTransform( + "inner", text => `${text}:${value}`, BridgeTypes.String, BridgeTypes.String + ), BridgeTypes.Int, BridgeTypes.String), + "inner:5" + ); + assert.equal(exports.exportGenericSelect([1, 2, 3], values => values[1], BridgeTypes.Int), 2); + assert.equal(exports.exportGenericSelect([], () => null, BridgeTypes.String), null); + assert.equal(exports.ExportGenericMethodBox.produce(() => "produced", BridgeTypes.String), "produced"); + + const wrappedStruct = exports.exportGenericWrapPointAndTag({ x: 5, y: 6 }, 8, { x: 7, y: 8 }, BridgeTypes.ExportGenericPoint); + assert.equal(wrappedStruct.x, 7); + assert.equal(wrappedStruct.y, 8); + assert.equal(exports.lastWrappedPointX(), 5); + assert.equal(exports.lastWrappedPointY(), 6); + assert.equal(exports.lastTag(), 8); + + const box = new exports.ExportGenericMethodBox(); + box.value = 123; + let callbackBox; + const transformedBox = exports.exportGenericTransform(box, value => { + assert.equal(value.value, 123); + callbackBox = value; + return value; + }, BridgeTypes.ExportGenericMethodBox, BridgeTypes.ExportGenericMethodBox); + assert.equal(transformedBox.value, 123); + transformedBox.release(); + callbackBox.release(); + box.release(); + + const methodBox = new exports.ExportGenericMethodBox(); + const otherMethodBox = new exports.ExportGenericMethodBox(); + methodBox.store(21, value => String(value * 2), BridgeTypes.Int, BridgeTypes.String); + otherMethodBox.store("abc", value => ({ x: value.length, y: 5 }), BridgeTypes.String, BridgeTypes.ExportGenericPoint); + assert.equal(methodBox.invoke(BridgeTypes.String), "42"); + assert.deepEqual(otherMethodBox.invoke(BridgeTypes.ExportGenericPoint), { x: 3, y: 5 }); + assert.equal(methodBox.invoke(BridgeTypes.String), "42"); + methodBox.store("failure", () => { throw new Error("stored callback failed"); }, BridgeTypes.String, BridgeTypes.Int); + assert.throws(() => methodBox.invoke(BridgeTypes.Int), /stored callback failed/); + methodBox.store(7, value => value + 1, BridgeTypes.Int, BridgeTypes.Int); + assert.equal(methodBox.invoke(BridgeTypes.Int), 8); + methodBox.clear(); + assert.equal(methodBox.invoke(BridgeTypes.Int), null); + otherMethodBox.release(); + methodBox.release(); + + const methodPair = exports.ExportGenericMethodPair.init(); + assert.deepEqual(methodPair.map([1, 2], (value, index) => `${index}:${value}`, BridgeTypes.Int, BridgeTypes.String), ["0:1", "1:2"]); + assert.deepEqual(methodPair.summary(["a", "b"], false, BridgeTypes.String), { x: 2, y: 4 }); + assert.throws(() => methodPair.summary([1], true, BridgeTypes.Int), /summary failed/); + assert.deepEqual(methodPair.summary([1, 2, 3], false, BridgeTypes.Int), { x: 3, y: 6 }); + assert.deepEqual(exports.ExportGenericMethodPair.wrap(3, BridgeTypes.Int), [3]); + + assert.equal(exports.ExportGenericMethodFactory.one(11, BridgeTypes.Int), 11); + + assert.equal(exports.ExportGenericMethodNamespace.make(13, BridgeTypes.Int), 13); + + assert.throws( + () => exports.exportGenericIdentity(1, "NotARealToken"), + TypeError + ); + assert.equal(exports.exportGenericIdentity(7, BridgeTypes.Int), 7); + let pointRead = false; + assert.throws( + () => exports.exportGenericWrapPointAndTag({ get x() { pointRead = true; return 1; }, y: 2 }, 3, 4, "NotARealToken"), + TypeError + ); + assert.equal(pointRead, false); + assert.equal(exports.exportGenericWrapPointAndTag({ x: 9, y: 10 }, 11, 12, BridgeTypes.Int), 12); + assert.equal(exports.lastWrappedPointX(), 9); + assert.equal(exports.lastWrappedPointY(), 10); + assert.equal(exports.lastTag(), 11); + + const jsNode = { id: "javascript" }; + assert.equal(exports.exportGenericStoreNode(jsNode, BridgeTypes.ExportGenericGraphNode), jsNode); + assert.equal(exports.lastStoredNodeID(), "javascript"); + + exports.exportGenericSaveNode( + "vault", + { id: "vault", region: "north" }, + BridgeTypes.ExportGenericCampus + ); + const loadedNode = exports.exportGenericLoadNode( + "vault", + BridgeTypes.ExportGenericCampus + ); + assert.equal(loadedNode.id, "vault"); + assert.equal(loadedNode.region, "north"); + assert.equal( + exports.exportGenericLoadNode("missing", BridgeTypes.ExportGenericCampus), + null + ); + + assert.throws( + () => exports.exportGenericStoreNode(5, BridgeTypes.Int), + TypeError + ); + const campus = exports.exportGenericStoreNode( + { id: "campus-1", region: "north" }, + BridgeTypes.ExportGenericCampus + ); + assert.equal(campus.region, "north"); + assert.equal(exports.lastStoredNodeID(), "campus-1"); +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 5287df791..5762f5049 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -20,6 +20,7 @@ import { getImports as getAsyncImportImports, runAsyncWorksTests } from './Bridg 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'; +import { runExportGenericTests, runExportGenericAsyncTests } from './BridgeJSRuntimeTests/JavaScript/ExportGenericTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { @@ -146,6 +147,11 @@ export async function setupOptions(options, context) { await runAsyncWorksTests(exports); return; }, + runExportGenericAsyncTests: async () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + await runExportGenericAsyncTests(exports); + }, AsyncImportImports: getAsyncImportImports(importsContext), fetchWeatherData: (city) => { return Promise.resolve({ @@ -250,6 +256,11 @@ export async function setupOptions(options, context) { } runAliasWorks(exports); } + bridgeJSRuntimeTests["runExportGenericTests"] = () => { + const exports = getExports(); + if (!exports) { throw new Error("No exports!?"); } + runExportGenericTests(exports); + } const bridgeJSGlobalTests = importObject["BridgeJSGlobalTests"] || {}; bridgeJSGlobalTests["runJsWorksGlobal"] = () => { return BridgeJSGlobalTests_runJsWorksGlobal(); From 5c72ff8cdb52c111bc6719ce8249edfa7240b6dd Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 22 Sep 2026 16:20:30 +0200 Subject: [PATCH 3/3] Docs: Describe generic Swift exports --- Plugins/BridgeJS/README.md | 2 +- .../BridgeJS/Exporting-Swift-to-JavaScript.md | 1 + .../Exporting-Swift/Exporting-Swift-Class.md | 3 +- .../Exporting-Swift/Exporting-Swift-Enum.md | 3 +- .../Exporting-Swift-Function.md | 4 +- .../Exporting-Swift-Generics.md | 51 +++++++++++++++++++ .../Exporting-Swift-Static-Functions.md | 2 +- .../Exporting-Swift/Exporting-Swift-Struct.md | 3 +- .../Articles/BridgeJS/Supported-Types.md | 4 +- .../Articles/BridgeJS/Unsupported-Features.md | 10 ++++ 10 files changed, 75 insertions(+), 8 deletions(-) create mode 100644 Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Generics.md diff --git a/Plugins/BridgeJS/README.md b/Plugins/BridgeJS/README.md index 0905695c5..841ed22fb 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) | -| 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) | +| Generic function or method (`T`, `[T]`, `T?`, `[String: T]`) | `(value: T): T` (imports); exports add `BridgeType` tokens | Depends on `T` | ✅ ([exports](../../Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Generics.md), [imports](../../Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md)) | ### Import-specific (TypeScript -> Swift) 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 38a47ffdc..a68610e97 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 @@ -15,6 +15,7 @@ Configure your package and build for JavaScript as described in +- - - - 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 09bc51d79..41475ff57 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 @@ -234,4 +234,5 @@ Identity mode improves performance for reuse-heavy workloads (same objects cross | Static/class methods: `static func`, `class func` | ✅ (See ) | | Extension methods/properties | ✅ | | Subscripts: `subscript()` | ❌ | -| Generics | ❌ | +| Generic methods (instance and static; see ) | ✅ | +| Generic classes: `class Box` | ❌ | 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 6d7af6799..f8428b980 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 @@ -544,4 +544,5 @@ This differs from classes, which use reference semantics and share state across | Associated values: Arrays | ✅ | | Associated values: Optionals of all supported types | ✅ | | Extension static functions/properties | ✅ | -| Generics | ❌ | +| Generic static methods (see ) | ✅ | +| Generic enums: `enum Result` | ❌ | 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 098a931af..39660566c 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 @@ -169,6 +169,6 @@ export type Exports = { | Throwing JS exception: `func x() throws(JSException)` | ✅ | | Throwing any exception: `func x() throws` | ❌ | | Async methods: `func x() async` | ✅ | -| Generics | ❌ | +| Generic functions (see ) | ✅ | | Opaque types: `func x() -> some P`, `func y(_: some P)` | ❌ | -| Default parameter values: `func x(_ foo: String = "")` | ✅ (See ) | \ No newline at end of file +| Default parameter values: `func x(_ foo: String = "")` | ✅ (See ) | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Generics.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Generics.md new file mode 100644 index 000000000..1ce7d7cd1 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Generics.md @@ -0,0 +1,51 @@ +# Exporting Generic Swift APIs + +Expose generic functions, methods, and callback parameters to JavaScript. + +## Overview + +Constrain each type parameter to `BridgedSwiftGenericBridgeable`. JavaScript callers select its concrete Swift type with a token from the generated `BridgeTypes` export. + +```swift +import JavaScriptKit + +@JS public final class ValueStore { + private var values: [String: any BridgedSwiftGenericBridgeable] = [:] + + @JS public init() {} + + @JS public func put(_ key: String, _ value: T) { + values[key] = value + } + + @JS public func get(_ key: String) -> T? { + values[key] as? T + } +} +``` + +```javascript +import { BridgeTypes } from "./bridge-js.js"; + +const store = new exports.ValueStore(); +store.put("count", 42, BridgeTypes.Int); +store.put("title", "Draft", BridgeTypes.String); +store.get("count", BridgeTypes.Int); // 42 +store.get("title", BridgeTypes.String); // "Draft" +store.get("count", BridgeTypes.String); // null: stored as Int +store.release(); +``` + +Pass one token per generic parameter after the regular arguments, in declaration order. Tokens use Swift names and underscore-separated namespaces, such as `BridgeTypes.API_Building`, even when the type has a separate JavaScript name. Import `BridgeTypes` from the generated module, not the `exports` object. + +The token selects the concrete return type, including for return-only generics such as `get`. Generic values may use `T`, `[T]`, `T?`, or `[String: T]`, mixed with concrete parameters and results. See for types usable as `T`. + +### Async functions and callbacks + +Generic exports and their callback parameters may be `async` or `throws(JSException)`. Callbacks can use the same generic types; an `@escaping` callback stays alive until Swift releases it and must run on the same JavaScript runtime/thread. Use `throws(JSException)` for callbacks that throw or reject a promise. + +### Protocol constraints + +Add `@JS` protocol constraints with `T: BridgedSwiftGenericBridgeable & GraphNode`, or use `T: GraphNode` if `GraphNode` inherits `BridgedSwiftGenericBridgeable` (see ). Constraints are preserved in TypeScript; unknown or non-conforming tokens throw `TypeError` before arguments cross the bridge. + +Exported generic initializers are unsupported; use an ordinary initializer as above or a generic factory method. Imported generic `@JSClass` initializers remain supported (see ). See for other export restrictions. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Functions.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Functions.md index 1c4b22abe..06a119485 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Functions.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Functions.md @@ -162,5 +162,5 @@ const result: string = Utils.String.uppercase("world"); | Class `class func` | ✅ | | Enum `static func` | ✅ | | Namespace enum `static func` | ✅ | -| Generic static functions | ❌ | +| Generic static functions (see ) | ✅ | | Protocol static requirements | ❌ | 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 208c80a25..3140789bf 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 @@ -169,7 +169,8 @@ This differs from classes, which use reference semantics and share state across | Static properties | ✅ | | Extension methods/properties | ✅ | | Property observers (`willSet`, `didSet`) | ❌ | -| Generics | ❌ | +| Generic methods (instance and static; see ) | ✅ | +| Generic structs: `struct Pair` | ❌ | | Conformances | ❌ | ## See Also diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md index 539f7ce15..ad4cb9e0a 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md @@ -33,7 +33,9 @@ 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. +Imported `@JSFunction` and exported `@JS` functions support type parameters constrained to `BridgedSwiftGenericBridgeable`. The constraint is satisfied by all supported primitives (including fixed-width integers), `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` provides it together with the JavaScript bridge. + +See and for supported forms and constraints. ## See Also diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md index 74588b06b..72a39deb0 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md @@ -55,3 +55,13 @@ While using `@JS` types from another Swift module is supported, it is not possib ### Exporting Swift: types from another Swift package Types defined in a separate Swift package cannot yet be referenced from `@JS` declarations in your package. + +## Generic exports + + supports functions and methods, not generic initializers, generic nominal types, or generic protocol requirements. Other unsupported forms: + +- Embedded Swift, `where` clauses, default parameter values, unused generic parameters, and constraints lacking bridgeability or using non-`@JS` protocols. +- Returned, nested, `@Sendable`, or `inout` generic callbacks, including callbacks with `inout` parameters. +- Generic metatypes (`T.Type`), associated types (`T.Element`), and containers beyond `T`, `[T]`, `T?`, or `[String: T]`. Use `JSValue`, not `JSObject`, as a generic argument. + +Type tokens, Swift type names, and protocol names must be unique across linked modules; JavaScript namespaces do not disambiguate them. Direct WebAssembly calls with arbitrary type IDs are unsupported. For import support, including generic `@JSClass` initializers, see .