diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fc7392f7f..69f63a27c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,6 +3,9 @@ on: pull_request: push: branches: [main] +concurrency: + group: ${{ github.workflow }} / ${{ startsWith(github.event_name, 'pull') && github.ref_name || github.sha }} + cancel-in-progress: ${{ startsWith(github.event_name, 'pull') }} jobs: test: name: Build and Test @@ -66,6 +69,37 @@ jobs: git diff --exit-code Sources/JavaScriptKit/Runtime - run: swift test --package-path ./Plugins/PackageToJS - run: swift test --package-path ./Plugins/BridgeJS + - name: Validate BridgeJS TypeScript declarations + run: npm run check:bridgejs-dts + + test-bridgejs-against-swift-versions: + name: Test BridgeJS against Swift versions + strategy: + matrix: + entry: + - image: "swift:6.1.2" + swift-syntax-version: "601.0.0" + - image: "swift:6.2" + swift-syntax-version: "602.0.0" + runs-on: ubuntu-latest + container: + image: ${{ matrix.entry.image }} + steps: + - uses: actions/checkout@v6 + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: '20' + - name: Install TypeScript + run: npm install + - name: Validate BridgeJS TypeScript declarations + run: npm run check:bridgejs-dts + - name: Run BridgeJS tests + # NOTE: Seems like the prebuilt SwiftSyntax binaries are not compatible with + # non-macro dependents, so disable experimental prebuilts for now. + run: swift test --disable-experimental-prebuilts --package-path ./Plugins/BridgeJS + env: + BRIDGEJS_OVERRIDE_SWIFT_SYNTAX_VERSION: ${{ matrix.entry.swift-syntax-version }} native-build: # Check native build to make it easy to develop applications by Xcode @@ -85,6 +119,16 @@ jobs: env: DEVELOPER_DIR: /Applications/${{ matrix.xcode }}.app/Contents/Developer/ + prettier: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: '20' + - run: npm install + - run: npx prettier --check Runtime/src + format: runs-on: ubuntu-latest container: @@ -123,7 +167,7 @@ jobs: - uses: actions/checkout@v6 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2025-09-14-a/swift-DEVELOPMENT-SNAPSHOT-2025-09-14-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-02-02-a/swift-DEVELOPMENT-SNAPSHOT-2026-02-02-a-ubuntu22.04.tar.gz - uses: swiftwasm/setup-swiftwasm@v2 id: setup-wasm32-unknown-wasip1 with: { target: wasm32-unknown-wasip1 } diff --git a/.gitignore b/.gitignore index 8dba07278..61397cf5b 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,23 @@ xcuserdata/ Examples/*/Bundle Examples/*/package-lock.json Package.resolved -Plugins/BridgeJS/Sources/JavaScript/package-lock.json +Plugins/BridgeJS/Sources/TS2Swift/JavaScript/package-lock.json Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/**/*.actual bridge-js.config.local.json _site/ + +# AI coding agent config files +AGENTS.md +CLAUDE.md +GEMINI.md +.claude/ +.opencode/ +.cursor/ +.cursorrules +.codex/ +.aider* +.cline/ +.clinerules +.windsurf/ +.windsurfrules +.codeiumignore diff --git a/Benchmarks/README.md b/Benchmarks/README.md index f7264b6b7..65d867eba 100644 --- a/Benchmarks/README.md +++ b/Benchmarks/README.md @@ -7,7 +7,7 @@ This directory contains performance benchmarks for JavaScriptKit. Before running the benchmarks, you need to build the test suite: ```bash -JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk $SWIFT_SDK_ID js -c release +swift package --swift-sdk $SWIFT_SDK_ID js -c release ``` ## Running Benchmarks diff --git a/Benchmarks/Sources/Generated/BridgeJS.Macros.swift b/Benchmarks/Sources/Generated/BridgeJS.Macros.swift index bc2ceb32b..40fc29e91 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.Macros.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.Macros.swift @@ -4,10 +4,10 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -@_spi(Experimental) import JavaScriptKit +@_spi(BridgeJS) import JavaScriptKit -@JSFunction func benchmarkHelperNoop() throws (JSException) -> Void +@JSFunction func benchmarkHelperNoop() throws(JSException) -> Void -@JSFunction func benchmarkHelperNoopWithNumber(_ n: Double) throws (JSException) -> Void +@JSFunction func benchmarkHelperNoopWithNumber(_ n: Double) throws(JSException) -> Void -@JSFunction func benchmarkRunner(_ name: String, _ body: JSObject) throws (JSException) -> Void +@JSFunction func benchmarkRunner(_ name: String, _ body: JSObject) throws(JSException) -> Void diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 86f4c87dc..a19e2c53a 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -8,18 +8,18 @@ @_spi(BridgeJS) import JavaScriptKit extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(Int.bridgeJSStackPop()) case 2: - return .flag(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .flag(Bool.bridgeJSStackPop()) case 3: - return .rate(Float.bridgeJSLiftParameter(_swift_js_pop_f32())) + return .rate(Float.bridgeJSStackPop()) case 4: - return .precise(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) + return .precise(Double.bridgeJSStackPop()) case 5: return .info default: @@ -27,84 +27,44 @@ extension APIResult: _BridgedSwiftAssociatedValueEnum { } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0): - _swift_js_push_i32(Int32(param0)) + param0.bridgeJSStackPush() return Int32(1) case .flag(let param0): - _swift_js_push_i32(param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .rate(let param0): - _swift_js_push_f32(param0) + param0.bridgeJSStackPush() return Int32(3) case .precise(let param0): - _swift_js_push_f64(param0) + param0.bridgeJSStackPush() return Int32(4) case .info: return Int32(5) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - case .flag(let param0): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - case .rate(let param0): - _swift_js_push_tag(Int32(3)) - _swift_js_push_f32(param0) - case .precise(let param0): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - case .info: - _swift_js_push_tag(Int32(5)) - } - } } extension ComplexResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> ComplexResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ComplexResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .error(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .error(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) case 2: - return .location(Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .location(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop()) case 3: - return .status(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) case 4: - return .coordinates(Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64())) + return .coordinates(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop()) case 5: - return .comprehensive(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .comprehensive(Bool.bridgeJSStackPop(), Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), Int.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop()) case 6: return .info default: @@ -112,413 +72,310 @@ extension ComplexResult: _BridgedSwiftAssociatedValueEnum { } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .error(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) case .location(let param0, let param1, let param2): - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(2) case .status(let param0, let param1, let param2): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(3) case .coordinates(let param0, let param1, let param2): - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(4) case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + param3.bridgeJSStackPush() + param4.bridgeJSStackPush() + param5.bridgeJSStackPush() + param6.bridgeJSStackPush() + param7.bridgeJSStackPush() + param8.bridgeJSStackPush() return Int32(5) case .info: return Int32(6) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .error(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - case .location(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(3)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .coordinates(let param0, let param1, let param2): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) - case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_tag(Int32(5)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .info: - _swift_js_push_tag(Int32(6)) - } - } } extension SimpleStruct: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> SimpleStruct { - let precise = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let rate = Float.bridgeJSLiftParameter(_swift_js_pop_f32()) - let flag = Bool.bridgeJSLiftParameter(_swift_js_pop_i32()) - let count = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SimpleStruct { + let precise = Double.bridgeJSStackPop() + let rate = Float.bridgeJSStackPop() + let flag = Bool.bridgeJSStackPop() + let count = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return SimpleStruct(name: name, count: count, flag: flag, rate: rate, precise: precise) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.count)) - _swift_js_push_i32(self.flag ? 1 : 0) - _swift_js_push_f32(self.rate) - _swift_js_push_f64(self.precise) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.count.bridgeJSStackPush() + self.flag.bridgeJSStackPush() + self.rate.bridgeJSStackPush() + self.precise.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_SimpleStruct(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_SimpleStruct(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SimpleStruct())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SimpleStruct") -fileprivate func _bjs_struct_lower_SimpleStruct(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_SimpleStruct_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_SimpleStruct(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_SimpleStruct_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_SimpleStruct(_ objectId: Int32) -> Void { + return _bjs_struct_lower_SimpleStruct_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SimpleStruct") -fileprivate func _bjs_struct_lift_SimpleStruct() -> Int32 +fileprivate func _bjs_struct_lift_SimpleStruct_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_SimpleStruct() -> Int32 { +fileprivate func _bjs_struct_lift_SimpleStruct_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_SimpleStruct() -> Int32 { + return _bjs_struct_lift_SimpleStruct_extern() +} extension Address: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Address { - let zipCode = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let city = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let street = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { + let zipCode = Int.bridgeJSStackPop() + let city = String.bridgeJSStackPop() + let street = String.bridgeJSStackPop() return Address(street: street, city: city, zipCode: zipCode) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_street = self.street - __bjs_street.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_city = self.city - __bjs_city.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.zipCode)) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.street.bridgeJSStackPush() + self.city.bridgeJSStackPush() + self.zipCode.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Address())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Address") -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Address_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Address") -fileprivate func _bjs_struct_lift_Address() -> Int32 +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Address() -> Int32 { +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Address() -> Int32 { + return _bjs_struct_lift_Address_extern() +} extension Person: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Person { - let email = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32()) - let address = Address.bridgeJSLiftParameter() - let age = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Person { + let email = Optional.bridgeJSStackPop() + let address = Address.bridgeJSStackPop() + let age = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return Person(name: name, age: age, address: address, email: email) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.age)) - self.address.bridgeJSLowerReturn() + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.age.bridgeJSStackPush() + self.address.bridgeJSStackPush() let __bjs_isSome_email = self.email != nil if let __bjs_unwrapped_email = self.email { - var __bjs_str_email = __bjs_unwrapped_email - __bjs_str_email.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + __bjs_unwrapped_email.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Person(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Person(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Person())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Person") -fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Person_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Person_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Person_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Person") -fileprivate func _bjs_struct_lift_Person() -> Int32 +fileprivate func _bjs_struct_lift_Person_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Person() -> Int32 { +fileprivate func _bjs_struct_lift_Person_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Person() -> Int32 { + return _bjs_struct_lift_Person_extern() +} extension ComplexStruct: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> ComplexStruct { - let metadata = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let tags = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let score = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let active = Bool.bridgeJSLiftParameter(_swift_js_pop_i32()) - let title = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ComplexStruct { + let metadata = String.bridgeJSStackPop() + let tags = String.bridgeJSStackPop() + let score = Double.bridgeJSStackPop() + let active = Bool.bridgeJSStackPop() + let title = String.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return ComplexStruct(id: id, title: title, active: active, score: score, tags: tags, metadata: metadata) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) - var __bjs_title = self.title - __bjs_title.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(self.active ? 1 : 0) - _swift_js_push_f64(self.score) - var __bjs_tags = self.tags - __bjs_tags.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_metadata = self.metadata - __bjs_metadata.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.title.bridgeJSStackPush() + self.active.bridgeJSStackPush() + self.score.bridgeJSStackPush() + self.tags.bridgeJSStackPush() + self.metadata.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_ComplexStruct(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_ComplexStruct(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ComplexStruct())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ComplexStruct") -fileprivate func _bjs_struct_lower_ComplexStruct(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_ComplexStruct_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_ComplexStruct(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_ComplexStruct_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_ComplexStruct(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ComplexStruct_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ComplexStruct") -fileprivate func _bjs_struct_lift_ComplexStruct() -> Int32 +fileprivate func _bjs_struct_lift_ComplexStruct_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_ComplexStruct() -> Int32 { +fileprivate func _bjs_struct_lift_ComplexStruct_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_ComplexStruct() -> Int32 { + return _bjs_struct_lift_ComplexStruct_extern() +} extension Point: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Point { - let y = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let x = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() return Point(x: x, y: y) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.x) - _swift_js_push_f64(self.y) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") -fileprivate func _bjs_struct_lift_Point() -> Int32 +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Point() -> Int32 { +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} @_expose(wasm, "bjs_run") @_cdecl("bjs_run") @@ -646,12 +503,15 @@ extension EnumRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_EnumRoundtrip_wrap") -fileprivate func _bjs_EnumRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_EnumRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_EnumRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_EnumRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_EnumRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_EnumRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_ComplexResultRoundtrip_init") @_cdecl("bjs_ComplexResultRoundtrip_init") @@ -780,12 +640,15 @@ extension ComplexResultRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_ComplexResultRoundtrip_wrap") -fileprivate func _bjs_ComplexResultRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ComplexResultRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ComplexResultRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ComplexResultRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ComplexResultRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ComplexResultRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_StringRoundtrip_init") @_cdecl("bjs_StringRoundtrip_init") @@ -837,12 +700,15 @@ extension StringRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_StringRoundtrip_wrap") -fileprivate func _bjs_StringRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_StringRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_StringRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_StringRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_StringRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_StringRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_OptionalReturnRoundtrip_init") @_cdecl("bjs_OptionalReturnRoundtrip_init") @@ -961,12 +827,15 @@ extension OptionalReturnRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_OptionalReturnRoundtrip_wrap") -fileprivate func _bjs_OptionalReturnRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_OptionalReturnRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_OptionalReturnRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_OptionalReturnRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_OptionalReturnRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalReturnRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_StructRoundtrip_init") @_cdecl("bjs_StructRoundtrip_init") @@ -1125,12 +994,15 @@ extension StructRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_StructRoundtrip_wrap") -fileprivate func _bjs_StructRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_StructRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_StructRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_StructRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_StructRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_StructRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_SimpleClass_init") @_cdecl("bjs_SimpleClass_init") @@ -1266,12 +1138,15 @@ extension SimpleClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_SimpleClass_wrap") -fileprivate func _bjs_SimpleClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_SimpleClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_SimpleClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_SimpleClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_SimpleClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SimpleClass_wrap_extern(pointer) +} @_expose(wasm, "bjs_AddressClass_init") @_cdecl("bjs_AddressClass_init") @@ -1365,12 +1240,15 @@ extension AddressClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_AddressClass_wrap") -fileprivate func _bjs_AddressClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_AddressClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_AddressClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_AddressClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_AddressClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_AddressClass_wrap_extern(pointer) +} @_expose(wasm, "bjs_ClassRoundtrip_init") @_cdecl("bjs_ClassRoundtrip_init") @@ -1465,12 +1343,15 @@ extension ClassRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_ClassRoundtrip_wrap") -fileprivate func _bjs_ClassRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ClassRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClassRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClassRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ClassRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassRoundtrip_wrap_extern(pointer) +} @_expose(wasm, "bjs_ArrayRoundtrip_init") @_cdecl("bjs_ArrayRoundtrip_init") @@ -1487,16 +1368,7 @@ public func _bjs_ArrayRoundtrip_init() -> UnsafeMutableRawPointer { @_cdecl("bjs_ArrayRoundtrip_takeIntArray") public func _bjs_ArrayRoundtrip_takeIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeIntArray(_: [Int].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1507,9 +1379,7 @@ public func _bjs_ArrayRoundtrip_takeIntArray(_ _self: UnsafeMutableRawPointer) - public func _bjs_ArrayRoundtrip_makeIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeIntArray() - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1519,19 +1389,8 @@ public func _bjs_ArrayRoundtrip_makeIntArray(_ _self: UnsafeMutableRawPointer) - @_cdecl("bjs_ArrayRoundtrip_roundtripIntArray") public func _bjs_ArrayRoundtrip_roundtripIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripIntArray(_: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1542,9 +1401,7 @@ public func _bjs_ArrayRoundtrip_roundtripIntArray(_ _self: UnsafeMutableRawPoint public func _bjs_ArrayRoundtrip_makeIntArrayLarge(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeIntArrayLarge() - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1554,16 +1411,7 @@ public func _bjs_ArrayRoundtrip_makeIntArrayLarge(_ _self: UnsafeMutableRawPoint @_cdecl("bjs_ArrayRoundtrip_takeDoubleArray") public func _bjs_ArrayRoundtrip_takeDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeDoubleArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeDoubleArray(_: [Double].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1574,9 +1422,7 @@ public func _bjs_ArrayRoundtrip_takeDoubleArray(_ _self: UnsafeMutableRawPointer public func _bjs_ArrayRoundtrip_makeDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeDoubleArray() - for __bjs_elem_ret in ret { - _swift_js_push_f64(__bjs_elem_ret)} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1586,19 +1432,8 @@ public func _bjs_ArrayRoundtrip_makeDoubleArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_roundtripDoubleArray") public func _bjs_ArrayRoundtrip_roundtripDoubleArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripDoubleArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_f64(__bjs_elem_ret)} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripDoubleArray(_: [Double].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1608,16 +1443,7 @@ public func _bjs_ArrayRoundtrip_roundtripDoubleArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_takeStringArray") public func _bjs_ArrayRoundtrip_takeStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeStringArray(_: [String].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1628,12 +1454,7 @@ public func _bjs_ArrayRoundtrip_takeStringArray(_ _self: UnsafeMutableRawPointer public func _bjs_ArrayRoundtrip_makeStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeStringArray() - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1643,22 +1464,8 @@ public func _bjs_ArrayRoundtrip_makeStringArray(_ _self: UnsafeMutableRawPointer @_cdecl("bjs_ArrayRoundtrip_roundtripStringArray") public func _bjs_ArrayRoundtrip_roundtripStringArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripStringArray(_: [String].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1668,16 +1475,7 @@ public func _bjs_ArrayRoundtrip_roundtripStringArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_takePointArray") public func _bjs_ArrayRoundtrip_takePointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takePointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takePointArray(_: [Point].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1688,9 +1486,7 @@ public func _bjs_ArrayRoundtrip_takePointArray(_ _self: UnsafeMutableRawPointer) public func _bjs_ArrayRoundtrip_makePointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makePointArray() - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1700,19 +1496,8 @@ public func _bjs_ArrayRoundtrip_makePointArray(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_ArrayRoundtrip_roundtripPointArray") public func _bjs_ArrayRoundtrip_roundtripPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripPointArray(_: [Point].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1723,9 +1508,7 @@ public func _bjs_ArrayRoundtrip_roundtripPointArray(_ _self: UnsafeMutableRawPoi public func _bjs_ArrayRoundtrip_makePointArrayLarge(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makePointArrayLarge() - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1735,25 +1518,7 @@ public func _bjs_ArrayRoundtrip_makePointArrayLarge(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_ArrayRoundtrip_takeNestedIntArray") public func _bjs_ArrayRoundtrip_takeNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Int]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedIntArray(_: [[Int]].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1764,11 +1529,7 @@ public func _bjs_ArrayRoundtrip_takeNestedIntArray(_ _self: UnsafeMutableRawPoin public func _bjs_ArrayRoundtrip_makeNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeNestedIntArray() - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret_elem))} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1778,30 +1539,8 @@ public func _bjs_ArrayRoundtrip_makeNestedIntArray(_ _self: UnsafeMutableRawPoin @_cdecl("bjs_ArrayRoundtrip_roundtripNestedIntArray") public func _bjs_ArrayRoundtrip_roundtripNestedIntArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Int]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret_elem))} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedIntArray(_: [[Int]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1811,25 +1550,7 @@ public func _bjs_ArrayRoundtrip_roundtripNestedIntArray(_ _self: UnsafeMutableRa @_cdecl("bjs_ArrayRoundtrip_takeNestedPointArray") public func _bjs_ArrayRoundtrip_takeNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Point]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeNestedPointArray(_: [[Point]].bridgeJSStackPop()) #else fatalError("Only available on WebAssembly") #endif @@ -1840,11 +1561,7 @@ public func _bjs_ArrayRoundtrip_takeNestedPointArray(_ _self: UnsafeMutableRawPo public func _bjs_ArrayRoundtrip_makeNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeNestedPointArray() - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - __bjs_elem_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1854,30 +1571,8 @@ public func _bjs_ArrayRoundtrip_makeNestedPointArray(_ _self: UnsafeMutableRawPo @_cdecl("bjs_ArrayRoundtrip_roundtripNestedPointArray") public func _bjs_ArrayRoundtrip_roundtripNestedPointArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Point]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - __bjs_elem_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripNestedPointArray(_: [[Point]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -1891,12 +1586,12 @@ public func _bjs_ArrayRoundtrip_takeOptionalIntArray(_ _self: UnsafeMutableRawPo let __count = Int(_swift_js_pop_i32()) var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) + }()) #else fatalError("Only available on WebAssembly") #endif @@ -1910,8 +1605,10 @@ public func _bjs_ArrayRoundtrip_makeOptionalIntArray(_ _self: UnsafeMutableRawPo for __bjs_elem_ret in ret { let __bjs_isSome_ret_elem = __bjs_elem_ret != nil if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_unwrapped_ret_elem))} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -1926,17 +1623,19 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalIntArray(_ _self: UnsafeMutable let __count = Int(_swift_js_pop_i32()) var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) + }()) for __bjs_elem_ret in ret { let __bjs_isSome_ret_elem = __bjs_elem_ret != nil if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_unwrapped_ret_elem))} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -1951,12 +1650,12 @@ public func _bjs_ArrayRoundtrip_takeOptionalPointArray(_ _self: UnsafeMutableRaw let __count = Int(_swift_js_pop_i32()) var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) + }()) #else fatalError("Only available on WebAssembly") #endif @@ -1968,10 +1667,8 @@ public func _bjs_ArrayRoundtrip_makeOptionalPointArray(_ _self: UnsafeMutableRaw #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalPointArray() for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_elem_ret.bridgeJSStackPush() + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -1986,17 +1683,15 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalPointArray(_ _self: UnsafeMutab let __count = Int(_swift_js_pop_i32()) var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) + }()) for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_elem_ret.bridgeJSStackPush() + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") @@ -2005,24 +1700,9 @@ public func _bjs_ArrayRoundtrip_roundtripOptionalPointArray(_ _self: UnsafeMutab @_expose(wasm, "bjs_ArrayRoundtrip_takeOptionalArray") @_cdecl("bjs_ArrayRoundtrip_takeOptionalArray") -public func _bjs_ArrayRoundtrip_takeOptionalArray(_ _self: UnsafeMutableRawPointer, _ values: Int32) -> Void { +public func _bjs_ArrayRoundtrip_takeOptionalArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalArray(_: { - if values == 0 { - return Optional<[Int]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }() - } - }()) + ArrayRoundtrip.bridgeJSLiftParameter(_self).takeOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif @@ -2033,12 +1713,7 @@ public func _bjs_ArrayRoundtrip_takeOptionalArray(_ _self: UnsafeMutableRawPoint public func _bjs_ArrayRoundtrip_makeOptionalArraySome(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalArraySome() - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -2049,12 +1724,7 @@ public func _bjs_ArrayRoundtrip_makeOptionalArraySome(_ _self: UnsafeMutableRawP public func _bjs_ArrayRoundtrip_makeOptionalArrayNone(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).makeOptionalArrayNone() - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -2062,30 +1732,10 @@ public func _bjs_ArrayRoundtrip_makeOptionalArrayNone(_ _self: UnsafeMutableRawP @_expose(wasm, "bjs_ArrayRoundtrip_roundtripOptionalArray") @_cdecl("bjs_ArrayRoundtrip_roundtripOptionalArray") -public func _bjs_ArrayRoundtrip_roundtripOptionalArray(_ _self: UnsafeMutableRawPointer, _ values: Int32) -> Void { +public func _bjs_ArrayRoundtrip_roundtripOptionalArray(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalArray(_: { - if values == 0 { - return Optional<[Int]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }() - } - }()) - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + let ret = ArrayRoundtrip.bridgeJSLiftParameter(_self).roundtripOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -2109,21 +1759,27 @@ extension ArrayRoundtrip: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_ArrayRoundtrip_wrap") -fileprivate func _bjs_ArrayRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ArrayRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ArrayRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ArrayRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ArrayRoundtrip_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ArrayRoundtrip_wrap_extern(pointer) +} #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkHelperNoop") -fileprivate func bjs_benchmarkHelperNoop() -> Void +fileprivate func bjs_benchmarkHelperNoop_extern() -> Void #else -fileprivate func bjs_benchmarkHelperNoop() -> Void { +fileprivate func bjs_benchmarkHelperNoop_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_benchmarkHelperNoop() -> Void { + return bjs_benchmarkHelperNoop_extern() +} func _$benchmarkHelperNoop() throws(JSException) -> Void { bjs_benchmarkHelperNoop() @@ -2134,12 +1790,15 @@ func _$benchmarkHelperNoop() throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkHelperNoopWithNumber") -fileprivate func bjs_benchmarkHelperNoopWithNumber(_ n: Float64) -> Void +fileprivate func bjs_benchmarkHelperNoopWithNumber_extern(_ n: Float64) -> Void #else -fileprivate func bjs_benchmarkHelperNoopWithNumber(_ n: Float64) -> Void { +fileprivate func bjs_benchmarkHelperNoopWithNumber_extern(_ n: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_benchmarkHelperNoopWithNumber(_ n: Float64) -> Void { + return bjs_benchmarkHelperNoopWithNumber_extern(n) +} func _$benchmarkHelperNoopWithNumber(_ n: Double) throws(JSException) -> Void { let nValue = n.bridgeJSLowerParameter() @@ -2151,12 +1810,15 @@ func _$benchmarkHelperNoopWithNumber(_ n: Double) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkRunner") -fileprivate func bjs_benchmarkRunner(_ name: Int32, _ body: Int32) -> Void +fileprivate func bjs_benchmarkRunner_extern(_ name: Int32, _ body: Int32) -> Void #else -fileprivate func bjs_benchmarkRunner(_ name: Int32, _ body: Int32) -> Void { +fileprivate func bjs_benchmarkRunner_extern(_ name: Int32, _ body: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_benchmarkRunner(_ name: Int32, _ body: Int32) -> Void { + return bjs_benchmarkRunner_extern(name, body) +} func _$benchmarkRunner(_ name: String, _ body: JSObject) throws(JSException) -> Void { let nameValue = name.bridgeJSLowerParameter() diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index cb081ab39..eacd18cb3 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -449,12 +449,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -470,12 +471,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -491,12 +493,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "bool" : { } - } + }, + "_1" : "null" } } }, @@ -512,12 +515,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "bool" : { } - } + }, + "_1" : "null" } } }, @@ -533,12 +537,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "double" : { } - } + }, + "_1" : "null" } } }, @@ -554,12 +559,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "double" : { } - } + }, + "_1" : "null" } } }, @@ -575,12 +581,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } }, @@ -596,12 +603,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } } @@ -1844,12 +1852,13 @@ "type" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } @@ -1876,12 +1885,13 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } @@ -1902,12 +1912,13 @@ "type" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } @@ -1917,12 +1928,13 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } @@ -1943,12 +1955,13 @@ "type" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "swiftStruct" : { "_0" : "Point" } - } + }, + "_1" : "null" } } } @@ -1975,12 +1988,13 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "swiftStruct" : { "_0" : "Point" } - } + }, + "_1" : "null" } } } @@ -2001,12 +2015,13 @@ "type" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "swiftStruct" : { "_0" : "Point" } - } + }, + "_1" : "null" } } } @@ -2016,12 +2031,13 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "nullable" : { "_0" : { "swiftStruct" : { "_0" : "Point" } - } + }, + "_1" : "null" } } } @@ -2040,7 +2056,7 @@ "label" : "_", "name" : "values", "type" : { - "optional" : { + "nullable" : { "_0" : { "array" : { "_0" : { @@ -2049,7 +2065,8 @@ } } } - } + }, + "_1" : "null" } } } @@ -2072,7 +2089,7 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "array" : { "_0" : { @@ -2081,7 +2098,8 @@ } } } - } + }, + "_1" : "null" } } }, @@ -2097,7 +2115,7 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "array" : { "_0" : { @@ -2106,7 +2124,8 @@ } } } - } + }, + "_1" : "null" } } }, @@ -2123,7 +2142,7 @@ "label" : "_", "name" : "values", "type" : { - "optional" : { + "nullable" : { "_0" : { "array" : { "_0" : { @@ -2132,13 +2151,14 @@ } } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "array" : { "_0" : { @@ -2147,7 +2167,8 @@ } } } - } + }, + "_1" : "null" } } } @@ -2601,12 +2622,13 @@ "isStatic" : false, "name" : "email", "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } } @@ -2715,14 +2737,6 @@ }, "imported" : { "children" : [ - { - "functions" : [ - - ], - "types" : [ - - ] - }, { "functions" : [ { diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 339a268ee..d984555e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,6 +60,12 @@ Tests for `BridgeJS` plugin: swift test --package-path ./Plugins/BridgeJS ``` +This runs both the TS2Swift Vitest suite (TypeScript `.d.ts` -> Swift macro output) and the Swift codegen/link tests. For fast iteration on the ts2swift tool only, run Vitest directly: + +```bash +cd Plugins/BridgeJS/Sources/TS2Swift/JavaScript && npm test +``` + To update snapshot test files when expected output changes: ```bash diff --git a/Examples/ActorOnWebWorker/build.sh b/Examples/ActorOnWebWorker/build.sh index 62b31144c..4def77883 100755 --- a/Examples/ActorOnWebWorker/build.sh +++ b/Examples/ActorOnWebWorker/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" -c release \ +swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ - js --use-cdn --output ./Bundle + js --use-cdn --output ./Bundle -c release diff --git a/Examples/Basic/build.sh b/Examples/Basic/build.sh index 7b5864c44..2351f4e2d 100755 --- a/Examples/Basic/build.sh +++ b/Examples/Basic/build.sh @@ -1,3 +1,3 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" -c "${1:-debug}" js --use-cdn +swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" js --use-cdn -c "${1:-debug}" diff --git a/Examples/Embedded/build.sh b/Examples/Embedded/build.sh index 7b33e4b74..d756d8d1e 100755 --- a/Examples/Embedded/build.sh +++ b/Examples/Embedded/build.sh @@ -2,4 +2,4 @@ set -euxo pipefail package_dir="$(cd "$(dirname "$0")" && pwd)" swift package --package-path "$package_dir" \ - -c release --swift-sdk "$(swiftc -print-target-info | jq -r '.swiftCompilerTag')_wasm-embedded" js + --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}-embedded" js -c release diff --git a/Examples/ExportSwift/README.md b/Examples/ExportSwift/README.md index 57d419295..39c66f0a6 100644 --- a/Examples/ExportSwift/README.md +++ b/Examples/ExportSwift/README.md @@ -5,7 +5,7 @@ This example demonstrates how to export Swift functions to JavaScript. 1. Build the project: ```sh - env JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn + swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn ``` 2. Serve the files: diff --git a/Examples/Multithreading/build.sh b/Examples/Multithreading/build.sh index 62b31144c..4def77883 100755 --- a/Examples/Multithreading/build.sh +++ b/Examples/Multithreading/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" -c release \ +swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ - js --use-cdn --output ./Bundle + js --use-cdn --output ./Bundle -c release diff --git a/Examples/OffscrenCanvas/build.sh b/Examples/OffscrenCanvas/build.sh index 62b31144c..4def77883 100755 --- a/Examples/OffscrenCanvas/build.sh +++ b/Examples/OffscrenCanvas/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" -c release \ +swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ - js --use-cdn --output ./Bundle + js --use-cdn --output ./Bundle -c release diff --git a/Examples/PlayBridgeJS/Sources/JavaScript/app.js b/Examples/PlayBridgeJS/Sources/JavaScript/app.js index 7da78e038..5580c802d 100644 --- a/Examples/PlayBridgeJS/Sources/JavaScript/app.js +++ b/Examples/PlayBridgeJS/Sources/JavaScript/app.js @@ -268,19 +268,38 @@ export class BridgeJSPlayground { try { this.hideError(); + this.editorSystem.clearDiagnostics(); const inputs = this.editorSystem.getInputs(); const swiftCode = inputs.swift; const dtsCode = inputs.dts; // Process the code and get PlayBridgeJSOutput - const result = this.playBridgeJS.update(swiftCode, dtsCode); - - // Update outputs using the PlayBridgeJSOutput object - this.editorSystem.updateOutputs(result); - - console.log('Code generated successfully'); + const result = this.playBridgeJS.updateDetailed(swiftCode, dtsCode); + + const diagnostics = result.diagnostics; + if (diagnostics && diagnostics.length > 0) { + const mapped = diagnostics.map(d => ({ + file: d.file, + startLineNumber: d.startLine, + startColumn: d.startColumn, + endLineNumber: d.endLine, + endColumn: d.endColumn, + message: d.message + })); + this.editorSystem.showDiagnostics(mapped); + return; + } + const output = result.output; + if (output) { + // Update outputs using the PlayBridgeJSOutput object + this.editorSystem.updateOutputs(output); + this.hideError(); + console.log('Code generated successfully'); + } else { + this.showError('No output produced.'); + } } catch (error) { console.error('Error generating code:', error); this.showError('Error generating code: ' + error.message); diff --git a/Examples/PlayBridgeJS/Sources/JavaScript/editor.js b/Examples/PlayBridgeJS/Sources/JavaScript/editor.js index dc3d362eb..97e78a1f8 100644 --- a/Examples/PlayBridgeJS/Sources/JavaScript/editor.js +++ b/Examples/PlayBridgeJS/Sources/JavaScript/editor.js @@ -43,7 +43,7 @@ export class EditorSystem { language: 'swift', placeholder: '// Import Swift Macros will appear here...', readOnly: true, - modelUri: 'BridgeJS.Macros.swift' + modelUri: 'Playground.Macros.swift' }, { key: 'swift-glue', @@ -97,7 +97,7 @@ export class EditorSystem { scrollbar: { vertical: 'visible', horizontal: 'visible' }, fixedOverflowWidgets: true, renderWhitespace: 'none', - wordWrap: 'on' + wordWrap: 'off' }; // Create all editors from config @@ -206,10 +206,10 @@ export class EditorSystem { updateOutputs(result) { const outputMap = { - 'swift-glue': () => result.swiftGlue(), - 'swift-import-macros': () => result.importSwiftMacroDecls(), - 'js-generated': () => result.outputJs(), - 'dts-generated': () => result.outputDts() + 'swift-glue': () => result.swiftGlue, + 'swift-import-macros': () => result.importSwiftMacroDecls, + 'js-generated': () => result.outputJs, + 'dts-generated': () => result.outputDts }; Object.entries(outputMap).forEach(([key, getContent]) => { @@ -230,6 +230,63 @@ export class EditorSystem { }); } + clearDiagnostics() { + // Remove all diagnostics owned by the playground. + this.editors.forEach(editor => { + const model = editor.getModel(); + if (!model || typeof monaco === 'undefined') return; + monaco.editor.setModelMarkers(model, 'bridgejs', []); + }); + } + + /** + * @param {{file: string, startLineNumber: number, startColumn: number, endLineNumber?: number, endColumn?: number, message: string}[]} diagnostics + */ + showDiagnostics(diagnostics) { + if (typeof monaco === 'undefined') return; + + // Group diagnostics per model so we can set markers in batches. + const markersByModel = new Map(); + + diagnostics.forEach(diag => { + const model = this.findModelForFile(diag.file); + if (!model) return; + + const markers = markersByModel.get(model) ?? []; + const lineLength = model.getLineMaxColumn(diag.startLineNumber); + const endLine = diag.endLineNumber ?? diag.startLineNumber; + const endColumn = Math.min(lineLength, diag.endColumn ?? diag.startColumn + 1); + + markers.push({ + severity: monaco.MarkerSeverity.Error, + message: diag.message, + startLineNumber: diag.startLineNumber, + startColumn: diag.startColumn, + endLineNumber: endLine, + endColumn + }); + + markersByModel.set(model, markers); + }); + + markersByModel.forEach((markers, model) => { + monaco.editor.setModelMarkers(model, 'bridgejs', markers); + }); + } + + findModelForFile(fileName) { + const normalized = fileName.startsWith('/') ? fileName.slice(1) : fileName; + for (const editor of this.editors.values()) { + const model = editor.getModel(); + if (!model) continue; + const uriPath = model.uri.path.startsWith('/') ? model.uri.path.slice(1) : model.uri.path; + if (uriPath === normalized || uriPath.endsWith('/' + normalized)) { + return model; + } + } + return null; + } + // Utility methods getConfigByKey(key) { return [...this.config.input, ...this.config.output].find(c => c.key === key); diff --git a/Examples/PlayBridgeJS/Sources/JavaScript/styles.css b/Examples/PlayBridgeJS/Sources/JavaScript/styles.css index ab943c6e0..f8eafbec9 100644 --- a/Examples/PlayBridgeJS/Sources/JavaScript/styles.css +++ b/Examples/PlayBridgeJS/Sources/JavaScript/styles.css @@ -306,6 +306,10 @@ body { margin: 0; background-color: var(--color-fill-secondary); border-bottom: 1px solid var(--color-border); + overflow-x: auto; + overflow-y: hidden; + scrollbar-gutter: stable; + -webkit-overflow-scrolling: touch; } .tab-button { @@ -319,6 +323,8 @@ body { transition: all 0.2s ease; position: relative; border-bottom: 2px solid transparent; + flex: 0 0 auto; + white-space: nowrap; } .tab-button:hover { @@ -411,12 +417,10 @@ body { } .tab-group { - flex-wrap: wrap; + scroll-padding-inline: 12px; } .tab-button { - flex: 1; - min-width: 0; text-align: center; } @@ -447,4 +451,4 @@ body { .share-url-input { font-size: 12px; } -} \ No newline at end of file +} diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift index 221302716..4a87a6d38 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.Macros.swift @@ -4,10 +4,10 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -@_spi(Experimental) import JavaScriptKit +@_spi(BridgeJS) import JavaScriptKit -@JSFunction func createTS2Swift() throws (JSException) -> TS2Swift +@JSFunction func createTS2Swift() throws(JSException) -> TS2Swift @JSClass struct TS2Swift { - @JSFunction func convert(_ ts: String) throws (JSException) -> String + @JSFunction func convert(_ ts: String) throws(JSException) -> String } diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index f97c181d9..88cdf900e 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -7,6 +7,162 @@ @_spi(BridgeJS) import JavaScriptKit +extension PlayBridgeJSOutput: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PlayBridgeJSOutput { + let swiftGlue = String.bridgeJSStackPop() + let importSwiftMacroDecls = String.bridgeJSStackPop() + let outputDts = String.bridgeJSStackPop() + let outputJs = String.bridgeJSStackPop() + return PlayBridgeJSOutput(outputJs: outputJs, outputDts: outputDts, importSwiftMacroDecls: importSwiftMacroDecls, swiftGlue: swiftGlue) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.outputJs.bridgeJSStackPush() + self.outputDts.bridgeJSStackPush() + self.importSwiftMacroDecls.bridgeJSStackPush() + self.swiftGlue.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PlayBridgeJSOutput(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PlayBridgeJSOutput())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PlayBridgeJSOutput") +fileprivate func _bjs_struct_lower_PlayBridgeJSOutput_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PlayBridgeJSOutput_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PlayBridgeJSOutput(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PlayBridgeJSOutput_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PlayBridgeJSOutput") +fileprivate func _bjs_struct_lift_PlayBridgeJSOutput_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PlayBridgeJSOutput_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PlayBridgeJSOutput() -> Int32 { + return _bjs_struct_lift_PlayBridgeJSOutput_extern() +} + +extension PlayBridgeJSDiagnostic: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PlayBridgeJSDiagnostic { + let endColumn = Int.bridgeJSStackPop() + let endLine = Int.bridgeJSStackPop() + let startColumn = Int.bridgeJSStackPop() + let startLine = Int.bridgeJSStackPop() + let message = String.bridgeJSStackPop() + let file = String.bridgeJSStackPop() + return PlayBridgeJSDiagnostic(file: file, message: message, startLine: startLine, startColumn: startColumn, endLine: endLine, endColumn: endColumn) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.file.bridgeJSStackPush() + self.message.bridgeJSStackPush() + self.startLine.bridgeJSStackPush() + self.startColumn.bridgeJSStackPush() + self.endLine.bridgeJSStackPush() + self.endColumn.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PlayBridgeJSDiagnostic(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PlayBridgeJSDiagnostic())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PlayBridgeJSDiagnostic") +fileprivate func _bjs_struct_lower_PlayBridgeJSDiagnostic_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PlayBridgeJSDiagnostic_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PlayBridgeJSDiagnostic(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PlayBridgeJSDiagnostic_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PlayBridgeJSDiagnostic") +fileprivate func _bjs_struct_lift_PlayBridgeJSDiagnostic_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PlayBridgeJSDiagnostic_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PlayBridgeJSDiagnostic() -> Int32 { + return _bjs_struct_lift_PlayBridgeJSDiagnostic_extern() +} + +extension PlayBridgeJSResult: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PlayBridgeJSResult { + let diagnostics = [PlayBridgeJSDiagnostic].bridgeJSStackPop() + let output = Optional.bridgeJSStackPop() + return PlayBridgeJSResult(output: output, diagnostics: diagnostics) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.output.bridgeJSStackPush() + self.diagnostics.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PlayBridgeJSResult(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PlayBridgeJSResult())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PlayBridgeJSResult") +fileprivate func _bjs_struct_lower_PlayBridgeJSResult_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PlayBridgeJSResult_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PlayBridgeJSResult(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PlayBridgeJSResult_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PlayBridgeJSResult") +fileprivate func _bjs_struct_lift_PlayBridgeJSResult_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PlayBridgeJSResult_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PlayBridgeJSResult() -> Int32 { + return _bjs_struct_lift_PlayBridgeJSResult_extern() +} + @_expose(wasm, "bjs_PlayBridgeJS_init") @_cdecl("bjs_PlayBridgeJS_init") public func _bjs_PlayBridgeJS_init() -> UnsafeMutableRawPointer { @@ -18,12 +174,12 @@ public func _bjs_PlayBridgeJS_init() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_PlayBridgeJS_update") -@_cdecl("bjs_PlayBridgeJS_update") -public func _bjs_PlayBridgeJS_update(_ _self: UnsafeMutableRawPointer, _ swiftSourceBytes: Int32, _ swiftSourceLength: Int32, _ dtsSourceBytes: Int32, _ dtsSourceLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PlayBridgeJS_updateDetailed") +@_cdecl("bjs_PlayBridgeJS_updateDetailed") +public func _bjs_PlayBridgeJS_updateDetailed(_ _self: UnsafeMutableRawPointer, _ swiftSourceBytes: Int32, _ swiftSourceLength: Int32, _ dtsSourceBytes: Int32, _ dtsSourceLength: Int32) -> Void { #if arch(wasm32) do { - let ret = try PlayBridgeJS.bridgeJSLiftParameter(_self).update(swiftSource: String.bridgeJSLiftParameter(swiftSourceBytes, swiftSourceLength), dtsSource: String.bridgeJSLiftParameter(dtsSourceBytes, dtsSourceLength)) + let ret = try PlayBridgeJS.bridgeJSLiftParameter(_self).updateDetailed(swiftSource: String.bridgeJSLiftParameter(swiftSourceBytes, swiftSourceLength), dtsSource: String.bridgeJSLiftParameter(dtsSourceBytes, dtsSourceLength)) return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { @@ -36,7 +192,7 @@ public func _bjs_PlayBridgeJS_update(_ _self: UnsafeMutableRawPointer, _ swiftSo _swift_js_throw(Int32(bitPattern: $0.id)) } } - return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped + return } #else fatalError("Only available on WebAssembly") @@ -61,90 +217,27 @@ extension PlayBridgeJS: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_PlayBridgeJS_wrap") -fileprivate func _bjs_PlayBridgeJS_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PlayBridgeJS_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PlayBridgeJS_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PlayBridgeJS_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif - -@_expose(wasm, "bjs_PlayBridgeJSOutput_outputJs") -@_cdecl("bjs_PlayBridgeJSOutput_outputJs") -public func _bjs_PlayBridgeJSOutput_outputJs(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = PlayBridgeJSOutput.bridgeJSLiftParameter(_self).outputJs() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_PlayBridgeJSOutput_outputDts") -@_cdecl("bjs_PlayBridgeJSOutput_outputDts") -public func _bjs_PlayBridgeJSOutput_outputDts(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = PlayBridgeJSOutput.bridgeJSLiftParameter(_self).outputDts() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +@inline(never) fileprivate func _bjs_PlayBridgeJS_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PlayBridgeJS_wrap_extern(pointer) } -@_expose(wasm, "bjs_PlayBridgeJSOutput_importSwiftMacroDecls") -@_cdecl("bjs_PlayBridgeJSOutput_importSwiftMacroDecls") -public func _bjs_PlayBridgeJSOutput_importSwiftMacroDecls(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = PlayBridgeJSOutput.bridgeJSLiftParameter(_self).importSwiftMacroDecls() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_PlayBridgeJSOutput_swiftGlue") -@_cdecl("bjs_PlayBridgeJSOutput_swiftGlue") -public func _bjs_PlayBridgeJSOutput_swiftGlue(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = PlayBridgeJSOutput.bridgeJSLiftParameter(_self).swiftGlue() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_PlayBridgeJSOutput_deinit") -@_cdecl("bjs_PlayBridgeJSOutput_deinit") -public func _bjs_PlayBridgeJSOutput_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension PlayBridgeJSOutput: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PlayBridgeJSOutput_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "PlayBridgeJS", name: "bjs_PlayBridgeJSOutput_wrap") -fileprivate func _bjs_PlayBridgeJSOutput_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_PlayBridgeJSOutput_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_createTS2Swift") -fileprivate func bjs_createTS2Swift() -> Int32 +fileprivate func bjs_createTS2Swift_extern() -> Int32 #else -fileprivate func bjs_createTS2Swift() -> Int32 { +fileprivate func bjs_createTS2Swift_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_createTS2Swift() -> Int32 { + return bjs_createTS2Swift_extern() +} func _$createTS2Swift() throws(JSException) -> TS2Swift { let ret = bjs_createTS2Swift() @@ -156,12 +249,15 @@ func _$createTS2Swift() throws(JSException) -> TS2Swift { #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_TS2Swift_convert") -fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ ts: Int32) -> Int32 +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ ts: Int32) -> Int32 #else -fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ ts: Int32) -> Int32 { +fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ ts: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_TS2Swift_convert(_ self: Int32, _ ts: Int32) -> Int32 { + return bjs_TS2Swift_convert_extern(self, ts) +} func _$TS2Swift_convert(_ self: JSObject, _ ts: String) throws(JSException) -> String { let selfValue = self.bridgeJSLowerParameter() diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 1cf8e64c6..3046e1f01 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -15,13 +15,13 @@ }, "methods" : [ { - "abiName" : "bjs_PlayBridgeJS_update", + "abiName" : "bjs_PlayBridgeJS_updateDetailed", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : true }, - "name" : "update", + "name" : "updateDetailed", "parameters" : [ { "label" : "swiftSource", @@ -43,8 +43,8 @@ } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "PlayBridgeJSOutput" + "swiftStruct" : { + "_0" : "PlayBridgeJSResult" } } } @@ -54,97 +54,175 @@ ], "swiftCallName" : "PlayBridgeJS" - }, + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ { "methods" : [ + + ], + "name" : "PlayBridgeJSOutput", + "properties" : [ { - "abiName" : "bjs_PlayBridgeJSOutput_outputJs", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, + "isReadonly" : true, + "isStatic" : false, "name" : "outputJs", - "parameters" : [ - - ], - "returnType" : { + "type" : { "string" : { } } }, { - "abiName" : "bjs_PlayBridgeJSOutput_outputDts", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, + "isReadonly" : true, + "isStatic" : false, "name" : "outputDts", - "parameters" : [ - - ], - "returnType" : { + "type" : { "string" : { } } }, { - "abiName" : "bjs_PlayBridgeJSOutput_importSwiftMacroDecls", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, + "isReadonly" : true, + "isStatic" : false, "name" : "importSwiftMacroDecls", - "parameters" : [ - - ], - "returnType" : { + "type" : { "string" : { } } }, { - "abiName" : "bjs_PlayBridgeJSOutput_swiftGlue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, + "isReadonly" : true, + "isStatic" : false, "name" : "swiftGlue", - "parameters" : [ - - ], - "returnType" : { + "type" : { "string" : { } } } ], - "name" : "PlayBridgeJSOutput", - "properties" : [ + "swiftCallName" : "PlayBridgeJSOutput" + }, + { + "methods" : [ ], - "swiftCallName" : "PlayBridgeJSOutput" - } - ], - "enums" : [ + "name" : "PlayBridgeJSDiagnostic", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "file", + "type" : { + "string" : { - ], - "exposeToGlobal" : false, - "functions" : [ + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "message", + "type" : { + "string" : { - ], - "protocols" : [ + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "startLine", + "type" : { + "int" : { - ], - "structs" : [ + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "startColumn", + "type" : { + "int" : { + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "endLine", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "endColumn", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "PlayBridgeJSDiagnostic" + }, + { + "methods" : [ + + ], + "name" : "PlayBridgeJSResult", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "output", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "PlayBridgeJSOutput" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "diagnostics", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "PlayBridgeJSDiagnostic" + } + } + } + } + } + ], + "swiftCallName" : "PlayBridgeJSResult" + } ] }, "imported" : { @@ -191,17 +269,12 @@ "name" : "TS2Swift", "setters" : [ + ], + "staticMethods" : [ + ] } ] - }, - { - "functions" : [ - - ], - "types" : [ - - ] } ] }, diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift index 80572962a..ec9eda774 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift @@ -1,14 +1,40 @@ import JavaScriptEventLoop import JavaScriptKit import SwiftParser +import SwiftSyntax import class Foundation.JSONDecoder @JS class PlayBridgeJS { @JS init() {} - @JS func update(swiftSource: String, dtsSource: String) throws(JSException) -> PlayBridgeJSOutput { + /// Structured entry point used by the playground so JS doesn't need to parse diagnostics. + @JS func updateDetailed(swiftSource: String, dtsSource: String) throws(JSException) -> PlayBridgeJSResult { do { - return try _update(swiftSource: swiftSource, dtsSource: dtsSource) + let output = try _update(swiftSource: swiftSource, dtsSource: dtsSource) + return PlayBridgeJSResult(output: output, diagnostics: []) + } catch let error as BridgeJSCoreDiagnosticError { + let diagnostics = error.diagnostics.map { diag -> PlayBridgeJSDiagnostic in + let converter = SourceLocationConverter(fileName: diag.file, tree: diag.diagnostic.node.root) + let start = converter.location(for: diag.diagnostic.node.positionAfterSkippingLeadingTrivia) + let end = converter.location(for: diag.diagnostic.node.endPositionBeforeTrailingTrivia) + + let startLine = start.line + let startColumn = start.column + let endLine = end.line + let endColumn = max(startColumn + 1, end.column) + + return PlayBridgeJSDiagnostic( + file: diag.file, + message: diag.diagnostic.message, + startLine: startLine, + startColumn: startColumn, + endLine: endLine, + endColumn: endColumn + ) + } + return PlayBridgeJSResult(output: nil, diagnostics: diagnostics) + } catch let error as BridgeJSCoreError { + throw JSException(message: error.description) } catch let error as JSException { throw error } catch { @@ -49,23 +75,26 @@ import class Foundation.JSONDecoder swiftGlue: (importResult ?? "") + "\n\n" + (exportResult ?? "") ) } + } -@JS class PlayBridgeJSOutput { - let _outputJs: String - let _outputDts: String - let _importSwiftMacroDecls: String - let _swiftGlue: String +@JS struct PlayBridgeJSOutput { + let outputJs: String + let outputDts: String + let importSwiftMacroDecls: String + let swiftGlue: String +} - init(outputJs: String, outputDts: String, importSwiftMacroDecls: String, swiftGlue: String) { - self._outputJs = outputJs - self._outputDts = outputDts - self._importSwiftMacroDecls = importSwiftMacroDecls - self._swiftGlue = swiftGlue - } +@JS struct PlayBridgeJSDiagnostic { + let file: String + let message: String + let startLine: Int + let startColumn: Int + let endLine: Int + let endColumn: Int +} - @JS func outputJs() -> String { self._outputJs } - @JS func outputDts() -> String { self._outputDts } - @JS func importSwiftMacroDecls() -> String { self._importSwiftMacroDecls } - @JS func swiftGlue() -> String { self._swiftGlue } +@JS struct PlayBridgeJSResult { + let output: PlayBridgeJSOutput? + let diagnostics: [PlayBridgeJSDiagnostic] } diff --git a/Examples/PlayBridgeJS/build.sh b/Examples/PlayBridgeJS/build.sh index 97e4b0f95..31c07896c 100755 --- a/Examples/PlayBridgeJS/build.sh +++ b/Examples/PlayBridgeJS/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -env JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" -c "${1:-debug}" \ +swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" \ plugin --allow-writing-to-package-directory \ - js --use-cdn --output ./Bundle + js --use-cdn --output ./Bundle -c "${1:-debug}" diff --git a/Makefile b/Makefile index 135465a73..270eb9b36 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ unittest: echo "SWIFT_SDK_ID is not set. Run 'swift sdk list' and pass a matching SDK, e.g. 'make unittest SWIFT_SDK_ID='."; \ exit 2; \ } - env JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk "$(SWIFT_SDK_ID)" \ + swift package --swift-sdk "$(SWIFT_SDK_ID)" \ $(TRACING_ARGS) \ --disable-sandbox \ js test --prelude ./Tests/prelude.mjs -Xnode --expose-gc diff --git a/Package.swift b/Package.swift index 1d4c8fb06..60adb7a5f 100644 --- a/Package.swift +++ b/Package.swift @@ -9,12 +9,15 @@ let useLegacyResourceBundling = Context.environment["JAVASCRIPTKIT_USE_LEGACY_RESOURCE_BUNDLING"].flatMap(Bool.init) ?? false let testingLinkerFlags: [LinkerSetting] = [ - .unsafeFlags([ - "-Xlinker", "--stack-first", - "-Xlinker", "--global-base=524288", - "-Xlinker", "-z", - "-Xlinker", "stack-size=524288", - ]) + .unsafeFlags( + [ + "-Xlinker", "--stack-first", + "-Xlinker", "--global-base=524288", + "-Xlinker", "-z", + "-Xlinker", "stack-size=524288", + ], + .when(platforms: [.wasi]) + ) ] let package = Package( @@ -183,6 +186,7 @@ let package = Package( "bridge-js.d.ts", "bridge-js.global.d.ts", "Generated/JavaScript", + "JavaScript", ], swiftSettings: [ .enableExperimentalFeature("Extern") diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index 456a87ca0..20583865b 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.2.swift @@ -16,12 +16,15 @@ let tracingTrait = Trait( ) let testingLinkerFlags: [LinkerSetting] = [ - .unsafeFlags([ - "-Xlinker", "--stack-first", - "-Xlinker", "--global-base=524288", - "-Xlinker", "-z", - "-Xlinker", "stack-size=524288", - ]) + .unsafeFlags( + [ + "-Xlinker", "--stack-first", + "-Xlinker", "--global-base=524288", + "-Xlinker", "-z", + "-Xlinker", "stack-size=524288", + ], + .when(platforms: [.wasi]) + ) ] let package = Package( @@ -194,6 +197,7 @@ let package = Package( "bridge-js.d.ts", "bridge-js.global.d.ts", "Generated/JavaScript", + "JavaScript", ], swiftSettings: [ .enableExperimentalFeature("Extern") diff --git a/Plugins/BridgeJS/Package.swift b/Plugins/BridgeJS/Package.swift index eb675c86b..2074a8a66 100644 --- a/Plugins/BridgeJS/Package.swift +++ b/Plugins/BridgeJS/Package.swift @@ -3,11 +3,13 @@ import CompilerPluginSupport import PackageDescription +let swiftSyntaxVersion = Context.environment["BRIDGEJS_OVERRIDE_SWIFT_SYNTAX_VERSION"] ?? "600.0.1" + let package = Package( name: "BridgeJS", platforms: [.macOS(.v13)], dependencies: [ - .package(url: "https://github.com/swiftlang/swift-syntax", from: "600.0.1"), + .package(url: "https://github.com/swiftlang/swift-syntax", from: Version(swiftSyntaxVersion)!), // Development dependencies .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), ], @@ -56,8 +58,10 @@ let package = Package( "BridgeJSCore", "BridgeJSLink", "TS2Swift", + .product(name: "SwiftParser", package: "swift-syntax"), + .product(name: "SwiftSyntax", package: "swift-syntax"), ], - exclude: ["__Snapshots__", "Inputs", "MultifileInputs", "ImportMacroInputs"] + exclude: ["__Snapshots__", "Inputs"] ), .macro( name: "BridgeJSMacros", @@ -70,7 +74,7 @@ let package = Package( name: "BridgeJSMacrosTests", dependencies: [ "BridgeJSMacros", - .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"), + .product(name: "SwiftSyntaxMacrosGenericTestSupport", package: "swift-syntax"), ] ), diff --git a/Plugins/BridgeJS/README.md b/Plugins/BridgeJS/README.md index 0e84674ac..9e1e0aa08 100644 --- a/Plugins/BridgeJS/README.md +++ b/Plugins/BridgeJS/README.md @@ -1,17 +1,17 @@ # BridgeJS > [!IMPORTANT] -> This feature is still experimental, and the API may change frequently. Use at your own risk with `JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1` environment variable. +> This feature is still experimental, and the API may change frequently. Use at your own risk. > [!NOTE] -> This documentation is intended for JavaScriptKit developers, not JavaScriptKit users. For user documentation, see [Exporting Swift to JavaScript](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/exporting-swift-to-javascript) and [Importing TypeScript into Swift](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/importing-typescript-into-swift). +> This documentation is intended for JavaScriptKit developers, not JavaScriptKit users. For user documentation, see [Introducing BridgeJS](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/introducing-bridgejs), [Setting up BridgeJS](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/setting-up-bridgejs), [Exporting Swift to JavaScript](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/exporting-swift-to-javascript), [Importing JavaScript into Swift](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/importing-javascript-into-swift), and [Generating bindings from TypeScript](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/generating-from-typescript). ## Overview BridgeJS provides easy interoperability between Swift and JavaScript/TypeScript. It enables: -1. **Importing TypeScript APIs into Swift**: Use TypeScript/JavaScript APIs directly from Swift code -2. **Exporting Swift APIs to JavaScript**: Make your Swift APIs available to JavaScript code +1. **Export Swift to JavaScript** - Expose Swift functions, classes, and types to JavaScript; the plugin generates TypeScript definitions (`.d.ts`) for the exported API. +2. **Import JavaScript into Swift** - Make JavaScript/TypeScript APIs callable from Swift with macro-annotated bindings or bindings generated from a TypeScript declaration file (`bridge-js.d.ts`). The workflow is: @@ -100,7 +100,7 @@ graph LR | `Foundation.URL` | `string` | - | [#496](https://github.com/swiftwasm/JavaScriptKit/issues/496) | | Generics | - | - | [#398](https://github.com/swiftwasm/JavaScriptKit/issues/398) | -### Import-specific (TypeScript → Swift) +### Import-specific (TypeScript -> Swift) | TypeScript Type | Swift Type | Status | |:----------------|:-----------|:-------| @@ -161,14 +161,20 @@ Return values use direct Wasm returns for primitives, and imported intrinsic fun - **Structs/Arrays/Enums**: Copy semantics - data serialized across boundary. No cleanup needed. - **Closures**: Boxed on source side, released when GC'd on either side. -For detailed semantics, see the [How It Works sections](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/exporting-swift-class#How-It-Works) in the user documentation. +For detailed semantics, see the [How It Works sections](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/exporting-swift-class#how-it-works) in the user documentation. + +## Testing + +- **Full BridgeJS tests** (Swift + TS2Swift Vitest): `swift test --package-path ./Plugins/BridgeJS` +- **TS2Swift only** (fast iteration on `.d.ts` -> Swift): `npm -C Sources/TS2Swift/JavaScript test` +- **Regenerate snapshot artifacts**: `UPDATE_SNAPSHOTS=1 swift test --package-path ./Plugins/BridgeJS` ## Debug utilities `BridgeJSToolInternal` exposes pipeline stages for debugging: - `emit-skeleton` - Parse Swift files (or `-` for stdin) and print the BridgeJS skeleton as JSON. -- `emit-swift-thunks` — Read skeleton JSON (from a file or `-` for stdin) and print the generated Swift glue (export and import thunks). +- `emit-swift-thunks` - Read skeleton JSON (from a file or `-` for stdin) and print the generated Swift glue (export and import thunks). - `emit-js` / `emit-dts` - Read skeleton JSON files (or `-` for stdin) and print the .js/.d.ts Use these to inspect parser output and generated code without running the full generate/link pipeline. diff --git a/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift index aec9f3bca..3cb6dc860 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSBuildPlugin/BridgeJSBuildPlugin.swift @@ -32,6 +32,15 @@ struct BridgeJSBuildPlugin: BuildToolPlugin { inputFiles.append(configFile) } + // Include Swift files generated by other plugins applied to this + // target (available in tools-version 6.0+). This lets BridgeJS + // process @JS annotations in files produced by earlier plugins + // without requiring any extra configuration. + let pluginGeneratedSwiftFiles = target.pluginGeneratedSources.filter { + $0.pathExtension == "swift" + } + inputFiles.append(contentsOf: pluginGeneratedSwiftFiles) + let inputTSFile = target.directoryURL.appending(path: "bridge-js.d.ts") let tsconfigPath = context.package.directoryURL.appending(path: "tsconfig.json") @@ -47,7 +56,6 @@ struct BridgeJSBuildPlugin: BuildToolPlugin { ] if FileManager.default.fileExists(atPath: inputTSFile.path) { - // Add .d.ts file and tsconfig.json as inputs inputFiles.append(contentsOf: [inputTSFile, tsconfigPath]) arguments.append(contentsOf: [ "--project", @@ -55,7 +63,8 @@ struct BridgeJSBuildPlugin: BuildToolPlugin { ]) } - arguments.append(contentsOf: inputSwiftFiles.map(\.path)) + let allSwiftFiles = inputSwiftFiles + pluginGeneratedSwiftFiles + arguments.append(contentsOf: allSwiftFiles.map(\.path)) return .buildCommand( displayName: "Generate BridgeJS code", diff --git a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift index 3dce62578..a45a06188 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCommandPlugin/BridgeJSCommandPlugin.swift @@ -98,7 +98,6 @@ extension BridgeJSCommandPlugin.Context { printStderr("Generating bridge code for \(target.name)...") let generatedDirectory = target.directoryURL.appending(path: "Generated") - let generatedJavaScriptDirectory = generatedDirectory.appending(path: "JavaScript") let bridgeDtsPath = target.directoryURL.appending(path: "bridge-js.d.ts") let tsconfigPath = context.package.directoryURL.appending(path: "tsconfig.json") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 5d6545668..d974fc16d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -4,43 +4,24 @@ import SwiftSyntaxBuilder #if canImport(BridgeJSSkeleton) import BridgeJSSkeleton #endif +#if canImport(BridgeJSUtilities) +import BridgeJSUtilities +#endif public struct ClosureCodegen { public init() {} - func collectClosureSignatures(from parameters: [Parameter], into signatures: inout Set) { - for param in parameters { - collectClosureSignatures(from: param.type, into: &signatures) - } - } - - func collectClosureSignatures(from type: BridgeType, into signatures: inout Set) { - switch type { - case .closure(let signature): - signatures.insert(signature) - for paramType in signature.parameters { - collectClosureSignatures(from: paramType, into: &signatures) - } - collectClosureSignatures(from: signature.returnType, into: &signatures) - case .optional(let wrapped): - collectClosureSignatures(from: wrapped, into: &signatures) - default: - break - } + private func swiftClosureType(for signature: ClosureSignature) -> String { + let closureParams = signature.parameters.map { "\($0.swiftType)" }.joined(separator: ", ") + let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") + let swiftReturnType = signature.returnType.swiftType + return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" } func renderClosureHelpers(_ signature: ClosureSignature) throws -> [DeclSyntax] { let mangledName = signature.mangleName let helperName = "_BJS_Closure_\(mangledName)" - let boxClassName = "_BJS_ClosureBox_\(mangledName)" - - let closureParams = signature.parameters.enumerated().map { _, type in - "\(type.swiftType)" - }.joined(separator: ", ") - - let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") - let swiftReturnType = signature.returnType.swiftType - let closureType = "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" + let swiftClosureType = swiftClosureType(for: signature) let externName = "invoke_js_callback_\(signature.moduleName)_\(mangledName)" @@ -63,126 +44,77 @@ public struct ClosureCodegen { try builder.call(returnType: signature.returnType) try builder.liftReturnValue(returnType: signature.returnType) - // Get the body code - let bodyCode = builder.getBody() - // Generate extern declaration using CallJSEmission let externDecl = builder.renderImportDecl() - - let boxClassDecl: DeclSyntax = """ - private final class \(raw: boxClassName): _BridgedSwiftClosureBox { - let closure: \(raw: closureType) - init(_ closure: @escaping \(raw: closureType)) { - self.closure = closure + let externABIName = "make_swift_closure_\(signature.moduleName)_\(signature.mangleName)" + let externDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: externDeclPrinter, + moduleName: "bjs", + abiName: externABIName, + functionName: externABIName, + signature: "(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32", + parameterNames: ["boxPtr", "file", "line"] + ) + let makeClosureExternDecl: DeclSyntax = "\(raw: externDeclPrinter.lines.joined(separator: "\n"))" + + let helperEnumDeclPrinter = CodeFragmentPrinter() + helperEnumDeclPrinter.write("private enum \(helperName) {") + helperEnumDeclPrinter.indent { + helperEnumDeclPrinter.write("static func bridgeJSLift(_ callbackId: Int32) -> \(swiftClosureType) {") + helperEnumDeclPrinter.indent { + helperEnumDeclPrinter.write("let callback = JSObject.bridgeJSLiftParameter(callbackId)") + let parameters: String + if signature.parameters.isEmpty { + parameters = "" + } else if signature.parameters.count == 1 { + parameters = " param0" + } else { + parameters = + " (" + + signature.parameters.enumerated().map { index, _ in + "param\(index)" + }.joined(separator: ", ") + ")" } - } - """ - - let helperEnumDecl = EnumDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.private)) - }, - name: .identifier(helperName), - memberBlockBuilder: { - DeclSyntax( - FunctionDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.static)) - }, - name: .identifier("bridgeJSLower"), - signature: FunctionSignatureSyntax( - parameterClause: FunctionParameterClauseSyntax { - FunctionParameterSyntax( - firstName: .wildcardToken(), - secondName: .identifier("closure"), - colon: .colonToken(), - type: TypeSyntax("@escaping \(raw: closureType)") - ) - }, - returnClause: ReturnClauseSyntax( - arrow: .arrowToken(), - type: IdentifierTypeSyntax(name: .identifier("UnsafeMutableRawPointer")) - ) - ), - body: CodeBlockSyntax { - "let box = \(raw: boxClassName)(closure)" - "return Unmanaged.passRetained(box).toOpaque()" + helperEnumDeclPrinter.write("return { [callback]\(parameters) in") + helperEnumDeclPrinter.indent { + SwiftCodePattern.buildWasmConditionalCompilation( + printer: helperEnumDeclPrinter, + wasmBody: { printer in + printer.write(lines: builder.body.lines) } ) - ) + } + helperEnumDeclPrinter.write("}") - DeclSyntax( - FunctionDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.static)) - }, - name: .identifier("bridgeJSLift"), - signature: FunctionSignatureSyntax( - parameterClause: FunctionParameterClauseSyntax { - FunctionParameterSyntax( - firstName: .wildcardToken(), - secondName: .identifier("callbackId"), - colon: .colonToken(), - type: IdentifierTypeSyntax(name: .identifier("Int32")) - ) - }, - returnClause: ReturnClauseSyntax( - arrow: .arrowToken(), - type: IdentifierTypeSyntax(name: .identifier(closureType)) - ) - ), - body: CodeBlockSyntax { - "let callback = JSObject.bridgeJSLiftParameter(callbackId)" - ReturnStmtSyntax( - expression: ClosureExprSyntax( - leftBrace: .leftBraceToken(), - signature: ClosureSignatureSyntax( - capture: ClosureCaptureClauseSyntax( - leftSquare: .leftSquareToken(), - items: ClosureCaptureListSyntax { - #if canImport(SwiftSyntax602) - ClosureCaptureSyntax( - name: .identifier("", presence: .missing), - initializer: InitializerClauseSyntax( - equal: .equalToken(presence: .missing), - nil, - value: ExprSyntax("callback") - ), - trailingTrivia: nil - ) - #else - ClosureCaptureSyntax( - expression: ExprSyntax("callback") - ) - #endif - }, - rightSquare: .rightSquareToken() - ), - parameterClause: .simpleInput( - ClosureShorthandParameterListSyntax { - for (index, _) in signature.parameters.enumerated() { - ClosureShorthandParameterSyntax(name: .identifier("param\(index)")) - } - } - ), - inKeyword: .keyword(.in) - ), - statements: CodeBlockItemListSyntax { - SwiftCodePattern.buildWasmConditionalCompilation(wasmBody: bodyCode.statements) - }, - rightBrace: .rightBraceToken() - ) - ) - } + } + helperEnumDeclPrinter.write("}") + } + helperEnumDeclPrinter.write("}") + + let helperEnumDecl: DeclSyntax = "\(raw: helperEnumDeclPrinter.lines.joined(separator: "\n"))" + + let typedClosureExtension: DeclSyntax = """ + extension JSTypedClosure where Signature == \(raw: swiftClosureType) { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType)) { + self.init( + makeClosure: \(raw: externABIName), + body: body, + fileID: fileID, + line: line ) - ) + } } - ) - return [externDecl, boxClassDecl, DeclSyntax(helperEnumDecl)] + """ + + return [ + externDecl, makeClosureExternDecl, helperEnumDecl, typedClosureExtension, + ] } func renderClosureInvokeHandler(_ signature: ClosureSignature) throws -> DeclSyntax { - let boxClassName = "_BJS_ClosureBox_\(signature.mangleName)" + let swiftClosureType = swiftClosureType(for: signature) + let boxType = "_BridgeJSTypedClosureBox<\(swiftClosureType)>" let abiName = "invoke_swift_closure_\(signature.moduleName)_\(signature.mangleName)" // Build ABI parameters directly with WasmCoreType (no string conversion needed) @@ -205,17 +137,9 @@ public struct ClosureCodegen { liftedParams.append("\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))") } - let closureCallExpr = ExprSyntax("box.closure(\(raw: liftedParams.joined(separator: ", ")))") + let closureCallExpr = ExprSyntax("closure(\(raw: liftedParams.joined(separator: ", ")))") - // Determine return type - let abiReturnWasmType: WasmCoreType? - if signature.returnType == .void { - abiReturnWasmType = nil - } else if let wasmType = try signature.returnType.loweringReturnInfo().returnType { - abiReturnWasmType = wasmType - } else { - abiReturnWasmType = nil - } + let abiReturnWasmType = try signature.returnType.loweringReturnInfo().returnType // Build signature using SwiftSignatureBuilder let funcSignature = SwiftSignatureBuilder.buildABIFunctionSignature( @@ -223,105 +147,28 @@ public struct ClosureCodegen { returnType: abiReturnWasmType ) - // Build body - let body = CodeBlockItemListSyntax { - "let box = Unmanaged<\(raw: boxClassName)>.fromOpaque(boxPtr).takeUnretainedValue()" + // Build function declaration using helper + let funcDecl = SwiftCodePattern.buildExposedFunctionDecl( + abiName: abiName, + signature: funcSignature + ) { printer in + printer.write("let closure = Unmanaged<\(boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure") if signature.returnType == .void { - closureCallExpr + printer.write(closureCallExpr.description) } else { - "let result = \(closureCallExpr)" - "return result.bridgeJSLowerReturn()" + printer.write("let result = \(closureCallExpr)") + printer.write("return result.bridgeJSLowerReturn()") } } - // Build function declaration using helper - let funcDecl = SwiftCodePattern.buildExposedFunctionDecl( - abiName: abiName, - signature: funcSignature, - body: body - ) - return DeclSyntax(funcDecl) } public func renderSupport(for skeleton: BridgeJSSkeleton) throws -> String? { - var closureSignatures: Set = [] - - if let exported = skeleton.exported { - for function in exported.functions { - collectClosureSignatures(from: function.parameters, into: &closureSignatures) - collectClosureSignatures(from: function.returnType, into: &closureSignatures) - } - for klass in exported.classes { - if let constructor = klass.constructor { - collectClosureSignatures(from: constructor.parameters, into: &closureSignatures) - } - for method in klass.methods { - collectClosureSignatures(from: method.parameters, into: &closureSignatures) - collectClosureSignatures(from: method.returnType, into: &closureSignatures) - } - for property in klass.properties { - collectClosureSignatures(from: property.type, into: &closureSignatures) - } - } - for proto in exported.protocols { - for method in proto.methods { - collectClosureSignatures(from: method.parameters, into: &closureSignatures) - collectClosureSignatures(from: method.returnType, into: &closureSignatures) - } - for property in proto.properties { - collectClosureSignatures(from: property.type, into: &closureSignatures) - } - } - for structDecl in exported.structs { - for property in structDecl.properties { - collectClosureSignatures(from: property.type, into: &closureSignatures) - } - if let constructor = structDecl.constructor { - collectClosureSignatures(from: constructor.parameters, into: &closureSignatures) - } - for method in structDecl.methods { - collectClosureSignatures(from: method.parameters, into: &closureSignatures) - collectClosureSignatures(from: method.returnType, into: &closureSignatures) - } - } - for enumDecl in exported.enums { - for method in enumDecl.staticMethods { - collectClosureSignatures(from: method.parameters, into: &closureSignatures) - collectClosureSignatures(from: method.returnType, into: &closureSignatures) - } - for property in enumDecl.staticProperties { - collectClosureSignatures(from: property.type, into: &closureSignatures) - } - } - } - - if let imported = skeleton.imported { - for fileSkeleton in imported.children { - for getter in fileSkeleton.globalGetters { - collectClosureSignatures(from: getter.type, into: &closureSignatures) - } - for function in fileSkeleton.functions { - collectClosureSignatures(from: function.parameters, into: &closureSignatures) - collectClosureSignatures(from: function.returnType, into: &closureSignatures) - } - for type in fileSkeleton.types { - if let constructor = type.constructor { - collectClosureSignatures(from: constructor.parameters, into: &closureSignatures) - } - for getter in type.getters { - collectClosureSignatures(from: getter.type, into: &closureSignatures) - } - for setter in type.setters { - collectClosureSignatures(from: setter.type, into: &closureSignatures) - } - for method in type.methods { - collectClosureSignatures(from: method.parameters, into: &closureSignatures) - collectClosureSignatures(from: method.returnType, into: &closureSignatures) - } - } - } - } + let collector = ClosureSignatureCollectorVisitor() + var walker = BridgeTypeWalker(visitor: collector) + walker.walk(skeleton) + let closureSignatures = walker.visitor.signatures guard !closureSignatures.isEmpty else { return nil } @@ -331,7 +178,9 @@ public struct ClosureCodegen { decls.append(try renderClosureInvokeHandler(signature)) } - let format = BasicFormat() - return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n") + return withSpan("Format Closure Glue") { + let format = BasicFormat() + return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n") + } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index d7d5c8200..2332918c1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -47,45 +47,52 @@ public class ExportSwift { func renderSwiftGlue() throws -> String? { var decls: [DeclSyntax] = [] - let protocolCodegen = ProtocolCodegen() - for proto in skeleton.protocols { - decls.append(contentsOf: try protocolCodegen.renderProtocolWrapper(proto, moduleName: moduleName)) + try withSpan("Render Protocols") { [self] in + let protocolCodegen = ProtocolCodegen() + for proto in skeleton.protocols { + decls.append(contentsOf: try protocolCodegen.renderProtocolWrapper(proto, moduleName: moduleName)) + } } - let enumCodegen = EnumCodegen() - for enumDef in skeleton.enums { - if let enumHelpers = enumCodegen.renderEnumHelpers(enumDef) { - decls.append(enumHelpers) - } + try withSpan("Render Enums") { [self] in + let enumCodegen = EnumCodegen() + for enumDef in skeleton.enums { + if let enumHelpers = enumCodegen.renderEnumHelpers(enumDef) { + decls.append(enumHelpers) + } - for staticMethod in enumDef.staticMethods { - decls.append(try renderSingleExportedFunction(function: staticMethod)) - } + for staticMethod in enumDef.staticMethods { + decls.append(try renderSingleExportedFunction(function: staticMethod)) + } - for staticProperty in enumDef.staticProperties { - decls.append( - contentsOf: try renderSingleExportedProperty( - property: staticProperty, - context: .enumStatic(enumDef: enumDef) + for staticProperty in enumDef.staticProperties { + decls.append( + contentsOf: try renderSingleExportedProperty( + property: staticProperty, + context: .enumStatic(enumDef: enumDef) + ) ) - ) + } } } - let structCodegen = StructCodegen() - for structDef in skeleton.structs { - decls.append(contentsOf: structCodegen.renderStructHelpers(structDef)) - decls.append(contentsOf: try renderSingleExportedStruct(struct: structDef)) - } + try withSpan("Render Structs") { [self] in + let structCodegen = StructCodegen() + for structDef in skeleton.structs { + decls.append(contentsOf: structCodegen.renderStructHelpers(structDef)) + decls.append(contentsOf: try renderSingleExportedStruct(struct: structDef)) + } - for function in skeleton.functions { - decls.append(try renderSingleExportedFunction(function: function)) + for function in skeleton.functions { + decls.append(try renderSingleExportedFunction(function: function)) + } + for klass in skeleton.classes { + decls.append(contentsOf: try renderSingleExportedClass(klass: klass)) + } } - for klass in skeleton.classes { - decls.append(contentsOf: try renderSingleExportedClass(klass: klass)) + return withSpan("Format Export Glue") { + return decls.map { $0.description }.joined(separator: "\n\n") } - let format = BasicFormat() - return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n") } class ExportedThunkBuilder { @@ -124,7 +131,7 @@ public class ExportSwift { let liftingExpr: ExprSyntax switch param.type { - case .closure(let signature): + case .closure(let signature, _): typeNameForIntrinsic = param.type.swiftType liftingExpr = ExprSyntax("_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(\(raw: param.name))") case .swiftStruct(let structName): @@ -133,40 +140,16 @@ public class ExportSwift { case .array: typeNameForIntrinsic = param.type.swiftType liftingExpr = StackCodegen().liftExpression(for: param.type) - case .optional(let wrappedType): - if case .array(let elementType) = wrappedType { - let arrayLift = StackCodegen().liftArrayExpression(elementType: elementType) - let isSomeParam = argumentsToLift[0] - let swiftTypeName = elementType.swiftType - typeNameForIntrinsic = "Optional<[\(swiftTypeName)]>" - liftingExpr = ExprSyntax( - """ - { - if \(raw: isSomeParam) == 0 { - return Optional<[\(raw: swiftTypeName)]>.none - } else { - return \(arrayLift) - } - }() - """ - ) - } else if case .swiftProtocol(let protocolName) = wrappedType { - let wrapperName = "Any\(protocolName)" - typeNameForIntrinsic = "Optional<\(wrapperName)>" - liftingExpr = ExprSyntax( - "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" - ) + case .nullable(let wrappedType, let kind): + let optionalSwiftType: String + if case .null = kind { + optionalSwiftType = "Optional" } else { - typeNameForIntrinsic = "Optional<\(wrappedType.swiftType)>" - liftingExpr = ExprSyntax( - "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" - ) + optionalSwiftType = "JSUndefinedOr" } - case .swiftProtocol(let protocolName): - let wrapperName = "Any\(protocolName)" - typeNameForIntrinsic = wrapperName + typeNameForIntrinsic = "\(optionalSwiftType)<\(wrappedType.swiftType)>" liftingExpr = ExprSyntax( - "\(raw: wrapperName).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" + "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" ) default: typeNameForIntrinsic = param.type.swiftType @@ -181,6 +164,20 @@ public class ExportSwift { } } + private func protocolCastSuffix(for returnType: BridgeType) -> (prefix: String, suffix: String) { + switch returnType { + case .swiftProtocol: + return ("", " as! \(returnType.swiftType)") + case .nullable(let wrappedType, _): + if case .swiftProtocol = wrappedType { + return ("(", ").flatMap { $0 as? \(wrappedType.swiftType) }") + } + return ("", "") + default: + return ("", "") + } + } + private func removeFirstLiftedParameter() -> (parameter: Parameter, expr: ExprSyntax) { let parameter = parameters.removeFirst() let expr = liftedParameterExprs.removeFirst() @@ -214,26 +211,10 @@ public class ExportSwift { if returnType == .void { return CodeBlockItemSyntax(item: .init(ExpressionStmtSyntax(expression: callExpr))) } else { - switch returnType { - case .swiftProtocol(let protocolName): - let wrapperName = "Any\(protocolName)" - return CodeBlockItemSyntax( - item: .init(DeclSyntax("let ret = \(raw: callExpr) as! \(raw: wrapperName)")) - ) - case .optional(let wrappedType): - if case .swiftProtocol(let protocolName) = wrappedType { - let wrapperName = "Any\(protocolName)" - return CodeBlockItemSyntax( - item: .init( - DeclSyntax("let ret = (\(raw: callExpr)).flatMap { $0 as? \(raw: wrapperName) }") - ) - ) - } else { - return CodeBlockItemSyntax(item: .init(DeclSyntax("let ret = \(raw: callExpr)"))) - } - default: - return CodeBlockItemSyntax(item: .init(DeclSyntax("let ret = \(raw: callExpr)"))) - } + let (prefix, suffix) = protocolCastSuffix(for: returnType) + return CodeBlockItemSyntax( + item: .init(DeclSyntax("let ret = \(raw: prefix)\(raw: callExpr)\(raw: suffix)")) + ) } } @@ -247,20 +228,8 @@ public class ExportSwift { if returnType == .void { append("\(raw: name)") } else { - switch returnType { - case .swiftProtocol(let protocolName): - let wrapperName = "Any\(protocolName)" - append("let ret = \(raw: name) as! \(raw: wrapperName)") - case .optional(let wrappedType): - if case .swiftProtocol(let protocolName) = wrappedType { - let wrapperName = "Any\(protocolName)" - append("let ret = \(raw: name).flatMap { $0 as? \(raw: wrapperName) }") - } else { - append("let ret = \(raw: name)") - } - default: - append("let ret = \(raw: name)") - } + let (prefix, suffix) = protocolCastSuffix(for: returnType) + append("let ret = \(raw: prefix)\(raw: name)\(raw: suffix)") } } @@ -278,8 +247,8 @@ public class ExportSwift { private func generateParameterLifting() { let stackParamIndices = parameters.enumerated().compactMap { index, param -> Int? in switch param.type { - case .swiftStruct, .optional(.swiftStruct), - .associatedValueEnum, .optional(.associatedValueEnum), + case .swiftStruct, .nullable(.swiftStruct, _), + .associatedValueEnum, .nullable(.associatedValueEnum, _), .array: return index default: @@ -304,20 +273,8 @@ public class ExportSwift { if returnType == .void { append("\(raw: selfExpr).\(raw: propertyName)") } else { - switch returnType { - case .swiftProtocol(let protocolName): - let wrapperName = "Any\(protocolName)" - append("let ret = \(raw: selfExpr).\(raw: propertyName) as! \(raw: wrapperName)") - case .optional(let wrappedType): - if case .swiftProtocol(let protocolName) = wrappedType { - let wrapperName = "Any\(protocolName)" - append("let ret = \(raw: selfExpr).\(raw: propertyName).flatMap { $0 as? \(raw: wrapperName) }") - } else { - append("let ret = \(raw: selfExpr).\(raw: propertyName)") - } - default: - append("let ret = \(raw: selfExpr).\(raw: propertyName)") - } + let (prefix, suffix) = protocolCastSuffix(for: returnType) + append("let ret = \(raw: prefix)\(raw: selfExpr).\(raw: propertyName)\(raw: suffix)") } } @@ -354,9 +311,9 @@ public class ExportSwift { } switch returnType { - case .closure(let signature): - append("return _BJS_Closure_\(raw: signature.mangleName).bridgeJSLower(ret)") - case .array, .optional(.array): + case .closure(_, useJSTypedClosure: false): + append("return JSTypedClosure(ret).bridgeJSLowerReturn()") + case .array, .nullable(.array, _): let stackCodegen = StackCodegen() for stmt in stackCodegen.lowerStatements(for: returnType, accessor: "ret", varPrefix: "ret") { append(stmt) @@ -405,22 +362,16 @@ public class ExportSwift { // Build function declaration using helper function let funcDecl = SwiftCodePattern.buildExposedFunctionDecl( abiName: abiName, - signature: signature, - body: body - ) + signature: signature + ) { printer in + printer.write(multilineString: body.description) + } return DeclSyntax(funcDecl) } private func returnPlaceholderStmt() -> String { - switch abiReturnType { - case .i32: return "return 0" - case .i64: return "return 0" - case .f32: return "return 0.0" - case .f64: return "return 0.0" - case .pointer: return "return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped" - case .none: return "return" - } + return abiReturnType?.swiftReturnPlaceholderStmt ?? "return" } } @@ -531,17 +482,7 @@ public class ExportSwift { } if function.effects.isStatic, let staticContext = function.staticContext { - let callName: String - switch staticContext { - case .className(let baseName), .enumName(let baseName), .structName(let baseName): - callName = "\(baseName).\(function.name)" - case .namespaceEnum: - if let namespace = function.namespace, !namespace.isEmpty { - callName = "\(namespace.joined(separator: ".")).\(function.name)" - } else { - callName = function.name - } - } + let callName = "\(staticContextBaseName(staticContext)).\(function.name)" builder.call(name: callName, returnType: function.returnType) } else { builder.call(name: function.name, returnType: function.returnType) @@ -551,17 +492,61 @@ public class ExportSwift { return builder.render(abiName: function.abiName) } + private func staticContextBaseName(_ staticContext: StaticContext) -> String { + switch staticContext { + case .className(let baseName), .enumName(let baseName), .structName(let baseName), + .namespaceEnum(let baseName): + return baseName + } + } + + private func renderSingleExportedConstructor( + constructor: ExportedConstructor, + callName: String, + returnType: BridgeType + ) throws -> DeclSyntax { + let builder = ExportedThunkBuilder(effects: constructor.effects) + for param in constructor.parameters { + try builder.liftParameter(param: param) + } + builder.call(name: callName, returnType: returnType) + try builder.lowerReturnValue(returnType: returnType) + return builder.render(abiName: constructor.abiName) + } + + private func renderSingleExportedMethod( + method: ExportedFunction, + ownerTypeName: String, + instanceSelfType: BridgeType + ) throws -> DeclSyntax { + let builder = ExportedThunkBuilder(effects: method.effects) + if !method.effects.isStatic { + try builder.liftParameter(param: Parameter(label: nil, name: "_self", type: instanceSelfType)) + } + for param in method.parameters { + try builder.liftParameter(param: param) + } + + if method.effects.isStatic { + builder.call(name: "\(ownerTypeName).\(method.name)", returnType: method.returnType) + } else { + builder.callMethod(methodName: method.name, returnType: method.returnType) + } + try builder.lowerReturnValue(returnType: method.returnType) + return builder.render(abiName: method.abiName) + } + func renderSingleExportedStruct(struct structDef: ExportedStruct) throws -> [DeclSyntax] { var decls: [DeclSyntax] = [] if let constructor = structDef.constructor { - let builder = ExportedThunkBuilder(effects: constructor.effects) - for param in constructor.parameters { - try builder.liftParameter(param: param) - } - builder.call(name: structDef.swiftCallName, returnType: .swiftStruct(structDef.swiftCallName)) - try builder.lowerReturnValue(returnType: .swiftStruct(structDef.swiftCallName)) - decls.append(builder.render(abiName: constructor.abiName)) + decls.append( + try renderSingleExportedConstructor( + constructor: constructor, + callName: structDef.swiftCallName, + returnType: .swiftStruct(structDef.swiftCallName) + ) + ) } for property in structDef.properties where property.isStatic { @@ -574,28 +559,13 @@ public class ExportSwift { } for method in structDef.methods { - let builder = ExportedThunkBuilder(effects: method.effects) - - if method.effects.isStatic { - for param in method.parameters { - try builder.liftParameter(param: param) - } - builder.call(name: "\(structDef.swiftCallName).\(method.name)", returnType: method.returnType) - } else { - try builder.liftParameter( - param: Parameter(label: nil, name: "_self", type: .swiftStruct(structDef.swiftCallName)) - ) - for param in method.parameters { - try builder.liftParameter(param: param) - } - builder.callMethod( - methodName: method.name, - returnType: method.returnType + decls.append( + try renderSingleExportedMethod( + method: method, + ownerTypeName: structDef.swiftCallName, + instanceSelfType: .swiftStruct(structDef.swiftCallName) ) - } - - try builder.lowerReturnValue(returnType: method.returnType) - decls.append(builder.render(abiName: method.abiName)) + ) } return decls @@ -652,55 +622,29 @@ public class ExportSwift { var decls: [DeclSyntax] = [] if let constructor = klass.constructor { - let builder = ExportedThunkBuilder(effects: constructor.effects) - for param in constructor.parameters { - try builder.liftParameter(param: param) - } - builder.call(name: klass.swiftCallName, returnType: BridgeType.swiftHeapObject(klass.name)) - try builder.lowerReturnValue(returnType: BridgeType.swiftHeapObject(klass.name)) - decls.append(builder.render(abiName: constructor.abiName)) + decls.append( + try renderSingleExportedConstructor( + constructor: constructor, + callName: klass.swiftCallName, + returnType: .swiftHeapObject(klass.name) + ) + ) } for method in klass.methods { - let builder = ExportedThunkBuilder(effects: method.effects) - - if method.effects.isStatic { - for param in method.parameters { - try builder.liftParameter(param: param) - } - builder.call(name: "\(klass.swiftCallName).\(method.name)", returnType: method.returnType) - } else { - try builder.liftParameter( - param: Parameter(label: nil, name: "_self", type: BridgeType.swiftHeapObject(klass.swiftCallName)) - ) - for param in method.parameters { - try builder.liftParameter(param: param) - } - builder.callMethod( - methodName: method.name, - returnType: method.returnType + decls.append( + try renderSingleExportedMethod( + method: method, + ownerTypeName: klass.swiftCallName, + instanceSelfType: .swiftHeapObject(klass.swiftCallName) ) - } - try builder.lowerReturnValue(returnType: method.returnType) - decls.append(builder.render(abiName: method.abiName)) + ) } // Generate property getters and setters for property in klass.properties { - if property.isStatic { - decls.append( - contentsOf: try renderSingleExportedProperty( - property: property, - context: .classStatic(klass: klass) - ) - ) - } else { - decls.append( - contentsOf: try renderSingleExportedProperty( - property: property, - context: .classInstance(klass: klass) - ) - ) - } + let context: PropertyRenderingContext = + property.isStatic ? .classStatic(klass: klass) : .classInstance(klass: klass) + decls.append(contentsOf: try renderSingleExportedProperty(property: property, context: context)) } do { @@ -709,11 +653,10 @@ public class ExportSwift { signature: SwiftSignatureBuilder.buildABIFunctionSignature( abiParameters: [("pointer", .pointer)], returnType: nil - ), - body: CodeBlockItemListSyntax { - "Unmanaged<\(raw: klass.swiftCallName)>.fromOpaque(pointer).release()" - } - ) + ) + ) { printer in + printer.write("Unmanaged<\(klass.swiftCallName)>.fromOpaque(pointer).release()") + } decls.append(DeclSyntax(funcDecl)) } @@ -752,39 +695,16 @@ public class ExportSwift { } """ // Build common function signature - let funcSignature = SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: [("pointer", .pointer)], - returnType: .i32 - ) - - // Build extern function declaration (no body) - let externFuncDecl = SwiftCodePattern.buildExternFunctionDecl( + let externDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: externDeclPrinter, moduleName: moduleName, abiName: externFunctionName, functionName: wrapFunctionName, - signature: funcSignature - ) - - // Build stub function declaration (with fatalError body) - let stubFuncDecl = FunctionDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.fileprivate)) - }, - funcKeyword: .keyword(.func), - name: .identifier(wrapFunctionName), - signature: funcSignature, - body: CodeBlockSyntax { - "fatalError(\"Only available on WebAssembly\")" - } - ) - - // Use helper function for conditional compilation - let externDecl = DeclSyntax( - SwiftCodePattern.buildWasmConditionalCompilationDecls( - wasmDecl: DeclSyntax(externFuncDecl), - elseDecl: DeclSyntax(stubFuncDecl) - ) + abiParameters: [("pointer", .pointer)], + returnType: .i32 ) + let externDecl: DeclSyntax = "\(raw: externDeclPrinter.lines.joined(separator: "\n"))" return [extensionDecl, externDecl] } } @@ -798,60 +718,39 @@ struct StackCodegen { /// - Returns: An ExprSyntax representing the lift expression func liftExpression(for type: BridgeType) -> ExprSyntax { switch type { - case .string: - return "String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .int, .uint: - return "Int.bridgeJSLiftParameter(_swift_js_pop_i32())" - case .bool: - return "Bool.bridgeJSLiftParameter(_swift_js_pop_i32())" - case .float: - return "Float.bridgeJSLiftParameter(_swift_js_pop_f32())" - case .double: - return "Double.bridgeJSLiftParameter(_swift_js_pop_f64())" - case .jsObject: - return "JSObject.bridgeJSLiftParameter(_swift_js_pop_i32())" - case .swiftHeapObject(let className): - return "\(raw: className).bridgeJSLiftParameter(_swift_js_pop_pointer())" - case .unsafePointer: - return "\(raw: type.swiftType).bridgeJSLiftParameter(_swift_js_pop_pointer())" - case .swiftProtocol(let protocolName): - // Protocols use their Any wrapper type for lifting - let wrapperName = "Any\(protocolName)" - return "\(raw: wrapperName).bridgeJSLiftParameter(_swift_js_pop_i32())" - case .caseEnum(let enumName): - return "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_i32())" - case .rawValueEnum(let enumName, let rawType): - switch rawType { - case .string: - return - "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .float: - return "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_f32())" - case .double: - return "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_f64())" - case .bool, .int, .int32, .int64, .uint, .uint32, .uint64: - return "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_i32())" - } - case .associatedValueEnum(let enumName): - return "\(raw: enumName).bridgeJSLiftParameter(_swift_js_pop_i32())" - case .swiftStruct(let structName): - return "\(raw: structName).bridgeJSLiftParameter()" - case .optional(let wrappedType): - return liftOptionalExpression(wrappedType: wrappedType) - case .void: - // Void shouldn't be lifted, but return a placeholder - return "()" - case .namespaceEnum: - // Namespace enums are not passed as values - return "()" - case .closure: - return "JSObject.bridgeJSLiftParameter(_swift_js_pop_i32())" + case .string, .int, .uint, .bool, .float, .double, + .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, + .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum: + return "\(raw: type.swiftType).bridgeJSStackPop()" + case .jsObject(let className?): + return "\(raw: className)(unsafelyWrapping: JSObject.bridgeJSStackPop())" + case .nullable(let wrappedType, let kind): + return liftNullableExpression(wrappedType: wrappedType, kind: kind) case .array(let elementType): return liftArrayExpression(elementType: elementType) + case .dictionary(let valueType): + return liftDictionaryExpression(valueType: valueType) + case .closure: + return "JSObject.bridgeJSStackPop()" + case .void, .namespaceEnum: + return "()" } } func liftArrayExpression(elementType: BridgeType) -> ExprSyntax { + switch elementType { + case .jsObject(let className?) where className != "JSObject": + return "[JSObject].bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" + case .nullable, .closure: + return liftArrayExpressionInline(elementType: elementType) + case .void, .namespaceEnum: + fatalError("Invalid array element type: \(elementType)") + default: + return "[\(raw: elementType.swiftType)].bridgeJSStackPop()" + } + } + + private func liftArrayExpressionInline(elementType: BridgeType) -> ExprSyntax { let elementLift = liftExpression(for: elementType) let swiftTypeName = elementType.swiftType return """ @@ -868,63 +767,53 @@ struct StackCodegen { """ } - private func liftOptionalExpression(wrappedType: BridgeType) -> ExprSyntax { - switch wrappedType { - case .string: - return - "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())" - case .int, .uint: - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .bool: - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .float: - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f32())" - case .double: - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f64())" - case .caseEnum(let enumName): - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .rawValueEnum(let enumName, let rawType): - switch rawType { - case .string: - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())" - case .float: - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f32())" - case .double: - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f64())" - case .bool, .int, .int32, .int64, .uint, .uint32, .uint64: - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - } - case .swiftStruct(let nestedName): - return "Optional<\(raw: nestedName)>.bridgeJSLiftParameter(_swift_js_pop_i32())" - case .swiftHeapObject(let className): - return - "Optional<\(raw: className)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_pointer())" - case .associatedValueEnum(let enumName): - return - "Optional<\(raw: enumName)>.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .jsObject: - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" - case .array(let elementType): - let arrayLift = liftArrayExpression(elementType: elementType) - let swiftTypeName = elementType.swiftType + func liftDictionaryExpression(valueType: BridgeType) -> ExprSyntax { + switch valueType { + case .jsObject(let className?) where className != "JSObject": return """ { - let __isSome = _swift_js_pop_i32() - if __isSome == 0 { - return Optional<[\(raw: swiftTypeName)]>.none - } else { - return \(arrayLift) - } + let __dict = [String: JSObject].bridgeJSStackPop() + return __dict.mapValues { \(raw: className)(unsafelyWrapping: $0) } }() """ + case .nullable, .closure: + return liftDictionaryExpressionInline(valueType: valueType) + case .void, .namespaceEnum: + fatalError("Invalid dictionary value type: \(valueType)") default: - // Fallback for other optional types - return "Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())" + return "[String: \(raw: valueType.swiftType)].bridgeJSStackPop()" + } + } + + private func liftDictionaryExpressionInline(valueType: BridgeType) -> ExprSyntax { + let valueLift = liftExpression(for: valueType) + let swiftTypeName = valueType.swiftType + return """ + { + let __count = Int(_swift_js_pop_i32()) + var __result: [String: \(raw: swiftTypeName)] = [:] + __result.reserveCapacity(__count) + for _ in 0..<__count { + let __value = \(valueLift) + let __key = String.bridgeJSStackPop() + __result[__key] = __value + } + return __result + }() + """ + } + + private func liftNullableExpression(wrappedType: BridgeType, kind: JSOptionalKind) -> ExprSyntax { + let typeName = kind == .null ? "Optional" : "JSUndefinedOr" + switch wrappedType { + case .string, .int, .uint, .bool, .float, .double, .jsObject(nil), .jsValue, + .swiftStruct, .swiftHeapObject, .caseEnum, .associatedValueEnum, .rawValueEnum, + .array, .dictionary: + return "\(raw: typeName)<\(raw: wrappedType.swiftType)>.bridgeJSStackPop()" + case .jsObject(let className?): + return "\(raw: typeName).bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" + case .nullable, .void, .namespaceEnum, .closure, .unsafePointer, .swiftProtocol: + fatalError("Invalid nullable wrapped type: \(wrappedType)") } } @@ -940,58 +829,24 @@ struct StackCodegen { varPrefix: String ) -> [CodeBlockItemSyntax] { switch type { - case .string: - return [ - "var __bjs_\(raw: varPrefix) = \(raw: accessor)", - "__bjs_\(raw: varPrefix).withUTF8 { ptr in _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) }", - ] - case .int, .uint: - return ["_swift_js_push_i32(Int32(\(raw: accessor)))"] - case .bool: - return ["_swift_js_push_i32(\(raw: accessor) ? 1 : 0)"] - case .float: - return ["_swift_js_push_f32(\(raw: accessor))"] - case .double: - return ["_swift_js_push_f64(\(raw: accessor))"] - case .jsObject: - return ["_swift_js_push_i32(\(raw: accessor).bridgeJSLowerReturn())"] - case .swiftHeapObject: - return ["_swift_js_push_pointer(\(raw: accessor).bridgeJSLowerReturn())"] - case .unsafePointer: - return ["_swift_js_push_pointer(\(raw: accessor).bridgeJSLowerReturn())"] - case .swiftProtocol(let protocolName): - let wrapperName = "Any\(protocolName)" - return ["_swift_js_push_i32((\(raw: accessor) as! \(raw: wrapperName)).bridgeJSLowerReturn())"] - case .caseEnum: - return ["_swift_js_push_i32(Int32(\(raw: accessor).bridgeJSLowerParameter()))"] - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return [ - "var __bjs_\(raw: varPrefix) = \(raw: accessor).rawValue", - "__bjs_\(raw: varPrefix).withUTF8 { ptr in _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) }", - ] - case .float: - return ["_swift_js_push_f32(\(raw: accessor).bridgeJSLowerParameter())"] - case .double: - return ["_swift_js_push_f64(\(raw: accessor).bridgeJSLowerParameter())"] - default: - return ["_swift_js_push_i32(Int32(\(raw: accessor).bridgeJSLowerParameter()))"] - } - case .associatedValueEnum: - return ["\(raw: accessor).bridgeJSLowerReturn()"] - case .swiftStruct: - return ["\(raw: accessor).bridgeJSLowerReturn()"] - case .optional(let wrappedType): + case .string, .int, .uint, .bool, .float, .double, .jsValue, + .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, + .caseEnum, .rawValueEnum: + return ["\(raw: accessor).bridgeJSStackPush()"] + case .jsObject(_?): + return ["\(raw: accessor).jsObject.bridgeJSStackPush()"] + case .swiftProtocol: + return ["(\(raw: accessor) as! \(raw: type.swiftType)).bridgeJSStackPush()"] + case .associatedValueEnum, .swiftStruct: + return ["\(raw: accessor).bridgeJSStackPush()"] + case .nullable(let wrappedType, _): return lowerOptionalStatements(wrappedType: wrappedType, accessor: accessor, varPrefix: varPrefix) - case .void: + case .void, .namespaceEnum: return [] - case .namespaceEnum: - return [] - case .closure: - return ["_swift_js_push_pointer(\(raw: accessor).bridgeJSLowerReturn())"] case .array(let elementType): return lowerArrayStatements(elementType: elementType, accessor: accessor, varPrefix: varPrefix) + case .dictionary(let valueType): + return lowerDictionaryStatements(valueType: valueType, accessor: accessor, varPrefix: varPrefix) } } @@ -1000,9 +855,32 @@ struct StackCodegen { accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { - var statements: [CodeBlockItemSyntax] = [] + switch elementType { + case .jsObject(let className?) where className != "JSObject": + return ["\(raw: accessor).map { $0.jsObject }.bridgeJSStackPush()"] + case .swiftProtocol: + return ["\(raw: accessor).map { $0 as! \(raw: elementType.swiftType) }.bridgeJSStackPush()"] + case .nullable, .closure: + return lowerArrayStatementsInline( + elementType: elementType, + accessor: accessor, + varPrefix: varPrefix + ) + case .void, .namespaceEnum: + fatalError("Invalid array element type: \(elementType)") + default: + return ["\(raw: accessor).bridgeJSStackPush()"] + } + } + + private func lowerArrayStatementsInline( + elementType: BridgeType, + accessor: String, + varPrefix: String + ) -> [CodeBlockItemSyntax] { + var statements: [String] = [] let elementVarName = "__bjs_elem_\(varPrefix)" - statements.append("for \(raw: elementVarName) in \(raw: accessor) {") + statements.append("for \(elementVarName) in \(accessor) {") let elementStatements = lowerStatements( for: elementType, @@ -1010,6 +888,64 @@ struct StackCodegen { varPrefix: "\(varPrefix)_elem" ) for stmt in elementStatements { + statements.append(stmt.description) + } + + statements.append("}") + statements.append("_swift_js_push_i32(Int32(\(accessor).count))") + let parsed: CodeBlockItemListSyntax = "\(raw: statements.joined(separator: "\n"))" + return Array(parsed) + } + + private func lowerDictionaryStatements( + valueType: BridgeType, + accessor: String, + varPrefix: String + ) -> [CodeBlockItemSyntax] { + switch valueType { + case .jsObject(let className?) where className != "JSObject": + return ["\(raw: accessor).mapValues { $0.jsObject }.bridgeJSStackPush()"] + case .swiftProtocol: + return ["\(raw: accessor).mapValues { $0 as! \(raw: valueType.swiftType) }.bridgeJSStackPush()"] + case .nullable, .closure: + return lowerDictionaryStatementsInline( + valueType: valueType, + accessor: accessor, + varPrefix: varPrefix + ) + case .void, .namespaceEnum: + fatalError("Invalid dictionary value type: \(valueType)") + default: + return ["\(raw: accessor).bridgeJSStackPush()"] + } + } + + private func lowerDictionaryStatementsInline( + valueType: BridgeType, + accessor: String, + varPrefix: String + ) -> [CodeBlockItemSyntax] { + var statements: [CodeBlockItemSyntax] = [] + let pairVarName = "__bjs_kv_\(varPrefix)" + statements.append("for \(raw: pairVarName) in \(raw: accessor) {") + statements.append("let __bjs_key_\(raw: varPrefix) = \(raw: pairVarName).key") + statements.append("let __bjs_value_\(raw: varPrefix) = \(raw: pairVarName).value") + + let keyStatements = lowerStatements( + for: .string, + accessor: "__bjs_key_\(varPrefix)", + varPrefix: "\(varPrefix)_key" + ) + for stmt in keyStatements { + statements.append(stmt) + } + + let valueStatements = lowerStatements( + for: valueType, + accessor: "__bjs_value_\(varPrefix)", + varPrefix: "\(varPrefix)_value" + ) + for stmt in valueStatements { statements.append(stmt) } @@ -1023,69 +959,44 @@ struct StackCodegen { accessor: String, varPrefix: String ) -> [CodeBlockItemSyntax] { - var statements: [CodeBlockItemSyntax] = [] - statements.append("let __bjs_isSome_\(raw: varPrefix) = \(raw: accessor) != nil") - statements.append("if let __bjs_unwrapped_\(raw: varPrefix) = \(raw: accessor) {") + switch wrappedType { + case .array, .dictionary, .swiftStruct: + return ["\(raw: accessor).bridgeJSStackPush()"] + default: + break + } + + var statements: [String] = [] + statements.append("let __bjs_isSome_\(varPrefix) = \(accessor) != nil") + statements.append("if let __bjs_unwrapped_\(varPrefix) = \(accessor) {") let innerStatements = lowerUnwrappedOptionalStatements( wrappedType: wrappedType, - unwrappedVar: "__bjs_unwrapped_\(varPrefix)", - varPrefix: varPrefix + unwrappedVar: "__bjs_unwrapped_\(varPrefix)" ) for stmt in innerStatements { - statements.append(stmt) + statements.append(stmt.description) } statements.append("}") - statements.append("_swift_js_push_i32(__bjs_isSome_\(raw: varPrefix) ? 1 : 0)") - return statements + statements.append("_swift_js_push_i32(__bjs_isSome_\(varPrefix) ? 1 : 0)") + let parsed: CodeBlockItemListSyntax = "\(raw: statements.joined(separator: "\n"))" + return Array(parsed) } private func lowerUnwrappedOptionalStatements( wrappedType: BridgeType, - unwrappedVar: String, - varPrefix: String + unwrappedVar: String ) -> [CodeBlockItemSyntax] { switch wrappedType { - case .string: - return [ - "var __bjs_str_\(raw: varPrefix) = \(raw: unwrappedVar)", - "__bjs_str_\(raw: varPrefix).withUTF8 { ptr in _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) }", - ] - case .int, .uint: - return ["_swift_js_push_i32(Int32(\(raw: unwrappedVar)))"] - case .bool: - return ["_swift_js_push_i32(\(raw: unwrappedVar) ? 1 : 0)"] - case .float: - return ["_swift_js_push_f32(\(raw: unwrappedVar))"] - case .double: - return ["_swift_js_push_f64(\(raw: unwrappedVar))"] - case .caseEnum: - return ["_swift_js_push_i32(\(raw: unwrappedVar).bridgeJSLowerParameter())"] - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return [ - "var __bjs_str_\(raw: varPrefix) = \(raw: unwrappedVar).rawValue", - "__bjs_str_\(raw: varPrefix).withUTF8 { ptr in _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) }", - ] - case .float: - return ["_swift_js_push_f32(\(raw: unwrappedVar).bridgeJSLowerParameter())"] - case .double: - return ["_swift_js_push_f64(\(raw: unwrappedVar).bridgeJSLowerParameter())"] - default: - return ["_swift_js_push_i32(\(raw: unwrappedVar).bridgeJSLowerParameter())"] - } - case .swiftStruct: - return ["\(raw: unwrappedVar).bridgeJSLowerReturn()"] - case .swiftHeapObject: - return ["_swift_js_push_pointer(\(raw: unwrappedVar).bridgeJSLowerReturn())"] - case .associatedValueEnum: - return ["_swift_js_push_i32(\(raw: unwrappedVar).bridgeJSLowerParameter())"] - case .jsObject: - return ["_swift_js_push_i32(\(raw: unwrappedVar).bridgeJSLowerReturn())"] - case .array(let elementType): - return lowerArrayStatements(elementType: elementType, accessor: unwrappedVar, varPrefix: varPrefix) + case .jsObject(_?): + return ["\(raw: unwrappedVar).jsObject.bridgeJSStackPush()"] + case .swiftProtocol: + return ["(\(raw: unwrappedVar) as! \(raw: wrappedType.swiftType)).bridgeJSStackPush()"] + case .string, .int, .uint, .bool, .float, .double, .jsValue, + .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, + .caseEnum, .rawValueEnum, .associatedValueEnum: + return ["\(raw: unwrappedVar).bridgeJSStackPush()"] default: return ["preconditionFailure(\"BridgeJS: unsupported optional wrapped type\")"] } @@ -1111,94 +1022,120 @@ struct EnumCodegen { } private func renderCaseEnumHelpers(_ enumDef: ExportedEnum) -> DeclSyntax { - let typeName = enumDef.swiftCallName - var initCases: [String] = [] - var valueCases: [String] = [] - for (index, enumCase) in enumDef.cases.enumerated() { - initCases.append("case \(index): self = .\(enumCase.name)") - valueCases.append("case .\(enumCase.name): return \(index)") - } - let initSwitch = (["switch bridgeJSRawValue {"] + initCases + ["default: return nil", "}"]).joined( - separator: "\n" - ) - let valueSwitch = (["switch self {"] + valueCases + ["}"]).joined(separator: "\n") + let printer = CodeFragmentPrinter() + printer.write("extension \(enumDef.swiftCallName): _BridgedSwiftCaseEnum {") + printer.indent { + printer.write( + multilineString: """ + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> \(enumDef.swiftCallName) { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> \(enumDef.swiftCallName) { + return \(enumDef.swiftCallName)(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } - return """ - extension \(raw: typeName): _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> \(raw: typeName) { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> \(raw: typeName) { - return \(raw: typeName)(bridgeJSRawValue: value)! + """ + ) + printer.nextLine() + + printer.write("private init?(bridgeJSRawValue: Int32) {") + printer.indent { + printer.write("switch bridgeJSRawValue {") + for (index, enumCase) in enumDef.cases.enumerated() { + printer.write("case \(index):") + printer.indent { + printer.write("self = .\(enumCase.name)") + } } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() + printer.write("default:") + printer.indent { + printer.write("return nil") } - - private init?(bridgeJSRawValue: Int32) { - \(raw: initSwitch) - } - - private var bridgeJSRawValue: Int32 { - \(raw: valueSwitch) + printer.write("}") + } + printer.write("}") + printer.nextLine() + + printer.write("private var bridgeJSRawValue: Int32 {") + printer.indent { + printer.write("switch self {") + for (index, enumCase) in enumDef.cases.enumerated() { + printer.write("case .\(enumCase.name):") + printer.indent { + printer.write("return \(index)") + } } + printer.write("}") } - """ + printer.write("}") + } + printer.write("}") + return "\(raw: printer.lines.joined(separator: "\n"))" } private func renderRawValueEnumHelpers(_ enumDef: ExportedEnum) -> DeclSyntax { - return "extension \(raw: enumDef.swiftCallName): _BridgedSwiftEnumNoPayload {}" + let typeName = enumDef.swiftCallName + guard enumDef.rawType != nil else { + return """ + extension \(raw: typeName): _BridgedSwiftEnumNoPayload { + } + """ + } + // When rawType is present, conform to _BridgedSwiftRawValueEnum which provides + // default implementations for _BridgedSwiftStackType methods via protocol extension. + return """ + extension \(raw: typeName): _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { + } + """ } private func renderAssociatedValueEnumHelpers(_ enumDef: ExportedEnum) -> DeclSyntax { let typeName = enumDef.swiftCallName - return """ - extension \(raw: typeName): _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> \(raw: typeName) { - switch caseId { - \(raw: generateStackLiftSwitchCases(enumDef: enumDef).joined(separator: "\n")) - default: fatalError("Unknown \(raw: typeName) case ID: \\(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - \(raw: generateLowerParameterSwitchCases(enumDef: enumDef).joined(separator: "\n")) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> \(raw: typeName) { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> \(raw: typeName) { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - \(raw: generateReturnSwitchCases(enumDef: enumDef).joined(separator: "\n")) - } + let printer = CodeFragmentPrinter() + printer.write("extension \(typeName): _BridgedSwiftAssociatedValueEnum {") + printer.indent { + printer.write( + "@_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> \(typeName) {" + ) + printer.indent { + printer.write("switch caseId {") + generateStackLiftSwitchCases(printer: printer, enumDef: enumDef) + printer.write("default:") + printer.indent { + printer.write("fatalError(\"Unknown \(typeName) case ID: \\(caseId)\")") } + printer.write("}") } - """ + printer.write("}") + printer.nextLine() + + printer.write("@_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 {") + printer.indent { + printer.write("switch self {") + generateReturnSwitchCases(printer: printer, enumDef: enumDef) + printer.write("}") + } + printer.write("}") + } + printer.write("}") + return "\(raw: printer.lines.joined(separator: "\n"))" } - private func generateStackLiftSwitchCases(enumDef: ExportedEnum) -> [String] { - var cases: [String] = [] + private func generateStackLiftSwitchCases(printer: CodeFragmentPrinter, enumDef: ExportedEnum) { for (caseIndex, enumCase) in enumDef.cases.enumerated() { if enumCase.associatedValues.isEmpty { - cases.append("case \(caseIndex): return .\(enumCase.name)") + printer.write("case \(caseIndex):") + printer.indent { + printer.write("return .\(enumCase.name)") + } } else { - var lines: [String] = [] - lines.append("case \(caseIndex):") + printer.write("case \(caseIndex):") let argList = enumCase.associatedValues.map { associatedValue in let labelPrefix: String if let label = associatedValue.label { @@ -1209,17 +1146,17 @@ struct EnumCodegen { let liftExpr = stackCodegen.liftExpression(for: associatedValue.type) return "\(labelPrefix)\(liftExpr)" } - lines.append("return .\(enumCase.name)(\(argList.joined(separator: ", ")))") - cases.append(lines.joined(separator: "\n")) + printer.indent { + printer.write("return .\(enumCase.name)(\(argList.joined(separator: ", ")))") + } } } - return cases } private func generatePayloadPushingCode( + printer: CodeFragmentPrinter, associatedValues: [AssociatedValue] - ) -> [String] { - var bodyLines: [String] = [] + ) { for (index, associatedValue) in associatedValues.enumerated() { let paramName = associatedValue.label ?? "param\(index)" let statements = stackCodegen.lowerStatements( @@ -1227,49 +1164,30 @@ struct EnumCodegen { accessor: paramName, varPrefix: paramName ) - for stmt in statements { - bodyLines.append(stmt.description) - } + printer.write(multilineString: CodeBlockItemListSyntax(statements).description) } - return bodyLines } - private func generateLowerParameterSwitchCases(enumDef: ExportedEnum) -> [String] { - var cases: [String] = [] + private func generateReturnSwitchCases(printer: CodeFragmentPrinter, enumDef: ExportedEnum) { for (caseIndex, enumCase) in enumDef.cases.enumerated() { if enumCase.associatedValues.isEmpty { - cases.append("case .\(enumCase.name):") - cases.append("return Int32(\(caseIndex))") - } else { - let payloadCode = generatePayloadPushingCode(associatedValues: enumCase.associatedValues) - let pattern = enumCase.associatedValues.enumerated() - .map { index, associatedValue in "let \(associatedValue.label ?? "param\(index)")" } - .joined(separator: ", ") - cases.append("case .\(enumCase.name)(\(pattern)):") - cases.append(contentsOf: payloadCode) - cases.append("return Int32(\(caseIndex))") - } - } - return cases - } - - private func generateReturnSwitchCases(enumDef: ExportedEnum) -> [String] { - var cases: [String] = [] - for (caseIndex, enumCase) in enumDef.cases.enumerated() { - if enumCase.associatedValues.isEmpty { - cases.append("case .\(enumCase.name):") - cases.append("_swift_js_push_tag(Int32(\(caseIndex)))") + printer.write("case .\(enumCase.name):") + printer.indent { + printer.write("return Int32(\(caseIndex))") + } } else { let pattern = enumCase.associatedValues.enumerated() .map { index, associatedValue in "let \(associatedValue.label ?? "param\(index)")" } .joined(separator: ", ") - cases.append("case .\(enumCase.name)(\(pattern)):") - cases.append("_swift_js_push_tag(Int32(\(caseIndex)))") - let payloadCode = generatePayloadPushingCode(associatedValues: enumCase.associatedValues) - cases.append(contentsOf: payloadCode) + printer.write("case .\(enumCase.name)(\(pattern)):") + printer.indent { + generatePayloadPushingCode(printer: printer, associatedValues: enumCase.associatedValues) + // Push tag AFTER payloads so it's popped first (LIFO) by the JS lift function. + // This ensures nested enum tags don't overwrite the outer tag. + printer.write("return Int32(\(caseIndex))") + } } } - return cases } } @@ -1280,89 +1198,77 @@ struct StructCodegen { func renderStructHelpers(_ structDef: ExportedStruct) -> [DeclSyntax] { let typeName = structDef.swiftCallName - let liftCode = generateStructLiftCode(structDef: structDef) - let lowerCode = generateStructLowerCode(structDef: structDef) - let accessControl = structDef.explicitAccessControl.map { "\($0) " } ?? "" let lowerExternName = "swift_js_struct_lower_\(structDef.name)" let liftExternName = "swift_js_struct_lift_\(structDef.name)" let lowerFunctionName = "_bjs_struct_lower_\(structDef.name)" let liftFunctionName = "_bjs_struct_lift_\(structDef.name)" - let bridgedStructExtension: DeclSyntax = """ - extension \(raw: typeName): _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> \(raw: typeName) { - \(raw: liftCode.joined(separator: "\n")) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - \(raw: lowerCode.joined(separator: "\n")) - } - - \(raw: accessControl)init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = \(raw: lowerFunctionName)(jsObject.bridgeJSLowerParameter()) - defer { _swift_js_struct_cleanup(__bjs_cleanupId) } - self = Self.bridgeJSLiftParameter() - } - - \(raw: accessControl)func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() - return JSObject(id: UInt32(bitPattern: \(raw: liftFunctionName)())) - } + let printer = CodeFragmentPrinter() + printer.write("extension \(typeName): _BridgedSwiftStruct {") + printer.indent { + printer.write("@_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> \(typeName) {") + printer.indent { + printer.write(lines: generateStructLiftCode(structDef: structDef)) } - """ + printer.write("}") + printer.nextLine() - let lowerExternDecl = Self.renderStructExtern( - externName: lowerExternName, - functionName: lowerFunctionName, - signature: SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: [("objectId", .i32)], - returnType: .i32 + printer.write("@_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() {") + printer.indent { + printer.write(lines: generateStructLowerCode(structDef: structDef)) + } + printer.write("}") + printer.nextLine() + + let accessControl = structDef.explicitAccessControl.map { "\($0) " } ?? "" + printer.write( + multilineString: """ + \(accessControl)init(unsafelyCopying jsObject: JSObject) { + \(lowerFunctionName)(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + """ ) - ) - let liftExternDecl = Self.renderStructExtern( - externName: liftExternName, - functionName: liftFunctionName, - signature: SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: [], - returnType: .i32 + printer.nextLine() + + printer.write( + multilineString: """ + \(accessControl)func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: \(liftFunctionName)())) + } + """ ) - ) + } + printer.write("}") - return [bridgedStructExtension, lowerExternDecl, liftExternDecl] - } + let bridgedStructExtension: DeclSyntax = "\(raw: printer.lines.joined(separator: "\n"))" - private static func renderStructExtern( - externName: String, - functionName: String, - signature: FunctionSignatureSyntax - ) -> DeclSyntax { - let externFuncDecl = SwiftCodePattern.buildExternFunctionDecl( + let lowerExternDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: lowerExternDeclPrinter, moduleName: "bjs", - abiName: externName, - functionName: functionName, - signature: signature + abiName: lowerExternName, + functionName: lowerFunctionName, + abiParameters: [("objectId", .i32)], + returnType: nil ) - - let stubFuncDecl = FunctionDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.fileprivate)) - }, - funcKeyword: .keyword(.func), - name: .identifier(functionName), - signature: signature, - body: CodeBlockSyntax { - "fatalError(\"Only available on WebAssembly\")" - } + let liftExternDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: liftExternDeclPrinter, + moduleName: "bjs", + abiName: liftExternName, + functionName: liftFunctionName, + abiParameters: [], + returnType: .i32 ) - return DeclSyntax( - SwiftCodePattern.buildWasmConditionalCompilationDecls( - wasmDecl: DeclSyntax(externFuncDecl), - elseDecl: DeclSyntax(stubFuncDecl) - ) - ) + return [ + bridgedStructExtension, "\(raw: lowerExternDeclPrinter.lines.joined(separator: "\n"))", + "\(raw: liftExternDeclPrinter.lines.joined(separator: "\n"))", + ] } private func generateStructLiftCode(structDef: ExportedStruct) -> [String] { @@ -1382,7 +1288,7 @@ struct StructCodegen { } private func generateStructLowerCode(structDef: ExportedStruct) -> [String] { - var lines: [String] = [] + let printer = CodeFragmentPrinter() let instanceProps = structDef.properties.filter { !$0.isStatic } for property in instanceProps { @@ -1392,12 +1298,10 @@ struct StructCodegen { accessor: accessor, varPrefix: property.name ) - for stmt in statements { - lines.append(stmt.description) - } + printer.write(multilineString: CodeBlockItemListSyntax(statements).description) } - return lines + return printer.lines } } @@ -1408,7 +1312,7 @@ struct ProtocolCodegen { let wrapperName = "Any\(proto.name)" let protocolName = proto.name - var methodDecls: [DeclSyntax] = [] + var methodDecls: [CodeFragmentPrinter] = [] var externDecls: [DeclSyntax] = [] for method in proto.methods { @@ -1432,76 +1336,73 @@ struct ProtocolCodegen { ) // Build extern declaration using helper function - let externSignature = SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: builder.abiParameterSignatures, - returnType: builder.abiReturnType - ) - let externFuncDecl = SwiftCodePattern.buildExternFunctionDecl( + let externDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: externDeclPrinter, moduleName: moduleName, abiName: method.abiName, functionName: "_extern_\(method.name)", - signature: externSignature - ) - externDecls.append(DeclSyntax(externFuncDecl)) - let methodImplementation = DeclSyntax( - FunctionDeclSyntax( - name: .identifier(method.name), - signature: signature, - body: builder.getBody() - ) + abiParameters: builder.abiParameterSignatures, + returnType: builder.abiReturnType ) - - methodDecls.append(methodImplementation) + externDecls.append(DeclSyntax("\(raw: externDeclPrinter.lines.joined(separator: "\n"))")) + let methodImplPrinter = CodeFragmentPrinter() + methodImplPrinter.write("func \(method.name)\(signature) {") + methodImplPrinter.indent { + methodImplPrinter.write(lines: builder.body.lines) + } + methodImplPrinter.write("}") + methodDecls.append(methodImplPrinter) } - var propertyDecls: [DeclSyntax] = [] + var propertyDecls: [CodeFragmentPrinter] = [] for property in proto.properties { - let (propertyImpl, propertyExternDecls) = try renderProtocolProperty( + let propertyDeclPrinter = CodeFragmentPrinter() + let propertyExternDecls = try renderProtocolProperty( + printer: propertyDeclPrinter, property: property, protocolName: protocolName, moduleName: moduleName ) - propertyDecls.append(propertyImpl) + propertyDecls.append(propertyDeclPrinter) externDecls.append(contentsOf: propertyExternDecls) } - let structDecl = StructDeclSyntax( - name: .identifier(wrapperName), - inheritanceClause: InheritanceClauseSyntax( - inheritedTypesBuilder: { - InheritedTypeSyntax(type: IdentifierTypeSyntax(name: .identifier(protocolName))) - InheritedTypeSyntax(type: IdentifierTypeSyntax(name: .identifier("_BridgedSwiftProtocolWrapper"))) - } - ), - memberBlockBuilder: { - DeclSyntax( - """ - let jsObject: JSObject - """ - ).with(\.trailingTrivia, .newlines(2)) + let structDeclPrinter = CodeFragmentPrinter() + structDeclPrinter.write("struct \(wrapperName): \(protocolName), _BridgedSwiftProtocolWrapper {") + structDeclPrinter.indent { + structDeclPrinter.write("let jsObject: JSObject") + structDeclPrinter.nextLine() - for decl in methodDecls + propertyDecls { - decl.with(\.trailingTrivia, .newlines(2)) - } + for methodDecl in methodDecls { + structDeclPrinter.write(lines: methodDecl.lines) + structDeclPrinter.nextLine() + } - DeclSyntax( - """ + for decl in propertyDecls { + structDeclPrinter.write(lines: decl.lines) + structDeclPrinter.nextLine() + } + structDeclPrinter.write( + multilineString: """ static func bridgeJSLiftParameter(_ value: Int32) -> Self { - return \(raw: wrapperName)(jsObject: JSObject(id: UInt32(bitPattern: value))) + return \(wrapperName)(jsObject: JSObject(id: UInt32(bitPattern: value))) } """ - ) - } - ) - return [DeclSyntax(structDecl)] + externDecls + ) + } + structDeclPrinter.write("}") + + return ["\(raw: structDeclPrinter.lines.joined(separator: "\n"))"] + externDecls } private func renderProtocolProperty( + printer: CodeFragmentPrinter, property: ExportedProtocolProperty, protocolName: String, moduleName: String - ) throws -> (propertyDecl: DeclSyntax, externDecls: [DeclSyntax]) { + ) throws -> [DeclSyntax] { let getterAbiName = ABINameGenerator.generateABIName( baseName: property.name, operation: "get", @@ -1523,41 +1424,28 @@ struct ProtocolCodegen { try getterBuilder.liftReturnValue(returnType: property.type) // Build getter extern declaration using helper function - let getterExternSignature = SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: getterBuilder.abiParameterSignatures, - returnType: getterBuilder.abiReturnType - ) - let getterExternDecl = SwiftCodePattern.buildExternFunctionDecl( + let getterExternDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: getterExternDeclPrinter, moduleName: moduleName, abiName: getterAbiName, functionName: getterAbiName, - signature: getterExternSignature + abiParameters: getterBuilder.abiParameterSignatures, + returnType: getterBuilder.abiReturnType ) + let getterExternDecl = DeclSyntax("\(raw: getterExternDeclPrinter.lines.joined(separator: "\n"))") + var externDecls: [DeclSyntax] = [getterExternDecl] + + printer.write("var \(property.name): \(property.type.swiftType) {") + try printer.indent { + printer.write("get {") + printer.indent { + printer.write(lines: getterBuilder.body.lines) + } + printer.write("}") + + if property.isReadonly { return } - if property.isReadonly { - let propertyDecl = VariableDeclSyntax( - bindingSpecifier: .keyword(.var), - bindings: PatternBindingListSyntax { - PatternBindingSyntax( - pattern: IdentifierPatternSyntax(identifier: .identifier(property.name)), - typeAnnotation: TypeAnnotationSyntax( - type: IdentifierTypeSyntax(name: .identifier(property.type.swiftType)) - ), - accessorBlock: AccessorBlockSyntax( - accessors: .accessors( - AccessorDeclListSyntax { - AccessorDeclSyntax( - accessorSpecifier: .keyword(.get), - body: getterBuilder.getBody() - ) - } - ) - ) - ) - } - ) - return (DeclSyntax(propertyDecl), [DeclSyntax(getterExternDecl)]) - } else { let setterBuilder = ImportTS.CallJSEmission( moduleName: moduleName, abiName: setterAbiName, @@ -1568,44 +1456,27 @@ struct ProtocolCodegen { try setterBuilder.call(returnType: .void) // Build setter extern declaration using helper function - let setterExternSignature = SwiftSignatureBuilder.buildABIFunctionSignature( - abiParameters: setterBuilder.abiParameterSignatures, - returnType: setterBuilder.abiReturnType - ) - let setterExternDecl = SwiftCodePattern.buildExternFunctionDecl( + let setterExternDeclPrinter = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: setterExternDeclPrinter, moduleName: moduleName, abiName: setterAbiName, functionName: setterAbiName, - signature: setterExternSignature + abiParameters: setterBuilder.abiParameterSignatures, + returnType: setterBuilder.abiReturnType ) + let setterExternDecl = DeclSyntax("\(raw: setterExternDeclPrinter.lines.joined(separator: "\n"))") + externDecls.append(setterExternDecl) - let propertyDecl = VariableDeclSyntax( - bindingSpecifier: .keyword(.var), - bindings: PatternBindingListSyntax { - PatternBindingSyntax( - pattern: IdentifierPatternSyntax(identifier: .identifier(property.name)), - typeAnnotation: TypeAnnotationSyntax( - type: IdentifierTypeSyntax(name: .identifier(property.type.swiftType)) - ), - accessorBlock: AccessorBlockSyntax( - accessors: .accessors( - AccessorDeclListSyntax { - AccessorDeclSyntax( - accessorSpecifier: .keyword(.get), - body: getterBuilder.getBody() - ) - AccessorDeclSyntax( - accessorSpecifier: .keyword(.set), - body: setterBuilder.getBody() - ) - } - ) - ) - ) - } - ) - return (DeclSyntax(propertyDecl), [DeclSyntax(getterExternDecl), DeclSyntax(setterExternDecl)]) + printer.write("set {") + printer.indent { + printer.write(lines: setterBuilder.body.lines) + } + printer.write("}") } + printer.write("}") + + return externDecls } } @@ -1647,26 +1518,35 @@ extension BridgeType { case .float: return "Float" case .double: return "Double" case .string: return "String" + case .jsValue: return "JSValue" case .jsObject(nil): return "JSObject" case .jsObject(let name?): return name case .swiftHeapObject(let name): return name case .unsafePointer(let ptr): return ptr.swiftType case .swiftProtocol(let name): return "Any\(name)" case .void: return "Void" - case .optional(let wrappedType): return "Optional<\(wrappedType.swiftType)>" + case .nullable(let wrappedType, let kind): + return kind == .null ? "Optional<\(wrappedType.swiftType)>" : "JSUndefinedOr<\(wrappedType.swiftType)>" case .array(let elementType): return "[\(elementType.swiftType)]" + case .dictionary(let valueType): return "[String: \(valueType.swiftType)]" case .caseEnum(let name): return name case .rawValueEnum(let name, _): return name case .associatedValueEnum(let name): return name case .swiftStruct(let name): return name case .namespaceEnum(let name): return name - case .closure(let signature): + case .closure(let signature, let useJSTypedClosure): let paramTypes = signature.parameters.map { $0.swiftType }.joined(separator: ", ") let effectsStr = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") - return "(\(paramTypes))\(effectsStr) -> \(signature.returnType.swiftType)" + let closureType = "(\(paramTypes))\(effectsStr) -> \(signature.returnType.swiftType)" + return useJSTypedClosure ? "JSTypedClosure<\(closureType)>" : closureType } } + var isClosureType: Bool { + if case .closure = self { return true } + return false + } + struct LiftingIntrinsicInfo: Sendable { let parameters: [(name: String, type: WasmCoreType)] @@ -1676,6 +1556,7 @@ extension BridgeType { static let double = LiftingIntrinsicInfo(parameters: [("value", .f64)]) static let string = LiftingIntrinsicInfo(parameters: [("bytes", .i32), ("length", .i32)]) static let jsObject = LiftingIntrinsicInfo(parameters: [("value", .i32)]) + static let jsValue = LiftingIntrinsicInfo(parameters: [("kind", .i32), ("payload1", .i32), ("payload2", .f64)]) static let swiftHeapObject = LiftingIntrinsicInfo(parameters: [("value", .pointer)]) static let unsafePointer = LiftingIntrinsicInfo(parameters: [("pointer", .pointer)]) static let void = LiftingIntrinsicInfo(parameters: []) @@ -1693,13 +1574,18 @@ extension BridgeType { case .double: return .double case .string: return .string case .jsObject: return .jsObject + case .jsValue: return .jsValue case .swiftHeapObject: return .swiftHeapObject case .unsafePointer: return .unsafePointer case .swiftProtocol: return .jsObject case .void: return .void - case .optional(let wrappedType): + case .nullable(let wrappedType, _): + let wrappedInfo = try wrappedType.liftParameterInfo() + if wrappedInfo.parameters.isEmpty { + return LiftingIntrinsicInfo(parameters: []) + } var optionalParams: [(name: String, type: WasmCoreType)] = [("isSome", .i32)] - optionalParams.append(contentsOf: try wrappedType.liftParameterInfo().parameters) + optionalParams.append(contentsOf: wrappedInfo.parameters) return LiftingIntrinsicInfo(parameters: optionalParams) case .caseEnum: return .caseEnum case .rawValueEnum(_, let rawType): @@ -1712,7 +1598,7 @@ extension BridgeType { throw BridgeJSCoreError("Namespace enums are not supported to pass as parameters") case .closure: return LiftingIntrinsicInfo(parameters: [("callbackId", .i32)]) - case .array: + case .array, .dictionary: return LiftingIntrinsicInfo(parameters: []) } } @@ -1726,6 +1612,7 @@ extension BridgeType { static let double = LoweringIntrinsicInfo(returnType: .f64) static let string = LoweringIntrinsicInfo(returnType: nil) static let jsObject = LoweringIntrinsicInfo(returnType: .i32) + static let jsValue = LoweringIntrinsicInfo(returnType: nil) static let swiftHeapObject = LoweringIntrinsicInfo(returnType: .pointer) static let unsafePointer = LoweringIntrinsicInfo(returnType: .pointer) static let void = LoweringIntrinsicInfo(returnType: nil) @@ -1745,11 +1632,12 @@ extension BridgeType { case .double: return .double case .string: return .string case .jsObject: return .jsObject + case .jsValue: return .jsValue case .swiftHeapObject: return .swiftHeapObject case .unsafePointer: return .unsafePointer case .swiftProtocol: return .jsObject case .void: return .void - case .optional: return .optional + case .nullable: return .optional case .caseEnum: return .caseEnum case .rawValueEnum(_, let rawType): return rawType.loweringIntrinsicInfo @@ -1760,8 +1648,8 @@ extension BridgeType { case .namespaceEnum: throw BridgeJSCoreError("Namespace enums are not supported to pass as parameters") case .closure: - return .swiftHeapObject - case .array: + return .jsObject + case .array, .dictionary: return .array } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 9e5575c41..8f5ac511a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -32,17 +32,23 @@ public struct ImportTS { var decls: [DeclSyntax] = [] for skeleton in self.skeleton.children { - for getter in skeleton.globalGetters { - let getterDecls = try renderSwiftGlobalGetter(getter, topLevelDecls: &decls) - decls.append(contentsOf: getterDecls) + try withSpan("Render Global Getters") { + for getter in skeleton.globalGetters { + let getterDecls = try renderSwiftGlobalGetter(getter, topLevelDecls: &decls) + decls.append(contentsOf: getterDecls) + } } - for function in skeleton.functions { - let thunkDecls = try renderSwiftThunk(function, topLevelDecls: &decls) - decls.append(contentsOf: thunkDecls) + try withSpan("Render Functions") { + for function in skeleton.functions { + let thunkDecls = try renderSwiftThunk(function, topLevelDecls: &decls) + decls.append(contentsOf: thunkDecls) + } } - for type in skeleton.types { - let typeDecls = try renderSwiftType(type, topLevelDecls: &decls) - decls.append(contentsOf: typeDecls) + try withSpan("Render Types") { + for type in skeleton.types { + let typeDecls = try renderSwiftType(type, topLevelDecls: &decls) + decls.append(contentsOf: typeDecls) + } } } if decls.isEmpty { @@ -50,8 +56,10 @@ public struct ImportTS { return nil } - let format = BasicFormat() - return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n") + return withSpan("Format Import Glue") { + let format = BasicFormat() + return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n") + } } func renderSwiftGlobalGetter( @@ -77,12 +85,16 @@ public struct ImportTS { let moduleName: String let context: BridgeContext - var body: [CodeBlockItemSyntax] = [] - var abiParameterForwardings: [LabeledExprSyntax] = [] + var body = CodeFragmentPrinter() + var abiParameterForwardings: [String] = [] var abiParameterSignatures: [(name: String, type: WasmCoreType)] = [] var abiReturnType: WasmCoreType? // Track destructured variable names for multiple lowered parameters var destructuredVarNames: [String] = [] + // Stack-lowered parameters should be evaluated in reverse order to match LIFO stacks + var stackLoweringStmts: [String] = [] + // Values to extend lifetime during call + var valuesToExtendLifetimeDuringCall: [String] = [] init(moduleName: String, abiName: String, context: BridgeContext = .importTS) { self.moduleName = moduleName @@ -93,56 +105,37 @@ public struct ImportTS { func lowerParameter(param: Parameter) throws { let loweringInfo = try param.type.loweringParameterInfo(context: context) + switch param.type { + case .closure(let signature, useJSTypedClosure: false): + let jsTypedClosureType = BridgeType.closure(signature, useJSTypedClosure: true).swiftType + body.write("let \(param.name) = \(jsTypedClosureType)(\(param.name))") + // The just created JSObject is not owned by the caller unlike those passed in parameters, + // so we need to extend its lifetime during the call to ensure the JSObject.id is valid. + valuesToExtendLifetimeDuringCall.append(param.name) + default: + break + } + let initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + + if loweringInfo.loweredParameters.isEmpty { + stackLoweringStmts.insert("let _ = \(initializerExpr)", at: 0) + return + } + // Generate destructured variable names for all lowered parameters let destructuredNames = loweringInfo.loweredParameters.map { "\(param.name)\($0.name.capitalizedFirstLetter)" } - let initializerExpr: ExprSyntax - switch param.type { - case .closure(let signature): - initializerExpr = ExprSyntax( - "_BJS_Closure_\(raw: signature.mangleName).bridgeJSLower(\(raw: param.name))" - ) - default: - initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") - } - // Always add destructuring statement to body (unified for single and multiple) - let pattern: PatternSyntax + let pattern: String if destructuredNames.count == 1 { - pattern = PatternSyntax(IdentifierPatternSyntax(identifier: .identifier(destructuredNames[0]))) + pattern = destructuredNames[0] } else { - pattern = PatternSyntax( - TuplePatternSyntax { - for name in destructuredNames { - TuplePatternElementSyntax( - pattern: IdentifierPatternSyntax(identifier: .identifier(name)) - ) - } - } - ) + pattern = "(" + destructuredNames.joined(separator: ", ") + ")" } - body.append( - CodeBlockItemSyntax( - item: .decl( - DeclSyntax( - VariableDeclSyntax( - bindingSpecifier: .keyword(.let), - bindings: PatternBindingListSyntax { - PatternBindingSyntax( - pattern: pattern, - initializer: InitializerClauseSyntax( - value: initializerExpr - ) - ) - } - ) - ) - ) - ) - ) + body.write("let \(pattern) = \(initializerExpr)") destructuredVarNames.append(contentsOf: destructuredNames) // Add to signatures and forwardings (unified for both single and multiple) @@ -158,38 +151,36 @@ public struct ImportTS { // Always use destructured variable in call without labels // Swift allows omitting labels when they match parameter names - let callExpr = ExprSyntax("\(raw: destructuredNames[index])") - abiParameterForwardings.append( - LabeledExprSyntax(expression: callExpr) - ) + abiParameterForwardings.append(destructuredNames[index]) } } func call(returnType: BridgeType) throws { - // Build function call expression - let callExpr = FunctionCallExprSyntax( - calledExpression: ExprSyntax("\(raw: abiName)"), - leftParen: .leftParenToken(), - arguments: LabeledExprListSyntax { - for forwarding in abiParameterForwardings { - forwarding - } - }, - rightParen: .rightParenToken() - ) + let liftingInfo: BridgeType.LiftingReturnInfo = try returnType.liftingReturnInfo(context: context) + for stmt in stackLoweringStmts { + body.write(stmt.description) + } - if returnType == .void { - body.append(CodeBlockItemSyntax(item: .stmt(StmtSyntax(ExpressionStmtSyntax(expression: callExpr))))) - } else if returnType.usesSideChannelForOptionalReturn() { - // Side channel returns don't need "let ret =" - body.append(CodeBlockItemSyntax(item: .stmt(StmtSyntax(ExpressionStmtSyntax(expression: callExpr))))) + let assign = + (returnType == .void || returnType.usesSideChannelForOptionalReturn() || liftingInfo.valueToLift == nil) + ? "" : "let ret = " + let callExpr = "\(abiName)(\(abiParameterForwardings.joined(separator: ", ")))" + + if !valuesToExtendLifetimeDuringCall.isEmpty { + body.write( + "\(assign)withExtendedLifetime((\(valuesToExtendLifetimeDuringCall.joined(separator: ", ")))) {" + ) + body.indent { + body.write(callExpr) + } + body.write("}") } else { - body.append("let ret = \(raw: callExpr)") + body.write("\(assign)\(callExpr)") } // Add exception check for ImportTS context if context == .importTS { - body.append("if let error = _swift_js_take_exception() { throw error }") + body.write("if let error = _swift_js_take_exception() { throw error }") } } @@ -204,96 +195,47 @@ public struct ImportTS { if returnType.usesSideChannelForOptionalReturn() { // Side channel returns: extern function returns Void, value is retrieved via side channel abiReturnType = nil - body.append( - CodeBlockItemSyntax( - item: .stmt( - StmtSyntax( - ReturnStmtSyntax( - expression: ExprSyntax( - "\(raw: returnType.swiftType).bridgeJSLiftReturnFromSideChannel()" - ) - ) - ) - ) - ) - ) + body.write("return \(returnType.swiftType).bridgeJSLiftReturnFromSideChannel()") } else { abiReturnType = liftingInfo.valueToLift - let liftExpr: ExprSyntax + let liftExpr: String switch returnType { - case .closure(let signature): - liftExpr = ExprSyntax("_BJS_Closure_\(raw: signature.mangleName).bridgeJSLift(ret)") + case .closure(let signature, _): + liftExpr = "_BJS_Closure_\(signature.mangleName).bridgeJSLift(ret)" default: if liftingInfo.valueToLift != nil { - liftExpr = "\(raw: returnType.swiftType).bridgeJSLiftReturn(ret)" + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn(ret)" } else { - liftExpr = "\(raw: returnType.swiftType).bridgeJSLiftReturn()" + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn()" } } - body.append( - CodeBlockItemSyntax( - item: .stmt( - StmtSyntax( - ReturnStmtSyntax(expression: liftExpr) - ) - ) - ) - ) + body.write("return \(liftExpr)") } } - func getBody() -> CodeBlockSyntax { - return CodeBlockSyntax(statements: CodeBlockItemListSyntax(body)) - } - func assignThis(returnType: BridgeType) { guard case .jsObject = returnType else { preconditionFailure("assignThis can only be called with a jsObject return type") } abiReturnType = .i32 - body.append("self.jsObject = JSObject(id: UInt32(bitPattern: ret))") + body.write("self.jsObject = JSObject(id: UInt32(bitPattern: ret))") } func renderImportDecl() -> DeclSyntax { - let signature = SwiftSignatureBuilder.buildABIFunctionSignature( + let printer = CodeFragmentPrinter() + SwiftCodePattern.buildExternFunctionDecl( + printer: printer, + moduleName: moduleName, + abiName: abiName, + functionName: abiName, abiParameters: abiParameterSignatures, returnType: abiReturnType ) - - // Build extern function declaration (no body) - let externFuncDecl = FunctionDeclSyntax( - attributes: SwiftCodePattern.buildExternAttribute(moduleName: moduleName, abiName: abiName), - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.fileprivate)).with(\.trailingTrivia, .space) - }, - funcKeyword: .keyword(.func).with(\.trailingTrivia, .space), - name: .identifier(abiName), - signature: signature - ) - - // Build stub function declaration (with fatalError body) - let stubFuncDecl = FunctionDeclSyntax( - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.fileprivate)).with(\.trailingTrivia, .space) - }, - funcKeyword: .keyword(.func).with(\.trailingTrivia, .space), - name: .identifier(abiName), - signature: signature, - body: CodeBlockSyntax { - "fatalError(\"Only available on WebAssembly\")" - } - ) - - // Use conditional compilation helper - return DeclSyntax( - SwiftCodePattern.buildWasmConditionalCompilationDecls( - wasmDecl: DeclSyntax(externFuncDecl), - elseDecl: DeclSyntax(stubFuncDecl) - ) - ) + return "\(raw: printer.lines.joined(separator: "\n"))" } func renderThunkDecl(name: String, parameters: [Parameter], returnType: BridgeType) -> DeclSyntax { + let printer = CodeFragmentPrinter() let effects = Effects(isAsync: false, isThrows: true) let signature = SwiftSignatureBuilder.buildFunctionSignature( parameters: parameters, @@ -301,35 +243,28 @@ public struct ImportTS { effects: effects, useWildcardLabels: true ) - return DeclSyntax( - FunctionDeclSyntax( - name: .identifier(name.backtickIfNeeded()), - signature: signature, - body: CodeBlockSyntax { - body - } - ) - ) + printer.write("func \(name.backtickIfNeeded())\(signature) {") + printer.indent { + printer.write(lines: body.lines) + } + printer.write("}") + return "\(raw: printer.lines.joined(separator: "\n"))" } func renderConstructorDecl(parameters: [Parameter]) -> DeclSyntax { + let printer = CodeFragmentPrinter() let effects = Effects(isAsync: false, isThrows: true) - // Constructors don't have return types, so build signature without return clause - let signature = FunctionSignatureSyntax( - parameterClause: SwiftSignatureBuilder.buildParameterClause( - parameters: parameters, - useWildcardLabels: true - ), - effectSpecifiers: SwiftSignatureBuilder.buildEffectSpecifiers(effects: effects) - ) - return DeclSyntax( - InitializerDeclSyntax( - signature: signature, - bodyBuilder: { - body - } - ) + let parameterClause = SwiftSignatureBuilder.buildParameterClause( + parameters: parameters, + useWildcardLabels: true ) + let effectSpecifiers = SwiftSignatureBuilder.buildEffectSpecifiers(effects: effects) + printer.write("init\(parameterClause)\(effectSpecifiers.map { " \($0)" } ?? "") {") + printer.indent { + printer.write(lines: body.lines) + } + printer.write("}") + return "\(raw: printer.lines.joined(separator: "\n"))" } } @@ -398,6 +333,24 @@ public struct ImportTS { ] } + func renderStaticMethod(method: ImportedFunctionSkeleton) throws -> [DeclSyntax] { + let abiName = method.abiName(context: type, operation: "static") + let builder = CallJSEmission(moduleName: moduleName, abiName: abiName) + for param in method.parameters { + try builder.lowerParameter(param: param) + } + try builder.call(returnType: method.returnType) + try builder.liftReturnValue(returnType: method.returnType) + topLevelDecls.append(builder.renderImportDecl()) + return [ + builder.renderThunkDecl( + name: Self.thunkName(type: type, method: method), + parameters: method.parameters, + returnType: method.returnType + ) + ] + } + func renderConstructorDecl(constructor: ImportedConstructorSkeleton) throws -> [DeclSyntax] { let builder = CallJSEmission(moduleName: moduleName, abiName: constructor.abiName(context: type)) for param in constructor.parameters { @@ -462,6 +415,10 @@ public struct ImportTS { decls.append(contentsOf: try renderConstructorDecl(constructor: constructor)) } + for method in type.staticMethods { + decls.append(contentsOf: try renderStaticMethod(method: method)) + } + for getter in type.getters { decls.append(try renderGetterDecl(getter: getter)) } @@ -517,12 +474,17 @@ struct SwiftSignatureBuilder { returnType: BridgeType, effects: Effects? = nil, useWildcardLabels: Bool = false - ) -> FunctionSignatureSyntax { - return FunctionSignatureSyntax( - parameterClause: buildParameterClause(parameters: parameters, useWildcardLabels: useWildcardLabels), - effectSpecifiers: effects.flatMap { buildEffectSpecifiers(effects: $0) }, - returnClause: buildReturnClause(returnType: returnType) - ) + ) -> String { + let parameterClause = buildParameterClause(parameters: parameters, useWildcardLabels: useWildcardLabels) + let effectSpecifiers = effects.flatMap { buildEffectSpecifiers(effects: $0) } + let returnClause = buildReturnClause(returnType: returnType) + var out = "" + out += parameterClause + if let effectSpecifiers { + out += " \(effectSpecifiers)" + } + out += returnClause + return out } /// Builds a function signature for ABI/extern functions using WasmCoreType parameters @@ -536,12 +498,14 @@ struct SwiftSignatureBuilder { abiParameters: [(name: String, type: WasmCoreType)], returnType: WasmCoreType?, effects: Effects? = nil - ) -> FunctionSignatureSyntax { - return FunctionSignatureSyntax( - parameterClause: buildABIParameterClause(abiParameters: abiParameters), - effectSpecifiers: effects.flatMap { buildEffectSpecifiers(effects: $0) }, - returnClause: buildABIReturnClause(returnType: returnType) - ) + ) -> String { + var out = "" + out += buildABIParameterClause(abiParameters: abiParameters) + if let effects = effects, let effectSpecifiers = buildEffectSpecifiers(effects: effects) { + out += " \(effectSpecifiers)" + } + out += buildABIReturnClause(returnType: returnType) + return out } /// Builds a parameter clause from an array of Parameter structs @@ -556,48 +520,28 @@ struct SwiftSignatureBuilder { static func buildParameterClause( parameters: [Parameter], useWildcardLabels: Bool = false - ) -> FunctionParameterClauseSyntax { - return FunctionParameterClauseSyntax(parametersBuilder: { - for param in parameters { - let paramTypeSyntax = buildParameterTypeSyntax(from: param.type) - if useWildcardLabels { - // Always use wildcard labels: "_ name: Type" - FunctionParameterSyntax( - firstName: .wildcardToken(), - secondName: .identifier(param.name), - colon: .colonToken(), - type: paramTypeSyntax - ) - } else { - let label = param.label ?? param.name - if label == param.name { - // External label same as parameter name: "count: Int" - FunctionParameterSyntax( - firstName: .identifier(label), - secondName: nil, - colon: .colonToken(), - type: paramTypeSyntax - ) - } else if param.label == nil { - // No label specified: use wildcard "_ name: Type" - FunctionParameterSyntax( - firstName: .wildcardToken(), - secondName: .identifier(param.name), - colon: .colonToken(), - type: paramTypeSyntax - ) - } else { - // External label differs: "label count: Int" - FunctionParameterSyntax( - firstName: .identifier(label), - secondName: .identifier(param.name), - colon: .colonToken(), - type: paramTypeSyntax - ) - } - } + ) -> String { + var out = "(" + out += parameters.map { param in + let label = param.label ?? param.name + let paramType = buildParameterTypeSyntax(from: param.type) + + if useWildcardLabels { + // Always use wildcard labels: "_ name: Type" + return "_ \(param.name): \(paramType)" + } else if label == param.name { + // External label same as parameter name: "count: Int" + return "\(param.name): \(paramType)" + } else if param.label == nil { + // No label specified: use wildcard "_ name: Type" + return "_ \(param.name): \(paramType)" + } else { + // External label differs: "label count: Int" + return "\(label) \(param.name): \(paramType)" } - }) + }.joined(separator: ", ") + out += ")" + return out } /// Builds a parameter clause for ABI/extern functions @@ -605,79 +549,56 @@ struct SwiftSignatureBuilder { /// All parameters use wildcard labels: "_ name: Type" static func buildABIParameterClause( abiParameters: [(name: String, type: WasmCoreType)] - ) -> FunctionParameterClauseSyntax { - return FunctionParameterClauseSyntax(parametersBuilder: { - for param in abiParameters { - FunctionParameterSyntax( - firstName: .wildcardToken().with(\.trailingTrivia, .space), - secondName: .identifier(param.name), - type: IdentifierTypeSyntax(name: .identifier(param.type.swiftType)) - ) - } - }) + ) -> String { + "(" + + abiParameters.map { param in + "_ \(param.name): \(param.type.swiftType)" + }.joined(separator: ", ") + ")" } /// Builds a return clause from a BridgeType /// /// Always returns a ReturnClauseSyntax, including for Void types /// (to match original behavior that explicitly includes "-> Void") - static func buildReturnClause(returnType: BridgeType) -> ReturnClauseSyntax? { - return ReturnClauseSyntax( - arrow: .arrowToken(), - type: buildTypeSyntax(from: returnType) - ) + static func buildReturnClause(returnType: BridgeType) -> String { + return " -> \(returnType.swiftType)" } /// Builds a return clause for ABI/extern functions /// /// Returns nil for Void (when returnType is nil), otherwise returns a ReturnClauseSyntax - static func buildABIReturnClause(returnType: WasmCoreType?) -> ReturnClauseSyntax? { + static func buildABIReturnClause(returnType: WasmCoreType?) -> String { guard let returnType = returnType else { - return ReturnClauseSyntax( - arrow: .arrowToken(), - type: IdentifierTypeSyntax(name: .identifier("Void")) - ) + return " -> Void" } - return ReturnClauseSyntax( - arrow: .arrowToken(), - type: IdentifierTypeSyntax(name: .identifier(returnType.swiftType)) - ) + return " -> \(returnType.swiftType)" } /// Builds effect specifiers (async/throws) from an Effects struct /// /// Uses JSException as the thrown error type for throws clauses - static func buildEffectSpecifiers(effects: Effects) -> FunctionEffectSpecifiersSyntax? { + static func buildEffectSpecifiers(effects: Effects) -> String? { guard effects.isAsync || effects.isThrows else { return nil } - return FunctionEffectSpecifiersSyntax( - asyncSpecifier: effects.isAsync ? .keyword(.async) : nil, - throwsClause: effects.isThrows - ? ThrowsClauseSyntax( - throwsSpecifier: .keyword(.throws), - leftParen: .leftParenToken(), - type: IdentifierTypeSyntax(name: .identifier("JSException")), - rightParen: .rightParenToken() - ) : nil - ) + var items: [String] = [] + if effects.isAsync { items.append("async") } + if effects.isThrows { items.append("throws(JSException)") } + return items.joined(separator: " ") } /// Builds a TypeSyntax node from a BridgeType /// /// Converts BridgeType to its Swift type representation as a TypeSyntax node - static func buildTypeSyntax(from type: BridgeType) -> TypeSyntax { - let identifierType = IdentifierTypeSyntax(name: .identifier(type.swiftType)) - return TypeSyntax(identifierType) + static func buildTypeSyntax(from type: BridgeType) -> String { + return type.swiftType } /// Builds a parameter type syntax from a BridgeType. - /// - /// Swift closure parameters must be `@escaping` because they are boxed and can be invoked from JavaScript. - static func buildParameterTypeSyntax(from type: BridgeType) -> TypeSyntax { + static func buildParameterTypeSyntax(from type: BridgeType) -> String { switch type { - case .closure: - return TypeSyntax("@escaping \(raw: type.swiftType)") + case .closure(_, useJSTypedClosure: false): + return "@escaping \(type.swiftType)" default: return buildTypeSyntax(from: type) } @@ -687,166 +608,111 @@ struct SwiftSignatureBuilder { enum SwiftCodePattern { /// Builds a conditional compilation block with #if arch(wasm32) and #else fatalError static func buildWasmConditionalCompilation( - wasmBody: CodeBlockItemListSyntax - ) -> IfConfigDeclSyntax { - return IfConfigDeclSyntax( - clauses: IfConfigClauseListSyntax { - IfConfigClauseSyntax( - poundKeyword: .poundIfToken(), - condition: ExprSyntax("arch(wasm32)"), - elements: .statements(wasmBody) - ) - IfConfigClauseSyntax( - poundKeyword: .poundElseToken(), - elements: .statements( - CodeBlockItemListSyntax { - "fatalError(\"Only available on WebAssembly\")" - } - ) - ) - } - ) + printer: CodeFragmentPrinter, + wasmBody: (_ printer: CodeFragmentPrinter) -> Void + ) { + printer.write("#if arch(wasm32)") + wasmBody(printer) + printer.write("#else") + printer.write("fatalError(\"Only available on WebAssembly\")") + printer.write("#endif") } /// Builds a conditional compilation block with #if arch(wasm32) and #else for declarations static func buildWasmConditionalCompilationDecls( - wasmDecl: DeclSyntax, - elseDecl: DeclSyntax - ) -> IfConfigDeclSyntax { - return IfConfigDeclSyntax( - clauses: IfConfigClauseListSyntax { - IfConfigClauseSyntax( - poundKeyword: .poundIfToken(), - condition: ExprSyntax("arch(wasm32)"), - elements: .statements( - CodeBlockItemListSyntax { - CodeBlockItemSyntax(item: .decl(wasmDecl)) - } - ) - ) - IfConfigClauseSyntax( - poundKeyword: .poundElseToken(), - elements: .statements( - CodeBlockItemListSyntax { - CodeBlockItemSyntax(item: .decl(elseDecl)) - } - ) - ) - } + printer: CodeFragmentPrinter, + wasmDecl: (_ printer: CodeFragmentPrinter) -> Void, + elseDecl: (_ printer: CodeFragmentPrinter) -> Void + ) { + printer.write("#if arch(wasm32)") + wasmDecl(printer) + printer.write("#else") + elseDecl(printer) + printer.write("#endif") + } + static func buildExternFunctionDecl( + printer: CodeFragmentPrinter, + moduleName: String, + abiName: String, + functionName: String, + abiParameters: [(name: String, type: WasmCoreType)], + returnType: WasmCoreType? + ) { + let signature = SwiftSignatureBuilder.buildABIFunctionSignature( + abiParameters: abiParameters, + returnType: returnType + ) + buildExternFunctionDecl( + printer: printer, + moduleName: moduleName, + abiName: abiName, + functionName: functionName, + signature: signature, + parameterNames: abiParameters.map { $0.name } ) } /// Builds the @_extern attribute for WebAssembly extern function declarations /// Builds an @_extern function declaration (no body, just the declaration) static func buildExternFunctionDecl( + printer: CodeFragmentPrinter, moduleName: String, abiName: String, functionName: String, - signature: FunctionSignatureSyntax - ) -> FunctionDeclSyntax { - return FunctionDeclSyntax( - attributes: buildExternAttribute(moduleName: moduleName, abiName: abiName), - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.fileprivate)) + signature: String, + parameterNames: [String], + ) { + // NOTE: Due to a Swift compiler issue, we can't declare possibly inlined functions as @_extern + // https://github.com/swiftlang/swift/pull/87250 + let inModuleDeclName = "\(functionName)_extern" + buildWasmConditionalCompilationDecls( + printer: printer, + wasmDecl: { printer in + printer.write(buildExternAttribute(moduleName: moduleName, abiName: abiName)) + printer.write("fileprivate func \(inModuleDeclName)\(signature)") }, - funcKeyword: .keyword(.func), - name: .identifier(functionName), - signature: signature + elseDecl: { printer in + printer.write("fileprivate func \(inModuleDeclName)\(signature) {") + printer.indent { + printer.write("fatalError(\"Only available on WebAssembly\")") + } + printer.write("}") + } ) + printer.write("@inline(never) fileprivate func \(functionName)\(signature) {") + printer.indent { + printer.write("return \(inModuleDeclName)(\(parameterNames.joined(separator: ", ")))") + } + printer.write("}") } /// Builds the standard @_expose and @_cdecl attributes for WebAssembly-exposed functions - static func buildExposeAttributes(abiName: String) -> AttributeListSyntax { - return AttributeListSyntax { - #if canImport(SwiftSyntax602) - let exposeAttrArgs = AttributeSyntax.Arguments.argumentList( - [ - LabeledExprSyntax(label: nil, expression: DeclReferenceExprSyntax(baseName: "wasm")), - LabeledExprSyntax(label: nil, expression: StringLiteralExprSyntax(content: abiName)), - ] - ) - let cdeclAttrArgs = AttributeSyntax.Arguments.argumentList( - [ - LabeledExprSyntax(label: nil, expression: StringLiteralExprSyntax(content: abiName)) - ] - ) - #else - let exposeAttrArgs = AttributeSyntax.Arguments.exposeAttributeArguments( - ExposeAttributeArgumentsSyntax( - language: .identifier("wasm"), - comma: .commaToken(), - cxxName: StringLiteralExprSyntax(content: abiName) - ) - ) - let cdeclAttrArgs = AttributeSyntax.Arguments.string(StringLiteralExprSyntax(content: abiName)) - #endif - AttributeSyntax( - attributeName: IdentifierTypeSyntax(name: .identifier("_expose")), - leftParen: .leftParenToken(), - arguments: exposeAttrArgs, - rightParen: .rightParenToken() - ) - .with(\.trailingTrivia, .newline) - - AttributeSyntax( - attributeName: IdentifierTypeSyntax(name: .identifier("_cdecl")), - leftParen: .leftParenToken(), - arguments: cdeclAttrArgs, - rightParen: .rightParenToken() - ) - .with(\.trailingTrivia, .newline) - } + static func buildExposeAttributes(abiName: String) -> String { + return """ + @_expose(wasm, "\(abiName)") + @_cdecl("\(abiName)") + """ } /// Builds a function declaration with @_expose/@_cdecl attributes and conditional compilation static func buildExposedFunctionDecl( abiName: String, - signature: FunctionSignatureSyntax, - body: CodeBlockItemListSyntax - ) -> FunctionDeclSyntax { - let funcBody = CodeBlockSyntax { - buildWasmConditionalCompilation(wasmBody: body) + signature: String, + body: (CodeFragmentPrinter) -> Void + ) -> DeclSyntax { + let printer = CodeFragmentPrinter() + printer.write(buildExposeAttributes(abiName: abiName)) + printer.write("public func _\(abiName)\(signature) {") + printer.indent { + buildWasmConditionalCompilation(printer: printer, wasmBody: body) } - - return FunctionDeclSyntax( - attributes: buildExposeAttributes(abiName: abiName), - modifiers: DeclModifierListSyntax { - DeclModifierSyntax(name: .keyword(.public)) - }, - funcKeyword: .keyword(.func), - name: .identifier("_\(abiName)"), - signature: signature, - body: funcBody - ) + printer.write("}") + return "\(raw: printer.lines.joined(separator: "\n"))" } /// Builds the @_extern attribute for WebAssembly extern function declarations - static func buildExternAttribute(moduleName: String, abiName: String) -> AttributeListSyntax { - return AttributeListSyntax { - AttributeSyntax( - attributeName: IdentifierTypeSyntax(name: .identifier("_extern")), - leftParen: .leftParenToken(), - arguments: .argumentList( - LabeledExprListSyntax { - LabeledExprSyntax( - expression: ExprSyntax("wasm") - ) - LabeledExprSyntax( - label: .identifier("module"), - colon: .colonToken(), - expression: StringLiteralExprSyntax(content: moduleName) - ) - LabeledExprSyntax( - label: .identifier("name"), - colon: .colonToken(), - expression: StringLiteralExprSyntax(content: abiName) - ) - } - ), - rightParen: .rightParenToken() - ) - .with(\.trailingTrivia, .newline) - } + static func buildExternAttribute(moduleName: String, abiName: String) -> String { + return "@_extern(wasm, module: \"\(moduleName)\", name: \"\(abiName)\")" } } @@ -860,6 +726,11 @@ extension BridgeType { static let double = LoweringParameterInfo(loweredParameters: [("value", .f64)]) static let string = LoweringParameterInfo(loweredParameters: [("value", .i32)]) static let jsObject = LoweringParameterInfo(loweredParameters: [("value", .i32)]) + static let jsValue = LoweringParameterInfo(loweredParameters: [ + ("kind", .i32), + ("payload1", .i32), + ("payload2", .f64), + ]) static let void = LoweringParameterInfo(loweredParameters: []) } @@ -871,24 +742,15 @@ extension BridgeType { case .double: return .double case .string: return .string case .jsObject: return .jsObject + case .jsValue: return .jsValue case .void: return .void case .closure: - // Swift closure is boxed and passed to JS as a pointer. - return LoweringParameterInfo(loweredParameters: [("pointer", .pointer)]) + // Swift closure is passed to JS as a JS function reference. + return LoweringParameterInfo(loweredParameters: [("funcRef", .i32)]) case .unsafePointer: return LoweringParameterInfo(loweredParameters: [("pointer", .pointer)]) - case .swiftHeapObject(let className): - switch context { - case .importTS: - throw BridgeJSCoreError( - """ - swiftHeapObject '\(className)' is not supported in TypeScript imports. - Swift classes can only be used in @JS protocols where Swift owns the instance. - """ - ) - case .exportSwift: - return LoweringParameterInfo(loweredParameters: [("pointer", .pointer)]) - } + case .swiftHeapObject: + return LoweringParameterInfo(loweredParameters: [("pointer", .pointer)]) case .swiftProtocol: throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") case .caseEnum: @@ -899,13 +761,8 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: [("value", .i32)]) } case .rawValueEnum(_, let rawType): - switch context { - case .importTS: - return LoweringParameterInfo(loweredParameters: [("value", rawType.wasmCoreType ?? .i32)]) - case .exportSwift: - // For protocol export we return .i32 for String raw value type instead of nil - return LoweringParameterInfo(loweredParameters: [("value", rawType.wasmCoreType ?? .i32)]) - } + let wasmType = rawType.wasmCoreType ?? .i32 + return LoweringParameterInfo(loweredParameters: [("value", wasmType)]) case .associatedValueEnum: switch context { case .importTS: @@ -923,23 +780,13 @@ extension BridgeType { } case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as parameters") - case .optional(let wrappedType): - switch context { - case .importTS: - throw BridgeJSCoreError("Optional types are not yet supported in TypeScript imports") - case .exportSwift: - let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) - var params = [("isSome", WasmCoreType.i32)] - params.append(contentsOf: wrappedInfo.loweredParameters) - return LoweringParameterInfo(loweredParameters: params) - } - case .array: - switch context { - case .importTS: - throw BridgeJSCoreError("Array types are not yet supported in TypeScript imports") - case .exportSwift: - return LoweringParameterInfo(loweredParameters: []) - } + case .nullable(let wrappedType, _): + let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) + var params = [("isSome", WasmCoreType.i32)] + params.append(contentsOf: wrappedInfo.loweredParameters) + return LoweringParameterInfo(loweredParameters: params) + case .array, .dictionary: + return LoweringParameterInfo(loweredParameters: []) } } @@ -952,6 +799,7 @@ extension BridgeType { static let double = LiftingReturnInfo(valueToLift: .f64) static let string = LiftingReturnInfo(valueToLift: .i32) static let jsObject = LiftingReturnInfo(valueToLift: .i32) + static let jsValue = LiftingReturnInfo(valueToLift: nil) static let void = LiftingReturnInfo(valueToLift: nil) } @@ -965,24 +813,15 @@ extension BridgeType { case .double: return .double case .string: return .string case .jsObject: return .jsObject + case .jsValue: return .jsValue case .void: return .void case .closure: // JS returns a callback ID for closures, which Swift lifts to a typed closure. return LiftingReturnInfo(valueToLift: .i32) case .unsafePointer: return LiftingReturnInfo(valueToLift: .pointer) - case .swiftHeapObject(let className): - switch context { - case .importTS: - throw BridgeJSCoreError( - """ - swiftHeapObject '\(className)' cannot be returned from imported TypeScript functions. - JavaScript cannot create Swift heap objects. - """ - ) - case .exportSwift: - return LiftingReturnInfo(valueToLift: .pointer) - } + case .swiftHeapObject: + return LiftingReturnInfo(valueToLift: .pointer) case .swiftProtocol: throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures") case .caseEnum: @@ -993,13 +832,8 @@ extension BridgeType { return LiftingReturnInfo(valueToLift: .i32) } case .rawValueEnum(_, let rawType): - switch context { - case .importTS: - return LiftingReturnInfo(valueToLift: rawType.wasmCoreType ?? .i32) - case .exportSwift: - // For protocol export we return .i32 for String raw value type instead of nil - return LiftingReturnInfo(valueToLift: rawType.wasmCoreType ?? .i32) - } + let wasmType = rawType.wasmCoreType ?? .i32 + return LiftingReturnInfo(valueToLift: wasmType) case .associatedValueEnum: switch context { case .importTS: @@ -1017,21 +851,11 @@ extension BridgeType { } case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as return values") - case .optional(let wrappedType): - switch context { - case .importTS: - throw BridgeJSCoreError("Optional types are not yet supported in TypeScript imports") - case .exportSwift: - let wrappedInfo = try wrappedType.liftingReturnInfo(context: context) - return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) - } - case .array: - switch context { - case .importTS: - throw BridgeJSCoreError("Array types are not yet supported in TypeScript imports") - case .exportSwift: - return LiftingReturnInfo(valueToLift: nil) - } + case .nullable(let wrappedType, _): + let wrappedInfo = try wrappedType.liftingReturnInfo(context: context) + return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) + case .array, .dictionary: + return LiftingReturnInfo(valueToLift: nil) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift index e11bd4058..06fb422a9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift @@ -20,31 +20,294 @@ public struct ProgressReporting { } } +// MARK: - Profiling + +/// A simple time-profiler API +public final class Profiling { + nonisolated(unsafe) static var current: Profiling? + + let beginEntry: (_ label: String) -> Void + let endEntry: (_ label: String) -> Void + let finalize: () -> Void + + /// Create a profiling instance that outputs Trace Event Format, which + /// can be viewed in chrome://tracing or other compatible viewers. + /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit?usp=sharing + public static func traceEvent(output: @escaping (String) -> Void) -> Profiling { + let clock = ContinuousClock() + let startTime = clock.now + var firstEntry = true + + func formatTimestamp() -> Int { + let duration = startTime.duration(to: .now) + let (seconds, attoseconds) = duration.components + // Convert to microseconds + return Int(seconds * 1_000_000 + attoseconds / 1_000_000_000_000) + } + + return Profiling( + beginEntry: { label in + let entry = #"{"ph":"B","pid":1,"name":\#(JSON.serialize(label)),"ts":\#(formatTimestamp())}"# + if firstEntry { + firstEntry = false + output("[\n\(entry)") + } else { + output(",\n\(entry)") + } + }, + endEntry: { label in + output(#",\#n{"ph":"E","pid":1,"name":\#(JSON.serialize(label)),"ts":\#(formatTimestamp())}"#) + }, + finalize: { + output("]\n") + } + ) + } + + public init( + beginEntry: @escaping (_ label: String) -> Void, + endEntry: @escaping (_ label: String) -> Void, + finalize: @escaping () -> Void + ) { + self.beginEntry = beginEntry + self.endEntry = endEntry + self.finalize = finalize + } + + public static func with(_ makeCurrent: () -> Profiling?, body: @escaping () throws -> Void) rethrows -> Void { + guard let current = makeCurrent() else { + return try body() + } + defer { current.finalize() } + Profiling.current = current + defer { Profiling.current = nil } + return try body() + } +} + +/// Mark a span of code with a label and measure the duration. +public func withSpan(_ label: String, body: @escaping () throws -> T) rethrows -> T { + guard let profiling = Profiling.current else { + return try body() + } + profiling.beginEntry(label) + defer { + profiling.endEntry(label) + } + return try body() +} + +/// Foundation-less JSON serialization +private enum JSON { + static func serialize(_ value: String) -> String { + // https://www.ietf.org/rfc/rfc4627.txt + var output = "\"" + for scalar in value.unicodeScalars { + switch scalar { + case "\"": + output += "\\\"" + case "\\": + output += "\\\\" + case "\u{08}": + output += "\\b" + case "\u{0C}": + output += "\\f" + case "\n": + output += "\\n" + case "\r": + output += "\\r" + case "\t": + output += "\\t" + case "\u{20}"..."\u{21}", "\u{23}"..."\u{5B}", "\u{5D}"..."\u{10FFFF}": + output.unicodeScalars.append(scalar) + default: + var hex = String(scalar.value, radix: 16, uppercase: true) + hex = String(repeating: "0", count: 4 - hex.count) + hex + output += "\\u" + hex + } + } + output += "\"" + return output + } +} + // MARK: - DiagnosticError import SwiftSyntax +import class Foundation.ProcessInfo -struct DiagnosticError: Error { - let node: Syntax - let message: String - let hint: String? +public struct DiagnosticError: Error { + public let node: Syntax + public let message: String + public let hint: String? - init(node: some SyntaxProtocol, message: String, hint: String? = nil) { + public init(node: some SyntaxProtocol, message: String, hint: String? = nil) { self.node = Syntax(node) self.message = message self.hint = hint } - func formattedDescription(fileName: String) -> String { - let locationConverter = SourceLocationConverter(fileName: fileName, tree: node.root) - let location = locationConverter.location(for: node.position) - var description = "\(fileName):\(location.line):\(location.column): error: \(message)" + /// Formats the diagnostic error as a string. + /// + /// - Parameters: + /// - fileName: The name of the file to display in the output. + /// - colorize: Whether to colorize the output with ANSI escape sequences. + /// - Returns: The formatted diagnostic error string. + public func formattedDescription(fileName: String, colorize: Bool = Self.shouldColorize) -> String { + let displayFileName = fileName == "-" ? "" : fileName + let converter = SourceLocationConverter(fileName: displayFileName, tree: node.root) + let startLocation = converter.location(for: node.positionAfterSkippingLeadingTrivia) + let endLocation = converter.location(for: node.endPositionBeforeTrailingTrivia) + + let sourceText = node.root.description + let lines = sourceText.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) + let startLineIndex = max(0, min(lines.count - 1, startLocation.line - 1)) + let mainLine = String(lines[startLineIndex]) + + let lineNumberWidth = max(3, String(lines.count).count) + + let header: String = { + guard colorize else { + return "\(displayFileName):\(startLocation.line):\(startLocation.column): error: \(message)" + } + return + "\(displayFileName):\(startLocation.line):\(startLocation.column): \(ANSI.boldRed)error: \(ANSI.boldDefault)\(message)\(ANSI.reset)" + }() + + let highlightStartColumn = min(max(1, startLocation.column), mainLine.utf8.count + 1) + let availableColumns = max(0, mainLine.utf8.count - (highlightStartColumn - 1)) + let rawHighlightLength: Int = { + guard availableColumns > 0 else { return 0 } + if startLocation.line == endLocation.line { + return max(1, min(endLocation.column - startLocation.column, availableColumns)) + } else { + return min(1, availableColumns) + } + }() + let highlightLength = min(rawHighlightLength, availableColumns) + + let formattedMainLine: String = { + guard colorize, highlightLength > 0 else { return mainLine } + + let startIndex = Self.index(atUTF8Offset: highlightStartColumn - 1, in: mainLine) + let endIndex = Self.index(atUTF8Offset: highlightStartColumn - 1 + highlightLength, in: mainLine) + + let prefix = String(mainLine[..= 0, lineIndex < lines.count else { continue } + descriptionParts.append( + Self.formatSourceLine( + number: lineIndex + 1, + text: String(lines[lineIndex]), + width: lineNumberWidth, + colorize: colorize + ) + ) + } + + descriptionParts.append( + Self.formatSourceLine( + number: startLocation.line, + text: formattedMainLine, + width: lineNumberWidth, + colorize: colorize + ) + ) + + let pointerSpacing = max(0, highlightStartColumn - 1) + let pointerMessage: String = { + let pointer = String(repeating: " ", count: pointerSpacing) + "`- " + guard colorize else { return pointer + "error: \(message)" } + return pointer + "\(ANSI.boldRed)error: \(ANSI.boldDefault)\(message)\(ANSI.reset)" + }() + descriptionParts.append( + Self.formatSourceLine( + number: nil, + text: pointerMessage, + width: lineNumberWidth, + colorize: colorize + ) + ) + + if startLineIndex + 1 < lines.count { + descriptionParts.append( + Self.formatSourceLine( + number: startLocation.line + 1, + text: String(lines[startLineIndex + 1]), + width: lineNumberWidth, + colorize: colorize + ) + ) + } + if let hint { - description += "\nHint: \(hint)" + descriptionParts.append("Hint: \(hint)") } - return description + + return descriptionParts.joined(separator: "\n") + } + + private static func formatSourceLine( + number: Int?, + text: String, + width: Int, + colorize: Bool + ) -> String { + let gutter: String + if let number { + let paddedNumber = String(repeating: " ", count: max(0, width - String(number).count)) + String(number) + gutter = colorize ? ANSI.cyan + paddedNumber + ANSI.reset : paddedNumber + } else { + gutter = String(repeating: " ", count: width) + } + return "\(gutter) | \(text)" + } + + public static var shouldColorize: Bool { + let env = ProcessInfo.processInfo.environment + let termIsDumb = env["TERM"] == "dumb" + return env["NO_COLOR"] == nil && !termIsDumb + } + + private static func index(atUTF8Offset offset: Int, in line: String) -> String.Index { + let clamped = max(0, min(offset, line.utf8.count)) + let utf8Index = line.utf8.index(line.utf8.startIndex, offsetBy: clamped) + // String.Index initializer is guaranteed to succeed because the UTF8 index comes from the same string. + return String.Index(utf8Index, within: line)! } } +/// Carries the diagnostics produced during SwiftToSkeleton. +public struct BridgeJSCoreDiagnosticError: Swift.Error, CustomStringConvertible { + public let diagnostics: [(file: String, diagnostic: DiagnosticError)] + + public init(diagnostics: [(file: String, diagnostic: DiagnosticError)]) { + self.diagnostics = diagnostics + } + + public var description: String { + diagnostics + .map { (file, diag) in diag.formattedDescription(fileName: file, colorize: false) } + .joined(separator: "\n") + } +} + +private enum ANSI { + static let reset = "\u{001B}[0;0m" + static let boldRed = "\u{001B}[1;31m" + static let boldDefault = "\u{001B}[1;39m" + static let cyan = "\u{001B}[0;36m" + static let underline = "\u{001B}[4;39m" +} // MARK: - BridgeJSCoreError diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index ea79d3f3b..0cf5a567f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -66,21 +66,22 @@ public final class SwiftToSkeleton { ) } - importedFiles.append( - ImportedFileSkeleton( - functions: importCollector.importedFunctions, - types: importCollector.importedTypes, - globalGetters: importCollector.importedGlobalGetters - ) + let importedFile = ImportedFileSkeleton( + functions: importCollector.importedFunctions, + types: importCollector.importedTypes, + globalGetters: importCollector.importedGlobalGetters ) + if !importedFile.isEmpty { + importedFiles.append(importedFile) + } exportCollector.finalize(&exported) } if !perSourceErrors.isEmpty { - let allErrors = perSourceErrors.flatMap { inputFilePath, errors in - errors.map { $0.formattedDescription(fileName: inputFilePath) } + let diagnostics = perSourceErrors.flatMap { inputFilePath, errors in + errors.map { (file: inputFilePath, diagnostic: $0) } } - throw BridgeJSCoreError(allErrors.joined(separator: "\n")) + throw BridgeJSCoreDiagnosticError(diagnostics: diagnostics) } let importedSkeleton: ImportedModuleSkeleton? = { let module = ImportedModuleSkeleton(children: importedFiles) @@ -90,7 +91,8 @@ public final class SwiftToSkeleton { return module }() - return BridgeJSSkeleton(moduleName: moduleName, exported: exported, imported: importedSkeleton) + let exportedSkeleton: ExportedSkeleton? = exported.isEmpty ? nil : exported + return BridgeJSSkeleton(moduleName: moduleName, exported: exportedSkeleton, imported: importedSkeleton) } func lookupType(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { @@ -98,6 +100,17 @@ public final class SwiftToSkeleton { return lookupType(for: attributedType.baseType, errors: &errors) } + if let identifierType = type.as(IdentifierTypeSyntax.self), + identifierType.name.text == "JSTypedClosure", + let genericArgs = identifierType.genericArgumentClause?.arguments, + genericArgs.count == 1, + let argument = genericArgs.firstAsTypeSyntax, + let signatureType = lookupType(for: argument, errors: &errors), + case .closure(let signature, false) = signatureType + { + return .closure(signature, useJSTypedClosure: true) + } + // (T1, T2, ...) -> R if let functionType = type.as(FunctionTypeSyntax.self) { var parameters: [BridgeType] = [] @@ -122,7 +135,8 @@ public final class SwiftToSkeleton { moduleName: moduleName, isAsync: isAsync, isThrows: isThrows - ) + ), + useJSTypedClosure: false ) } @@ -130,7 +144,31 @@ public final class SwiftToSkeleton { if let optionalType = type.as(OptionalTypeSyntax.self) { let wrappedType = optionalType.wrappedType if let baseType = lookupType(for: wrappedType, errors: &errors) { - return .optional(baseType) + return .nullable(baseType, .null) + } + } + // JSUndefinedOr + if let identifierType = type.as(IdentifierTypeSyntax.self), + identifierType.name.text == "JSUndefinedOr", + let genericArgs = identifierType.genericArgumentClause?.arguments, + genericArgs.count == 1, + let argType = TypeSyntax(genericArgs.first?.argument) + { + if let baseType = lookupType(for: argType, errors: &errors) { + return .nullable(baseType, .undefined) + } + } + // JavaScriptKit.JSUndefinedOr + if let memberType = type.as(MemberTypeSyntax.self), + let baseType = memberType.baseType.as(IdentifierTypeSyntax.self), + baseType.name.text == "JavaScriptKit", + memberType.name.text == "JSUndefinedOr", + let genericArgs = memberType.genericArgumentClause?.arguments, + genericArgs.count == 1, + let argType = TypeSyntax(genericArgs.first?.argument) + { + if let wrappedType = lookupType(for: argType, errors: &errors) { + return .nullable(wrappedType, .undefined) } } // Optional @@ -141,7 +179,7 @@ public final class SwiftToSkeleton { let argType = TypeSyntax(genericArgs.first?.argument) { if let baseType = lookupType(for: argType, errors: &errors) { - return .optional(baseType) + return .nullable(baseType, .null) } } // Swift.Optional @@ -154,7 +192,7 @@ public final class SwiftToSkeleton { let argType = TypeSyntax(genericArgs.first?.argument) { if let wrappedType = lookupType(for: argType, errors: &errors) { - return .optional(wrappedType) + return .nullable(wrappedType, .null) } } // [T] @@ -187,6 +225,45 @@ public final class SwiftToSkeleton { return .array(elementType) } } + // [String: T] + if let dictType = type.as(DictionaryTypeSyntax.self) { + if let keyType = lookupType(for: dictType.key, errors: &errors), + keyType == .string, + let valueType = lookupType(for: dictType.value, errors: &errors) + { + return .dictionary(valueType) + } + } + // Dictionary + if let identifierType = type.as(IdentifierTypeSyntax.self), + identifierType.name.text == "Dictionary", + let genericArgs = identifierType.genericArgumentClause?.arguments, + genericArgs.count == 2, + let keyArg = TypeSyntax(genericArgs.first?.argument), + let valueArg = TypeSyntax(genericArgs.last?.argument), + let keyType = lookupType(for: keyArg, errors: &errors), + keyType == .string + { + if let valueType = lookupType(for: valueArg, errors: &errors) { + return .dictionary(valueType) + } + } + // Swift.Dictionary + if let memberType = type.as(MemberTypeSyntax.self), + let baseType = memberType.baseType.as(IdentifierTypeSyntax.self), + baseType.name.text == "Swift", + memberType.name.text == "Dictionary", + let genericArgs = memberType.genericArgumentClause?.arguments, + genericArgs.count == 2, + let keyArg = TypeSyntax(genericArgs.first?.argument), + let valueArg = TypeSyntax(genericArgs.last?.argument), + let keyType = lookupType(for: keyArg, errors: &errors), + keyType == .string + { + if let valueType = lookupType(for: valueArg, errors: &errors) { + return .dictionary(valueType) + } + } if let aliasDecl = typeDeclResolver.resolveTypeAlias(type) { if let resolvedType = lookupType(for: aliasDecl.initializer.value, errors: &errors) { return resolvedType @@ -368,22 +445,28 @@ private enum ExportSwiftConstants { static let supportedRawTypes = SwiftEnumRawType.allCases.map { $0.rawValue } } +extension AttributeSyntax { + /// The attribute name as text when it is a simple identifier (e.g. "JS", "JSFunction"). + /// Prefer this over `attributeName.trimmedDescription` for name checks to avoid unnecessary string work. + fileprivate var attributeNameText: String? { + attributeName.as(IdentifierTypeSyntax.self)?.name.text + } +} + extension AttributeListSyntax { func hasJSAttribute() -> Bool { firstJSAttribute != nil } var firstJSAttribute: AttributeSyntax? { - first(where: { - $0.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JS" - })?.as(AttributeSyntax.self) + first(where: { $0.as(AttributeSyntax.self)?.attributeNameText == "JS" })?.as(AttributeSyntax.self) } /// Returns true if any attribute has the given name (e.g. "JSClass"). func hasAttribute(name: String) -> Bool { contains { attribute in guard let syntax = attribute.as(AttributeSyntax.self) else { return false } - return syntax.attributeName.trimmedDescription == name + return syntax.attributeNameText == name } } } @@ -535,7 +618,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { switch type { case .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name): enumName = name - case .optional(let wrappedType): + case .nullable(let wrappedType, _): switch wrappedType { case .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name): enumName = name @@ -584,7 +667,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let expr = defaultClause.value if expr.is(NilLiteralExprSyntax.self) { - guard case .optional(_) = type else { + guard case .nullable = type else { diagnose( node: expr, message: "nil is only valid for optional parameters", @@ -640,10 +723,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let isStructType: Bool let expectedTypeName: String? switch type { - case .swiftStruct(let name), .optional(.swiftStruct(let name)): + case .swiftStruct(let name), .nullable(.swiftStruct(let name), _): isStructType = true expectedTypeName = name.split(separator: ".").last.map(String.init) - case .swiftHeapObject(let name), .optional(.swiftHeapObject(let name)): + case .swiftHeapObject(let name), .nullable(.swiftHeapObject(let name), _): isStructType = false expectedTypeName = name.split(separator: ".").last.map(String.init) default: @@ -779,7 +862,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { switch type { case .array(let element): elementType = element - case .optional(.array(let element)): + case .nullable(.array(let element), _): elementType = element default: diagnose( @@ -818,7 +901,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let type = resolvedType else { continue // Skip unsupported types } - if case .closure(let signature) = type { + if case .closure(let signature, _) = type { if signature.isAsync { diagnose( node: param.type, @@ -834,11 +917,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { continue } } - if case .optional(let wrappedType) = type, wrappedType.isOptional { + if case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription) continue } - if case .optional(let wrappedType) = type, wrappedType.isOptional { + if case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription) continue } @@ -960,7 +1043,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { if let returnClause = node.signature.returnClause { let resolvedType = withLookupErrors { self.parent.lookupType(for: returnClause.type, errors: &$0) } - if let type = resolvedType, case .optional(let wrappedType) = type, wrappedType.isOptional { + if let type = resolvedType, case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: returnClause.type, type: returnClause.type.trimmedDescription) return nil } @@ -990,7 +1073,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } let isNamespaceEnum = exportedEnumByName[enumKey]?.cases.isEmpty ?? true - staticContext = isNamespaceEnum ? .namespaceEnum : .enumName(enumName) + let swiftCallName = exportedEnumByName[enumKey]?.swiftCallName ?? enumName + staticContext = isNamespaceEnum ? .namespaceEnum(swiftCallName) : .enumName(enumName) case .protocolBody(_, _): return nil case .structBody(let structName, _): @@ -1187,7 +1271,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } let isNamespaceEnum = exportedEnumByName[enumKey]?.cases.isEmpty ?? true - staticContext = isStatic ? (isNamespaceEnum ? .namespaceEnum : .enumName(enumName)) : nil + // Use swiftCallName for the full Swift call path (handles nested enums correctly) + let swiftCallName = exportedEnumByName[enumKey]?.swiftCallName ?? enumName + staticContext = + isStatic ? (isNamespaceEnum ? .namespaceEnum(swiftCallName) : .enumName(swiftCallName)) : nil case .topLevel: diagnose(node: node, message: "@JS var must be inside a @JS class or enum") return .skipChildren @@ -1392,18 +1479,20 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { for enumCase in exportedEnum.cases { for associatedValue in enumCase.associatedValues { switch associatedValue.type { - case .string, .int, .float, .double, .bool: + case .string, .int, .float, .double, .bool, .caseEnum, .rawValueEnum, + .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: break - case .optional(let wrappedType): + case .nullable(let wrappedType, _): switch wrappedType { - case .string, .int, .float, .double, .bool: + case .string, .int, .float, .double, .bool, .caseEnum, .rawValueEnum, + .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: break default: diagnose( node: node, message: "Unsupported associated value type: \(associatedValue.type.swiftType)", hint: - "Only primitive types and optional primitives (String?, Int?, Float?, Double?, Bool?) are supported in associated-value enums" + "Only primitive types, enums, structs, classes, JSObject, arrays, and their optionals are supported in associated-value enums" ) } default: @@ -1411,7 +1500,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { node: node, message: "Unsupported associated value type: \(associatedValue.type.swiftType)", hint: - "Only primitive types and optional primitives (String?, Int?, Float?, Double?, Bool?) are supported in associated-value enums" + "Only primitive types, enums, structs, classes, JSObject, arrays, and their optionals are supported in associated-value enums" ) } } @@ -1583,7 +1672,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { if let returnClause = node.signature.returnClause { let resolvedType = withLookupErrors { self.parent.lookupType(for: returnClause.type, errors: &$0) } - if let type = resolvedType, case .optional(let wrappedType) = type, wrappedType.isOptional { + if let type = resolvedType, case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: returnClause.type, type: returnClause.type.trimmedDescription) return nil } @@ -1808,7 +1897,7 @@ fileprivate extension BridgeType { switch (self, expectedType) { case let (lhs, rhs) where lhs == rhs: return true - case (.optional(let wrapped), expectedType): + case (.nullable(let wrapped, _), expectedType): return wrapped == expectedType default: return false @@ -1852,7 +1941,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { private let inputFilePath: String private var jsClassNames: Set private let parent: SwiftToSkeleton - // MARK: - State Management enum State { @@ -1872,6 +1960,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let from: JSImportFrom? var constructor: ImportedConstructorSkeleton? var methods: [ImportedFunctionSkeleton] + var staticMethods: [ImportedFunctionSkeleton] var getters: [ImportedGetterSkeleton] var setters: [ImportedSetterSkeleton] } @@ -1886,9 +1975,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } static func firstJSFunctionAttribute(_ attributes: AttributeListSyntax?) -> AttributeSyntax? { - attributes?.first { attribute in - attribute.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JSFunction" - }?.as(AttributeSyntax.self) + firstAttribute(attributes, named: "JSFunction") } static func hasJSGetterAttribute(_ attributes: AttributeListSyntax?) -> Bool { @@ -1896,9 +1983,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } static func firstJSGetterAttribute(_ attributes: AttributeListSyntax?) -> AttributeSyntax? { - attributes?.first { attribute in - attribute.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JSGetter" - }?.as(AttributeSyntax.self) + firstAttribute(attributes, named: "JSGetter") } static func hasJSSetterAttribute(_ attributes: AttributeListSyntax?) -> Bool { @@ -1906,9 +1991,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } static func firstJSSetterAttribute(_ attributes: AttributeListSyntax?) -> AttributeSyntax? { - attributes?.first { attribute in - attribute.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JSSetter" - }?.as(AttributeSyntax.self) + firstAttribute(attributes, named: "JSSetter") } static func hasJSClassAttribute(_ attributes: AttributeListSyntax?) -> Bool { @@ -1916,16 +1999,18 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } static func firstJSClassAttribute(_ attributes: AttributeListSyntax?) -> AttributeSyntax? { - attributes?.first { attribute in - attribute.as(AttributeSyntax.self)?.attributeName.trimmedDescription == "JSClass" - }?.as(AttributeSyntax.self) + firstAttribute(attributes, named: "JSClass") + } + + static func firstAttribute(_ attributes: AttributeListSyntax?, named name: String) -> AttributeSyntax? { + attributes?.first { $0.as(AttributeSyntax.self)?.attributeNameText == name }?.as(AttributeSyntax.self) } static func hasAttribute(_ attributes: AttributeListSyntax?, name: String) -> Bool { guard let attributes else { return false } return attributes.contains { attribute in guard let syntax = attribute.as(AttributeSyntax.self) else { return false } - return syntax.attributeName.trimmedDescription == name + return syntax.attributeNameText == name } } @@ -1983,7 +2068,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { DiagnosticError( node: node, message: "@\(attributeName) declarations must be throws.", - hint: "Declare the function as 'throws (JSException)'." + hint: "Declare the function as 'throws(JSException)'." ) ) return nil @@ -2090,6 +2175,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { from: nil, constructor: nil, methods: [], + staticMethods: [], getters: [], setters: [] ) @@ -2103,6 +2189,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { from: from, constructor: nil, methods: [], + staticMethods: [], getters: [], setters: [] ) @@ -2117,6 +2204,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { from: type.from, constructor: type.constructor, methods: type.methods, + staticMethods: type.staticMethods, getters: type.getters, setters: type.setters, documentation: nil @@ -2161,12 +2249,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { // MARK: - Visitor Methods - override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { - let typeName = node.extendedType.trimmedDescription - collectStaticMembers(in: node.memberBlock.members, typeName: typeName) - return .skipChildren - } - override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { switch state { case .topLevel: @@ -2187,7 +2269,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { private func handleTopLevelFunction(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { if let jsFunction = AttributeChecker.firstJSFunctionAttribute(node.attributes), - let function = parseFunction(jsFunction, node, enclosingTypeName: nil, isStaticMember: true) + let function = parseFunction(jsFunction, node) { importedFunctions.append(function) return .skipChildren @@ -2212,13 +2294,11 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { type: inout CurrentType ) -> Bool { if let jsFunction = AttributeChecker.firstJSFunctionAttribute(node.attributes) { - if isStaticMember { - parseFunction(jsFunction, node, enclosingTypeName: typeName, isStaticMember: true).map { - importedFunctions.append($0) - } - } else { - parseFunction(jsFunction, node, enclosingTypeName: typeName, isStaticMember: false).map { - type.methods.append($0) + if let method = parseFunction(jsFunction, node) { + if isStaticMember { + type.staticMethods.append(method) + } else { + type.methods.append(method) } } return true @@ -2309,38 +2389,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } } - // MARK: - Member Collection - - private func collectStaticMembers(in members: MemberBlockItemListSyntax, typeName: String) { - for member in members { - if let function = member.decl.as(FunctionDeclSyntax.self) { - if let jsFunction = AttributeChecker.firstJSFunctionAttribute(function.attributes), - let parsed = parseFunction(jsFunction, function, enclosingTypeName: typeName, isStaticMember: true) - { - importedFunctions.append(parsed) - } else if AttributeChecker.hasJSSetterAttribute(function.attributes) { - errors.append( - DiagnosticError( - node: function, - message: - "@JSSetter is not supported for static members. Use it only for instance members in @JSClass types." - ) - ) - } - } else if let variable = member.decl.as(VariableDeclSyntax.self), - AttributeChecker.hasJSGetterAttribute(variable.attributes) - { - errors.append( - DiagnosticError( - node: variable, - message: - "@JSGetter is not supported for static members. Use it only for instance members in @JSClass types." - ) - ) - } - } - } - // MARK: - Parsing Methods private func parseConstructor( @@ -2361,8 +2409,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { private func parseFunction( _ jsFunction: AttributeSyntax, _ node: FunctionDeclSyntax, - enclosingTypeName: String?, - isStaticMember: Bool ) -> ImportedFunctionSkeleton? { guard validateEffects(node.signature.effectSpecifiers, node: node, attributeName: "JSFunction") != nil else { @@ -2372,12 +2418,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) let jsName = AttributeChecker.extractJSName(from: jsFunction) let from = AttributeChecker.extractJSImportFrom(from: jsFunction) - let name: String - if isStaticMember, let enclosingTypeName { - name = "\(enclosingTypeName)_\(baseName)" - } else { - name = baseName - } + let name = baseName let parameters = parseParameters(from: node.signature.parameterClause) let returnType: BridgeType @@ -2508,3 +2549,18 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } } } + +extension GenericArgumentListSyntax { + /// Compatibility helper for accessing the first argument as a TypeSyntax + /// + /// Note: SwiftSyntax 601 and later support InlineArrayTypeSyntax and + /// ``GenericArgumentSyntax/argument`` is now a ``TypeSyntax`` or ``ExprSyntax``. + fileprivate var firstAsTypeSyntax: TypeSyntax? { + guard let first = self.first else { return nil } + #if canImport(SwiftSyntax601) + return first.argument.as(TypeSyntax.self) + #else + return TypeSyntax(first.argument) + #endif + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 60b55cd47..3c7b197a4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -11,6 +11,7 @@ public struct BridgeJSLink { var skeletons: [BridgeJSSkeleton] = [] let sharedMemory: Bool private let namespaceBuilder = NamespaceBuilder() + private let intrinsicRegistry = JSIntrinsicRegistry() public init( skeletons: [BridgeJSSkeleton] = [], @@ -50,23 +51,33 @@ public struct BridgeJSLink { """ let swiftHeapObjectClassJs = """ + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } """ @@ -245,17 +256,11 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedStorageToReturnOptionalFloat);", "let \(JSGlueVariableScope.reservedStorageToReturnOptionalDouble);", "let \(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject);", - "let \(JSGlueVariableScope.reservedTmpRetTag);", - "let \(JSGlueVariableScope.reservedTmpRetStrings) = [];", - "let \(JSGlueVariableScope.reservedTmpRetInts) = [];", - "let \(JSGlueVariableScope.reservedTmpRetF32s) = [];", - "let \(JSGlueVariableScope.reservedTmpRetF64s) = [];", - "let \(JSGlueVariableScope.reservedTmpParamInts) = [];", - "let \(JSGlueVariableScope.reservedTmpParamF32s) = [];", - "let \(JSGlueVariableScope.reservedTmpParamF64s) = [];", - "let \(JSGlueVariableScope.reservedTmpRetPointers) = [];", - "let \(JSGlueVariableScope.reservedTmpParamPointers) = [];", - "let \(JSGlueVariableScope.reservedTmpStructCleanups) = [];", + "let \(JSGlueVariableScope.reservedStringStack) = [];", + "let \(JSGlueVariableScope.reservedI32Stack) = [];", + "let \(JSGlueVariableScope.reservedF32Stack) = [];", + "let \(JSGlueVariableScope.reservedF64Stack) = [];", + "let \(JSGlueVariableScope.reservedPointerStack) = [];", "const \(JSGlueVariableScope.reservedEnumHelpers) = {};", "const \(JSGlueVariableScope.reservedStructHelpers) = {};", "", @@ -264,51 +269,11 @@ public struct BridgeJSLink { ] } - /// Checks if a skeleton contains any closure types - private func hasClosureTypes(in skeleton: ExportedSkeleton) -> Bool { - for function in skeleton.functions { - if containsClosureType(in: function.parameters) || containsClosureType(in: function.returnType) { - return true - } - } - for klass in skeleton.classes { - if let constructor = klass.constructor, containsClosureType(in: constructor.parameters) { - return true - } - for method in klass.methods { - if containsClosureType(in: method.parameters) || containsClosureType(in: method.returnType) { - return true - } - } - for property in klass.properties { - if containsClosureType(in: property.type) { - return true - } - } - } - return false - } - - private func containsClosureType(in parameters: [Parameter]) -> Bool { - parameters.contains { containsClosureType(in: $0.type) } - } - - private func containsClosureType(in type: BridgeType) -> Bool { - switch type { - case .closure: - return true - case .optional(let wrapped): - return containsClosureType(in: wrapped) - default: - return false - } - } - - private func generateAddImports(needsImportsObject: Bool) -> CodeFragmentPrinter { + private func generateAddImports(needsImportsObject: Bool) throws -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() let allStructs = skeletons.compactMap { $0.exported?.structs }.flatMap { $0 } printer.write("return {") - printer.indent { + try printer.indent { printer.write(lines: [ "/**", " * @param {WebAssembly.Imports} importObject", @@ -316,7 +281,7 @@ public struct BridgeJSLink { "addImports: (importObject, importsContext) => {", ]) - printer.indent { + try printer.indent { printer.write(lines: [ "bjs = {};", "importObject[\"bjs\"] = bjs;", @@ -341,6 +306,9 @@ public struct BridgeJSLink { printer.write( "const source = \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).getObject(sourceId);" ) + printer.write( + "\(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).release(sourceId);" + ) printer.write( "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, bytesPtr);" ) @@ -385,24 +353,19 @@ public struct BridgeJSLink { printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(id);") } printer.write("}") - printer.write("bjs[\"swift_js_push_tag\"] = function(tag) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpRetTag) = tag;") - } - printer.write("}") printer.write("bjs[\"swift_js_push_i32\"] = function(v) {") printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpRetInts).push(v | 0);") + printer.write("\(JSGlueVariableScope.reservedI32Stack).push(v | 0);") } printer.write("}") printer.write("bjs[\"swift_js_push_f32\"] = function(v) {") printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpRetF32s).push(Math.fround(v));") + printer.write("\(JSGlueVariableScope.reservedF32Stack).push(Math.fround(v));") } printer.write("}") printer.write("bjs[\"swift_js_push_f64\"] = function(v) {") printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpRetF64s).push(v);") + printer.write("\(JSGlueVariableScope.reservedF64Stack).push(v);") } printer.write("}") printer.write("bjs[\"swift_js_push_string\"] = function(ptr, len) {") @@ -411,73 +374,48 @@ public struct BridgeJSLink { "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len)\(sharedMemory ? ".slice()" : "");" ) printer.write("const value = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes);") - printer.write("\(JSGlueVariableScope.reservedTmpRetStrings).push(value);") + printer.write("\(JSGlueVariableScope.reservedStringStack).push(value);") } printer.write("}") printer.write("bjs[\"swift_js_pop_i32\"] = function() {") printer.indent { - printer.write("return \(JSGlueVariableScope.reservedTmpParamInts).pop();") + printer.write("return \(JSGlueVariableScope.reservedI32Stack).pop();") } printer.write("}") printer.write("bjs[\"swift_js_pop_f32\"] = function() {") printer.indent { - printer.write("return \(JSGlueVariableScope.reservedTmpParamF32s).pop();") + printer.write("return \(JSGlueVariableScope.reservedF32Stack).pop();") } printer.write("}") printer.write("bjs[\"swift_js_pop_f64\"] = function() {") printer.indent { - printer.write("return \(JSGlueVariableScope.reservedTmpParamF64s).pop();") + printer.write("return \(JSGlueVariableScope.reservedF64Stack).pop();") } printer.write("}") printer.write("bjs[\"swift_js_push_pointer\"] = function(pointer) {") printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpRetPointers).push(pointer);") + printer.write("\(JSGlueVariableScope.reservedPointerStack).push(pointer);") } printer.write("}") printer.write("bjs[\"swift_js_pop_pointer\"] = function() {") printer.indent { - printer.write("return \(JSGlueVariableScope.reservedTmpParamPointers).pop();") - } - printer.write("}") - printer.write("bjs[\"swift_js_struct_cleanup\"] = function(cleanupId) {") - printer.indent { - printer.write("if (cleanupId === 0) { return; }") - printer.write("const index = (cleanupId | 0) - 1;") - printer.write("const cleanup = \(JSGlueVariableScope.reservedTmpStructCleanups)[index];") - printer.write("\(JSGlueVariableScope.reservedTmpStructCleanups)[index] = null;") - printer.write("if (cleanup) { cleanup(); }") - printer.write( - "while (\(JSGlueVariableScope.reservedTmpStructCleanups).length > 0 && \(JSGlueVariableScope.reservedTmpStructCleanups)[\(JSGlueVariableScope.reservedTmpStructCleanups).length - 1] == null) {" - ) - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpStructCleanups).pop();") - } - printer.write("}") + printer.write("return \(JSGlueVariableScope.reservedPointerStack).pop();") } printer.write("}") - if !allStructs.isEmpty { for structDef in allStructs { printer.write("bjs[\"swift_js_struct_lower_\(structDef.name)\"] = function(objectId) {") printer.indent { printer.write( - "const { cleanup: cleanup } = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" + "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" ) - printer.write("if (cleanup) {") - printer.indent { - printer.write( - "return \(JSGlueVariableScope.reservedTmpStructCleanups).push(cleanup);" - ) - } - printer.write("}") - printer.write("return 0;") } printer.write("}") printer.write("bjs[\"swift_js_struct_lift_\(structDef.name)\"] = function() {") printer.indent { printer.write( - "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" + "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lift();" ) printer.write("return \(JSGlueVariableScope.reservedSwift).memory.retain(value);") } @@ -645,35 +583,108 @@ public struct BridgeJSLink { printer.write("return pointer || 0;") } printer.write("}") + // Always provide swift_js_closure_unregister as a no-op by default. + // The @_extern(wasm) declaration in BridgeJSIntrinsics.swift is unconditional, + // so the WASM binary always imports this symbol. When closures ARE used, + // the real implementation below will override this no-op. + printer.write("bjs[\"swift_js_closure_unregister\"] = function(funcRef) {}") for unified in skeletons { let moduleName = unified.moduleName - var closureSignatures: Set = [] - if let exported = unified.exported { - collectClosureSignatures(from: exported, into: &closureSignatures) - } - if let imported = unified.imported { - collectClosureSignatures(from: imported, into: &closureSignatures) - } + let collector = ClosureSignatureCollectorVisitor() + var walker = BridgeTypeWalker(visitor: collector) + walker.walk(unified) + let closureSignatures = walker.visitor.signatures guard !closureSignatures.isEmpty else { continue } + intrinsicRegistry.register(name: "swiftClosureHelpers") { helperPrinter in + helperPrinter.write( + "const \(JSGlueVariableScope.reservedSwiftClosureRegistry) = (typeof FinalizationRegistry === \"undefined\") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => {" + ) + helperPrinter.indent { + helperPrinter.write("if (state.unregistered) { return; }") + helperPrinter.write( + "\(JSGlueVariableScope.reservedInstance)?.exports?.bjs_release_swift_closure(state.pointer);" + ) + } + helperPrinter.write("});") + helperPrinter.write( + "const \(JSGlueVariableScope.reservedMakeSwiftClosure) = (pointer, file, line, func) => {" + ) + helperPrinter.indent { + helperPrinter.write( + "const state = { pointer, file, line, unregistered: false };" + ) + helperPrinter.write("const real = (...args) => {") + helperPrinter.indent { + helperPrinter.write("if (state.unregistered) {") + helperPrinter.indent { + helperPrinter.write( + "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, state.file);" + ) + helperPrinter.write("let length = 0;") + helperPrinter.write("while (bytes[length] !== 0) { length += 1; }") + helperPrinter.write( + "const fileID = \(JSGlueVariableScope.reservedTextDecoder).decode(bytes.subarray(0, length));" + ) + helperPrinter.write( + "throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`);" + ) + } + helperPrinter.write("}") + helperPrinter.write("return func(...args);") + } + helperPrinter.write("};") + helperPrinter.write( + "real.__unregister = () => {" + ) + helperPrinter.indent { + helperPrinter.write( + "if (state.unregistered) { return; }" + ) + helperPrinter.write("state.unregistered = true;") + helperPrinter.write( + "\(JSGlueVariableScope.reservedSwiftClosureRegistry).unregister(state);" + ) + } + helperPrinter.write("};") + helperPrinter.write( + "\(JSGlueVariableScope.reservedSwiftClosureRegistry).register(real, state, state);" + ) + helperPrinter.write("return \(JSGlueVariableScope.reservedSwift).memory.retain(real);") + } + helperPrinter.write("};") + } + printer.write("bjs[\"swift_js_closure_unregister\"] = function(funcRef) {") + printer.indent { + printer.write("const func = \(JSGlueVariableScope.reservedSwift).memory.getObject(funcRef);") + printer.write("func.__unregister();") + } + printer.write("}") + for signature in closureSignatures.sorted(by: { $0.mangleName < $1.mangleName }) { let invokeFuncName = "invoke_js_callback_\(moduleName)_\(signature.mangleName)" - printer.write( - lines: generateInvokeFunction( - signature: signature, - functionName: invokeFuncName - ) + let invokeLines = try generateInvokeFunction( + signature: signature, + functionName: invokeFuncName ) + printer.write(lines: invokeLines) let lowerFuncName = "lower_closure_\(moduleName)_\(signature.mangleName)" - printer.write( - lines: generateLowerClosureFunction( + let makeFuncName = "make_swift_closure_\(moduleName)_\(signature.mangleName)" + printer.write("bjs[\"\(makeFuncName)\"] = function(boxPtr, file, line) {") + try printer.indent { + let lowerLines = try generateLowerClosureFunction( signature: signature, functionName: lowerFuncName ) - ) + printer.write(lines: lowerLines) + printer.write( + "return \(JSGlueVariableScope.reservedMakeSwiftClosure)(boxPtr, file, line, \(lowerFuncName));" + ) + } + printer.write("}") } } } @@ -682,192 +693,58 @@ public struct BridgeJSLink { return printer } - private func collectClosureSignatures(from skeleton: ExportedSkeleton, into signatures: inout Set) - { - for function in skeleton.functions { - collectClosureSignatures(from: function.parameters, into: &signatures) - collectClosureSignatures(from: function.returnType, into: &signatures) - } - for klass in skeleton.classes { - if let constructor = klass.constructor { - collectClosureSignatures(from: constructor.parameters, into: &signatures) - } - for method in klass.methods { - collectClosureSignatures(from: method.parameters, into: &signatures) - collectClosureSignatures(from: method.returnType, into: &signatures) - } - for property in klass.properties { - collectClosureSignatures(from: property.type, into: &signatures) - } - } - } - - private func collectClosureSignatures( - from skeleton: ImportedModuleSkeleton, - into signatures: inout Set - ) { - for fileSkeleton in skeleton.children { - for getter in fileSkeleton.globalGetters { - collectClosureSignatures(from: getter.type, into: &signatures) - } - for function in fileSkeleton.functions { - collectClosureSignatures(from: function.parameters, into: &signatures) - collectClosureSignatures(from: function.returnType, into: &signatures) - } - for type in fileSkeleton.types { - if let constructor = type.constructor { - collectClosureSignatures(from: constructor.parameters, into: &signatures) - } - for getter in type.getters { - collectClosureSignatures(from: getter.type, into: &signatures) - } - for setter in type.setters { - collectClosureSignatures(from: setter.type, into: &signatures) - } - for method in type.methods { - collectClosureSignatures(from: method.parameters, into: &signatures) - collectClosureSignatures(from: method.returnType, into: &signatures) - } - } - } - } - - private func collectClosureSignatures(from parameters: [Parameter], into signatures: inout Set) { - for param in parameters { - collectClosureSignatures(from: param.type, into: &signatures) - } - } - - private func collectClosureSignatures(from type: BridgeType, into signatures: inout Set) { - switch type { - case .closure(let signature): - signatures.insert(signature) - for paramType in signature.parameters { - collectClosureSignatures(from: paramType, into: &signatures) - } - collectClosureSignatures(from: signature.returnType, into: &signatures) - case .optional(let wrapped): - collectClosureSignatures(from: wrapped, into: &signatures) - default: - break - } - } - private func generateInvokeFunction( signature: ClosureSignature, functionName: String - ) -> [String] { - let printer = CodeFragmentPrinter() - let scope = JSGlueVariableScope() - let cleanupCode = CodeFragmentPrinter() + ) throws -> [String] { + let thunkBuilder = ImportedThunkBuilder(context: .exportSwift, intrinsicRegistry: intrinsicRegistry) + thunkBuilder.parameterNames.append("callbackId") + thunkBuilder.body.write("const callback = \(JSGlueVariableScope.reservedSwift).memory.getObject(callbackId);") - // Build parameter list for invoke function - var invokeParams: [String] = ["callbackId"] for (index, paramType) in signature.parameters.enumerated() { - if case .optional = paramType { - invokeParams.append("param\(index)IsSome") - invokeParams.append("param\(index)Value") - } else { - invokeParams.append("param\(index)Id") - } + let paramName = "param\(index)" + try thunkBuilder.liftParameter(param: Parameter(label: nil, name: paramName, type: paramType)) } - printer.nextLine() - printer.write("bjs[\"\(functionName)\"] = function(\(invokeParams.joined(separator: ", "))) {") - printer.indent { - printer.write("try {") - printer.indent { - printer.write("const callback = \(JSGlueVariableScope.reservedSwift).memory.getObject(callbackId);") - - for (index, paramType) in signature.parameters.enumerated() { - let fragment = try! IntrinsicJSFragment.closureLiftParameter(type: paramType) - let args: [String] - if case .optional = paramType { - args = ["param\(index)IsSome", "param\(index)Value", "param\(index)"] - } else { - args = ["param\(index)Id", "param\(index)"] - } - _ = fragment.printCode(args, scope, printer, cleanupCode) - } - - let callbackParams = signature.parameters.indices.map { "param\($0)" }.joined(separator: ", ") - printer.write("const result = callback(\(callbackParams));") - - // Type check if needed (for example, formatName requires string return) - switch signature.returnType { - case .string: - printer.write("if (typeof result !== \"string\") {") - printer.indent { - printer.write("throw new TypeError(\"Callback must return a string\");") - } - printer.write("}") - default: - break - } + let returnExpr = try thunkBuilder.call(calleeExpr: "callback", returnType: signature.returnType) - let returnFragment = try! IntrinsicJSFragment.closureLowerReturn(type: signature.returnType) - _ = returnFragment.printCode(["result"], scope, printer, cleanupCode) - } - printer.write("} catch (error) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedSetException)?.(error);") - let errorFragment = IntrinsicJSFragment.closureErrorReturn(type: signature.returnType) - _ = errorFragment.printCode([], scope, printer, cleanupCode) - } - printer.write("}") - } - printer.write("};") + var functionLines = thunkBuilder.renderFunction( + name: nil, + returnExpr: returnExpr, + returnType: signature.returnType + ) + functionLines[0] = "bjs[\"\(functionName)\"] = " + functionLines[0] - return printer.lines + return functionLines } /// Generates a lower_closure_* function that wraps a Swift closure for JavaScript private func generateLowerClosureFunction( signature: ClosureSignature, functionName: String - ) -> [String] { + ) throws -> [String] { let printer = CodeFragmentPrinter() - let scope = JSGlueVariableScope() - let cleanupCode = CodeFragmentPrinter() - - printer.nextLine() - printer.write("bjs[\"\(functionName)\"] = function(closurePtr) {") - printer.indent { - printer.write( - "return function(\(signature.parameters.indices.map { "param\($0)" }.joined(separator: ", "))) {" - ) - printer.indent { - printer.write("try {") - printer.indent { - var invokeArgs: [String] = ["closurePtr"] - - for (index, paramType) in signature.parameters.enumerated() { - let paramName = "param\(index)" - let fragment = try! IntrinsicJSFragment.lowerParameter(type: paramType) - let lowered = fragment.printCode([paramName], scope, printer, cleanupCode) - invokeArgs.append(contentsOf: lowered) - } - - // Call the Swift invoke function - let invokeCall = - "\(JSGlueVariableScope.reservedInstance).exports.invoke_swift_closure_\(signature.moduleName)_\(signature.mangleName)(\(invokeArgs.joined(separator: ", ")))" + let builder = ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + hasDirectAccessToSwiftClass: false, + intrinsicRegistry: intrinsicRegistry + ) + builder.parameterForwardings.append("boxPtr") - let returnFragment = try! IntrinsicJSFragment.closureLiftReturn(type: signature.returnType) - _ = returnFragment.printCode([invokeCall], scope, printer, cleanupCode) - } - printer.write("} catch (error) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedSetException)?.(error);") - switch signature.returnType { - case .void: - printer.write("return;") - default: - printer.write("throw error;") - } - } - printer.write("}") + printer.write( + "const \(functionName) = function(\(signature.parameters.indices.map { "param\($0)" }.joined(separator: ", "))) {" + ) + try printer.indent { + // Lower parameters using shared thunk builder + for (index, paramType) in signature.parameters.enumerated() { + let paramName = "param\(index)" + try builder.lowerParameter(param: Parameter(label: nil, name: paramName, type: paramType)) } - printer.write("};") + + let invokeCall = + "invoke_swift_closure_\(signature.moduleName)_\(signature.mangleName)" + let returnExpr = try builder.call(abiName: invokeCall, returnType: signature.returnType) + builder.renderFunctionBody(into: printer, returnExpr: returnExpr) } printer.write("};") @@ -1036,23 +913,59 @@ public struct BridgeJSLink { ) printer.write(lines: topLevelNamespaceCode) + let propertyAssignments = try generateNamespacePropertyAssignments( + data: data, + exportedSkeletons: exportedSkeletons, + namespaceBuilder: namespaceBuilder + ) + // Main function declaration printer.write("export async function createInstantiator(options, \(JSGlueVariableScope.reservedSwift)) {") - printer.indent { + try printer.indent { printer.write(lines: generateVariableDeclarations()) + let bodyPrinter = CodeFragmentPrinter() let allStructs = exportedSkeletons.flatMap { $0.structs } for structDef in allStructs { let structPrinter = CodeFragmentPrinter() - let structScope = JSGlueVariableScope() - let structCleanup = CodeFragmentPrinter() + let structScope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) let fragment = IntrinsicJSFragment.structHelper(structDefinition: structDef, allStructs: allStructs) - _ = fragment.printCode([structDef.name], structScope, structPrinter, structCleanup) - printer.write(lines: structPrinter.lines) + _ = try fragment.printCode( + [structDef.name], + IntrinsicJSFragment.PrintCodeContext( + scope: structScope, + printer: structPrinter + ) + ) + bodyPrinter.write(lines: structPrinter.lines) } - printer.nextLine() - printer.write(contentsOf: generateAddImports(needsImportsObject: data.needsImportsObject)) + + let allAssocEnums = exportedSkeletons.flatMap { + $0.enums.filter { $0.enumType == .associatedValue } + } + for enumDef in allAssocEnums { + let enumPrinter = CodeFragmentPrinter() + let enumScope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) + let fragment = IntrinsicJSFragment.associatedValueEnumHelperFactory(enumDefinition: enumDef) + _ = try fragment.printCode( + [enumDef.valuesName], + IntrinsicJSFragment.PrintCodeContext( + scope: enumScope, + printer: enumPrinter + ) + ) + bodyPrinter.write(lines: enumPrinter.lines) + } + bodyPrinter.nextLine() + bodyPrinter.write(contentsOf: try generateAddImports(needsImportsObject: data.needsImportsObject)) + + if !intrinsicRegistry.isEmpty { + printer.write(lines: intrinsicRegistry.emitLines()) + printer.nextLine() + } + + printer.write(lines: bodyPrinter.lines) } printer.indent() @@ -1079,8 +992,6 @@ public struct BridgeJSLink { "\(JSGlueVariableScope.reservedMemory) = \(JSGlueVariableScope.reservedInstance).exports.memory;", ]) printer.nextLine() - // Enum helpers section - printer.write(contentsOf: enumHelperAssignments()) // Error handling printer.write("\(JSGlueVariableScope.reservedSetException) = (error) => {") printer.indent { @@ -1094,28 +1005,24 @@ public struct BridgeJSLink { } // createExports method - try printer.indent { + printer.indent { printer.write(lines: [ "/** @param {WebAssembly.Instance} instance */", "createExports: (instance) => {", ]) - try printer.indent { + printer.indent { printer.write("const js = \(JSGlueVariableScope.reservedSwift).memory.heap;") printer.write(lines: data.classLines) - // Struct helpers must be initialized AFTER classes are defined (to allow _exports access) + // Struct and enum helpers must be initialized AFTER classes are defined (to allow _exports access) printer.write(contentsOf: structHelperAssignments()) + printer.write(contentsOf: enumHelperAssignments()) let namespaceInitCode = namespaceBuilder.buildNamespaceInitialization( exportedSkeletons: exportedSkeletons ) printer.write(lines: namespaceInitCode) - let propertyAssignments = try generateNamespacePropertyAssignments( - data: data, - exportedSkeletons: exportedSkeletons, - namespaceBuilder: namespaceBuilder - ) printer.write(lines: propertyAssignments) } printer.write("},") @@ -1128,6 +1035,7 @@ public struct BridgeJSLink { } public func link() throws -> (outputJs: String, outputDts: String) { + intrinsicRegistry.reset() let data = try collectLinkData() let outputJs = try generateJavaScript(data: data) let outputDts = generateTypeScript(data: data) @@ -1140,7 +1048,7 @@ public struct BridgeJSLink { for skeleton in skeletons.compactMap(\.exported) { for enumDef in skeleton.enums where enumDef.enumType == .associatedValue { printer.write( - "const \(enumDef.name)Helpers = __bjs_create\(enumDef.valuesName)Helpers()(\(JSGlueVariableScope.reservedTmpParamInts), \(JSGlueVariableScope.reservedTmpParamF32s), \(JSGlueVariableScope.reservedTmpParamF64s), \(JSGlueVariableScope.reservedTextEncoder), \(JSGlueVariableScope.reservedSwift));" + "const \(enumDef.name)Helpers = __bjs_create\(enumDef.valuesName)Helpers();" ) printer.write("\(JSGlueVariableScope.reservedEnumHelpers).\(enumDef.name) = \(enumDef.name)Helpers;") printer.nextLine() @@ -1156,7 +1064,7 @@ public struct BridgeJSLink { for skeleton in skeletons.compactMap(\.exported) { for structDef in skeleton.structs { printer.write( - "const \(structDef.name)Helpers = __bjs_create\(structDef.name)Helpers()(\(JSGlueVariableScope.reservedTmpParamInts), \(JSGlueVariableScope.reservedTmpParamF32s), \(JSGlueVariableScope.reservedTmpParamF64s), \(JSGlueVariableScope.reservedTmpParamPointers), \(JSGlueVariableScope.reservedTmpRetPointers), \(JSGlueVariableScope.reservedTextEncoder), \(JSGlueVariableScope.reservedSwift), \(JSGlueVariableScope.reservedEnumHelpers));" + "const \(structDef.name)Helpers = __bjs_create\(structDef.name)Helpers();" ) printer.write( "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name) = \(structDef.name)Helpers;" @@ -1194,7 +1102,7 @@ public struct BridgeJSLink { for klass in classes.sorted(by: { $0.name < $1.name }) { let wrapperFunctionName = "bjs_\(klass.name)_wrap" wrapperLines.append("importObject[\"\(moduleName)\"][\"\(wrapperFunctionName)\"] = function(pointer) {") - wrapperLines.append(" const obj = \(klass.name).__construct(pointer);") + wrapperLines.append(" const obj = _exports['\(klass.name)'].__construct(pointer);") wrapperLines.append(" return \(JSGlueVariableScope.reservedSwift).memory.retain(obj);") wrapperLines.append("};") } @@ -1222,6 +1130,7 @@ public struct BridgeJSLink { let hierarchicalLines = try namespaceBuilder.buildHierarchicalExportsObject( exportedSkeletons: exportedSkeletons, + intrinsicRegistry: intrinsicRegistry, renderFunctionImpl: { function in let (js, _) = try self.renderExportedFunction(function: function) return js @@ -1288,16 +1197,20 @@ public struct BridgeJSLink { class ExportedThunkBuilder { var body: CodeFragmentPrinter - var cleanupCode: CodeFragmentPrinter var parameterForwardings: [String] = [] let effects: Effects let scope: JSGlueVariableScope + let context: IntrinsicJSFragment.PrintCodeContext - init(effects: Effects) { + init(effects: Effects, hasDirectAccessToSwiftClass: Bool = true, intrinsicRegistry: JSIntrinsicRegistry) { self.effects = effects - self.scope = JSGlueVariableScope() + self.scope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) self.body = CodeFragmentPrinter() - self.cleanupCode = CodeFragmentPrinter() + self.context = IntrinsicJSFragment.PrintCodeContext( + scope: scope, + printer: body, + hasDirectAccessToSwiftClass: hasDirectAccessToSwiftClass + ) } func lowerParameter(param: Parameter) throws { @@ -1306,7 +1219,8 @@ public struct BridgeJSLink { loweringFragment.parameters.count == 1, "Lowering fragment should have exactly one parameter to lower" ) - let loweredValues = loweringFragment.printCode([param.name], scope, body, cleanupCode) + let paramName = scope.variable(param.name) + let loweredValues = try loweringFragment.printCode([paramName], context) parameterForwardings.append(contentsOf: loweredValues) } @@ -1338,7 +1252,7 @@ public struct BridgeJSLink { body.write("const \(returnVariable) = \(call);") fragmentArguments = [returnVariable] } - let liftedValues = liftingFragment.printCode(fragmentArguments, scope, body, cleanupCode) + let liftedValues = try liftingFragment.printCode(fragmentArguments, context) assert(liftedValues.count <= 1, "Lifting fragment should produce at most one value") return liftedValues.first } @@ -1366,10 +1280,9 @@ public struct BridgeJSLink { ] } - /// Renders the thunk body (body code, cleanup, exception handling, and optional return) into a printer. + /// Renders the thunk body (body code, exception handling, and optional return) into a printer. func renderFunctionBody(into printer: CodeFragmentPrinter, returnExpr: String?) { printer.write(contentsOf: body) - printer.write(contentsOf: cleanupCode) printer.write(lines: checkExceptionLines()) if let returnExpr = returnExpr { printer.write("return \(returnExpr);") @@ -1420,6 +1333,9 @@ public struct BridgeJSLink { case .namespaceEnum: return enumDef.tsFullPath default: + if enumDef.emitStyle == .tsEnum { + return enumDef.tsFullPath + } return "\(enumDef.tsFullPath)Tag" } } @@ -1428,8 +1344,9 @@ public struct BridgeJSLink { return type.tsType case .swiftStruct(let name): return name.components(separatedBy: ".").last ?? name - case .optional(let wrapped): - return "\(resolveTypeScriptType(wrapped, exportedSkeletons: exportedSkeletons)) | null" + case .nullable(let wrapped, let kind): + let base = resolveTypeScriptType(wrapped, exportedSkeletons: exportedSkeletons) + return "\(base) | \(kind.absenceLiteral)" case .array(let elementType): let elementTypeStr = resolveTypeScriptType(elementType, exportedSkeletons: exportedSkeletons) // Parenthesize compound types so `[]` binds correctly in TypeScript @@ -1438,6 +1355,9 @@ public struct BridgeJSLink { return "(\(elementTypeStr))[]" } return "\(elementTypeStr)[]" + case .dictionary(let valueType): + let valueTypeStr = resolveTypeScriptType(valueType, exportedSkeletons: exportedSkeletons) + return "Record" default: return type.tsType } @@ -1515,7 +1435,10 @@ public struct BridgeJSLink { try jsPrinter.indent { // Constructor as 'init' function if let constructor = structDefinition.constructor { - let thunkBuilder = ExportedThunkBuilder(effects: constructor.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: constructor.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in constructor.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1581,27 +1504,30 @@ public struct BridgeJSLink { ) throws -> (jsTopLevel: [String], jsExportEntry: [String], dtsType: [String], dtsExportEntry: [String]) { var jsTopLevelLines: [String] = [] var dtsTypeLines: [String] = [] - let scope = JSGlueVariableScope() - let cleanup = CodeFragmentPrinter() + let scope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) let printer = CodeFragmentPrinter() + let context = IntrinsicJSFragment.PrintCodeContext( + scope: scope, + printer: printer + ) let enumValuesName = enumDefinition.valuesName switch enumDefinition.enumType { case .simple: - let fragment = IntrinsicJSFragment.simpleEnumHelper(enumDefinition: enumDefinition) - _ = fragment.printCode([enumValuesName], scope, printer, cleanup) + let fragment = IntrinsicJSFragment.caseEnumHelper(enumDefinition: enumDefinition) + _ = try fragment.printCode([enumValuesName], context) jsTopLevelLines.append(contentsOf: printer.lines) case .rawValue: guard enumDefinition.rawType != nil else { throw BridgeJSLinkError(message: "Raw value enum \(enumDefinition.name) is missing rawType") } - let fragment = IntrinsicJSFragment.rawValueEnumHelper(enumDefinition: enumDefinition) - _ = fragment.printCode([enumValuesName], scope, printer, cleanup) + let fragment = IntrinsicJSFragment.caseEnumHelper(enumDefinition: enumDefinition) + _ = try fragment.printCode([enumValuesName], context) jsTopLevelLines.append(contentsOf: printer.lines) case .associatedValue: - let fragment = IntrinsicJSFragment.associatedValueEnumHelper(enumDefinition: enumDefinition) - _ = fragment.printCode([enumValuesName], scope, printer, cleanup) + let fragment = IntrinsicJSFragment.associatedValueEnumValues(enumDefinition: enumDefinition) + _ = try fragment.printCode([enumValuesName], context) jsTopLevelLines.append(contentsOf: printer.lines) case .namespace: break @@ -1729,7 +1655,7 @@ public struct BridgeJSLink { ] for (associatedValueIndex, associatedValue) in enumCase.associatedValues.enumerated() { let prop = associatedValue.label ?? "param\(associatedValueIndex)" - fields.append("\(prop): \(associatedValue.type.tsType)") + fields.append("\(prop): \(resolveTypeScriptType(associatedValue.type))") } unionParts.append("{ \(fields.joined(separator: "; ")) }") } @@ -1751,12 +1677,17 @@ public struct BridgeJSLink { extension BridgeJSLink { - func renderExportedFunction(function: ExportedFunction) throws -> (js: [String], dts: [String]) { + func renderExportedFunction( + function: ExportedFunction + ) throws -> (js: [String], dts: [String]) { if function.effects.isStatic, let staticContext = function.staticContext { return try renderStaticFunction(function: function, staticContext: staticContext) } - let thunkBuilder = ExportedThunkBuilder(effects: function.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: function.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in function.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1789,7 +1720,10 @@ extension BridgeJSLink { return try renderEnumStaticFunction(function: function, enumName: enumName) case .namespaceEnum: if let namespace = function.namespace, !namespace.isEmpty { - return try renderNamespaceFunction(function: function, namespace: namespace.joined(separator: ".")) + return try renderNamespaceFunction( + function: function, + namespace: namespace.joined(separator: ".") + ) } else { return try renderExportedFunction(function: function) } @@ -1800,7 +1734,10 @@ extension BridgeJSLink { function: ExportedFunction, className: String ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ExportedThunkBuilder(effects: function.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: function.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in function.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1828,7 +1765,10 @@ extension BridgeJSLink { function: ExportedFunction, enumName: String ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ExportedThunkBuilder(effects: function.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: function.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in function.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1856,7 +1796,10 @@ extension BridgeJSLink { function: ExportedFunction, namespace: String ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ExportedThunkBuilder(effects: function.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: function.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in function.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1878,7 +1821,10 @@ extension BridgeJSLink { private func renderStaticMethodForExportObject( method: ExportedFunction ) throws -> [String] { - let thunkBuilder = ExportedThunkBuilder(effects: method.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: method.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in method.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1903,7 +1849,10 @@ extension BridgeJSLink { let propertyPrinter = CodeFragmentPrinter() // Generate getter - let getterThunkBuilder = ExportedThunkBuilder(effects: Effects(isAsync: false, isThrows: false)) + let getterThunkBuilder = ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry + ) let getterReturnExpr = try getterThunkBuilder.call( abiName: className != nil ? property.getterAbiName(className: className!) @@ -1920,7 +1869,8 @@ extension BridgeJSLink { // Generate setter if not readonly if !property.isReadonly { let setterThunkBuilder = ExportedThunkBuilder( - effects: Effects(isAsync: false, isThrows: false) + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry ) try setterThunkBuilder.lowerParameter( param: Parameter(label: "value", name: "value", type: property.type) @@ -1966,7 +1916,10 @@ extension BridgeJSLink { } if let constructor: ExportedConstructor = klass.constructor { - let thunkBuilder = ExportedThunkBuilder(effects: constructor.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: constructor.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in constructor.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -1998,7 +1951,10 @@ extension BridgeJSLink { for method in klass.methods { if method.effects.isStatic { - let thunkBuilder = ExportedThunkBuilder(effects: method.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: method.effects, + intrinsicRegistry: intrinsicRegistry + ) for param in method.parameters { try thunkBuilder.lowerParameter(param: param) } @@ -2021,7 +1977,10 @@ extension BridgeJSLink { ) } } else { - let thunkBuilder = ExportedThunkBuilder(effects: method.effects) + let thunkBuilder = ExportedThunkBuilder( + effects: method.effects, + intrinsicRegistry: intrinsicRegistry + ) thunkBuilder.lowerSelf() for param in method.parameters { try thunkBuilder.lowerParameter(param: param) @@ -2072,7 +2031,10 @@ extension BridgeJSLink { jsPrinter: CodeFragmentPrinter, dtsPrinter: CodeFragmentPrinter ) throws { - let getterThunkBuilder = ExportedThunkBuilder(effects: Effects(isAsync: false, isThrows: false)) + let getterThunkBuilder = ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry + ) if !isStatic { getterThunkBuilder.lowerSelf() } @@ -2094,7 +2056,10 @@ extension BridgeJSLink { // Generate setter if not readonly if !property.isReadonly { - let setterThunkBuilder = ExportedThunkBuilder(effects: Effects(isAsync: false, isThrows: false)) + let setterThunkBuilder = ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry + ) if !isStatic { setterThunkBuilder.lowerSelf() } @@ -2128,16 +2093,19 @@ extension BridgeJSLink { class ImportedThunkBuilder { let body: CodeFragmentPrinter let scope: JSGlueVariableScope - let cleanupCode: CodeFragmentPrinter let context: BridgeContext var parameterNames: [String] = [] var parameterForwardings: [String] = [] + let printContext: IntrinsicJSFragment.PrintCodeContext - init(context: BridgeContext = .importTS) { + init(context: BridgeContext = .importTS, intrinsicRegistry: JSIntrinsicRegistry) { self.body = CodeFragmentPrinter() - self.scope = JSGlueVariableScope() - self.cleanupCode = CodeFragmentPrinter() + self.scope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) self.context = context + self.printContext = IntrinsicJSFragment.PrintCodeContext( + scope: scope, + printer: body + ) } func liftSelf() { @@ -2146,31 +2114,29 @@ extension BridgeJSLink { func liftParameter(param: Parameter) throws { let liftingFragment = try IntrinsicJSFragment.liftParameter(type: param.type, context: context) - assert( - liftingFragment.parameters.count >= 1, - "Lifting fragment should have at least one parameter to lift" - ) let valuesToLift: [String] - if liftingFragment.parameters.count == 1 { + if liftingFragment.parameters.count == 0 { + valuesToLift = [] + } else if liftingFragment.parameters.count == 1 { parameterNames.append(param.name) valuesToLift = [scope.variable(param.name)] } else { valuesToLift = liftingFragment.parameters.map { scope.variable(param.name + $0.capitalizedFirstLetter) } parameterNames.append(contentsOf: valuesToLift) } - let liftedValues = liftingFragment.printCode(valuesToLift, scope, body, cleanupCode) + let liftedValues = try liftingFragment.printCode(valuesToLift, printContext) assert(liftedValues.count == 1, "Lifting fragment should produce exactly one value") parameterForwardings.append(contentsOf: liftedValues) } func renderFunction( - name: String, + name: String?, returnExpr: String?, returnType: BridgeType ) -> [String] { let printer = CodeFragmentPrinter() - printer.write("function \(name)(\(parameterNames.joined(separator: ", "))) {") + printer.write("function\(name.map { " \($0)" } ?? "")(\(parameterNames.joined(separator: ", "))) {") printer.indent { printer.write("try {") printer.indent { @@ -2202,7 +2168,7 @@ extension BridgeJSLink { return try call(name: name, fromObjectExpr: "imports", returnType: returnType) } - private func call(calleeExpr: String, returnType: BridgeType) throws -> String? { + func call(calleeExpr: String, returnType: BridgeType) throws -> String? { let callExpr = "\(calleeExpr)(\(parameterForwardings.joined(separator: ", ")))" return try self.call(callExpr: callExpr, returnType: returnType) } @@ -2246,11 +2212,19 @@ extension BridgeJSLink { ) } + func callStaticMethod(on objectExpr: String, name: String, returnType: BridgeType) throws -> String? { + let calleeExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) + return try call( + calleeExpr: calleeExpr, + returnType: returnType + ) + } + func callPropertyGetter(name: String, returnType: BridgeType) throws -> String? { let objectExpr = "\(JSGlueVariableScope.reservedSwift).memory.getObject(self)" let accessExpr = Self.propertyAccessExpr(objectExpr: objectExpr, propertyName: name) if context == .exportSwift, returnType.usesSideChannelForOptionalReturn() { - guard case .optional(let wrappedType) = returnType else { + guard case .nullable(let wrappedType, _) = returnType else { fatalError("usesSideChannelForOptionalReturn returned true for non-optional type") } @@ -2260,7 +2234,7 @@ extension BridgeJSLink { ) let fragment = try IntrinsicJSFragment.protocolPropertyOptionalToSideChannel(wrappedType: wrappedType) - _ = fragment.printCode([resultVar], scope, body, cleanupCode) + _ = try fragment.printCode([resultVar], printContext) return nil // Side-channel types return nil (no direct return value) } @@ -2313,12 +2287,15 @@ extension BridgeJSLink { loweringFragment: IntrinsicJSFragment ) throws -> String? { assert(loweringFragment.parameters.count <= 1, "Lowering fragment should have at most one parameter") - let loweredValues = loweringFragment.printCode(returnExpr.map { [$0] } ?? [], scope, body, cleanupCode) + let loweredValues = try loweringFragment.printCode( + returnExpr.map { [$0] } ?? [], + printContext + ) assert(loweredValues.count <= 1, "Lowering fragment should produce at most one value") return loweredValues.first } - private static func propertyAccessExpr(objectExpr: String, propertyName: String) -> String { + static func propertyAccessExpr(objectExpr: String, propertyName: String) -> String { if propertyName.range(of: #"^[$A-Z_][0-9A-Z_$]*$"#, options: [.regularExpression, .caseInsensitive]) != nil { return "\(objectExpr).\(propertyName)" @@ -2613,6 +2590,7 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsObject( exportedSkeletons: [ExportedSkeleton], + intrinsicRegistry: JSIntrinsicRegistry, renderFunctionImpl: (ExportedFunction) throws -> [String] ) throws -> [String] { let printer = CodeFragmentPrinter() @@ -2622,7 +2600,10 @@ extension BridgeJSLink { try populateJavaScriptExportLines(node: rootNode, renderFunctionImpl: renderFunctionImpl) - try populatePropertyImplementations(node: rootNode) + try populatePropertyImplementations( + node: rootNode, + intrinsicRegistry: intrinsicRegistry + ) printExportsObjectHierarchy(node: rootNode, printer: printer, currentPath: []) @@ -2643,10 +2624,16 @@ extension BridgeJSLink { } } - private func populatePropertyImplementations(node: NamespaceNode) throws { + private func populatePropertyImplementations( + node: NamespaceNode, + intrinsicRegistry: JSIntrinsicRegistry + ) throws { for property in node.content.staticProperties { // Generate getter - let getterThunkBuilder = ExportedThunkBuilder(effects: Effects(isAsync: false, isThrows: false)) + let getterThunkBuilder = ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry + ) let getterReturnExpr = try getterThunkBuilder.call( abiName: property.getterAbiName(), returnType: property.type @@ -2656,7 +2643,6 @@ extension BridgeJSLink { getterPrinter.write("get \(property.name)() {") getterPrinter.indent { getterPrinter.write(contentsOf: getterThunkBuilder.body) - getterPrinter.write(contentsOf: getterThunkBuilder.cleanupCode) getterPrinter.write(lines: getterThunkBuilder.checkExceptionLines()) if let returnExpr = getterReturnExpr { getterPrinter.write("return \(returnExpr);") @@ -2669,21 +2655,21 @@ extension BridgeJSLink { // Generate setter if not readonly if !property.isReadonly { let setterThunkBuilder = ExportedThunkBuilder( - effects: Effects(isAsync: false, isThrows: false) + effects: Effects(isAsync: false, isThrows: false), + intrinsicRegistry: intrinsicRegistry ) try setterThunkBuilder.lowerParameter( param: Parameter(label: "value", name: "value", type: property.type) ) _ = try setterThunkBuilder.call( abiName: property.setterAbiName(), - returnType: .void + returnType: BridgeType.void ) let setterPrinter = CodeFragmentPrinter() setterPrinter.write("set \(property.name)(value) {") setterPrinter.indent { setterPrinter.write(contentsOf: setterThunkBuilder.body) - setterPrinter.write(contentsOf: setterThunkBuilder.cleanupCode) setterPrinter.write(lines: setterThunkBuilder.checkExceptionLines()) } setterPrinter.write("},") @@ -2696,7 +2682,10 @@ extension BridgeJSLink { // Recursively process child nodes for (_, childNode) in node.children { - try populatePropertyImplementations(node: childNode) + try populatePropertyImplementations( + node: childNode, + intrinsicRegistry: intrinsicRegistry + ) } } @@ -2801,6 +2790,7 @@ extension BridgeJSLink { depth: 1, printer: printer, exposeToGlobal: true, + exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback ) printer.unindent() @@ -2819,6 +2809,7 @@ extension BridgeJSLink { depth: 1, printer: printer, exposeToGlobal: false, + exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback ) } @@ -2832,6 +2823,7 @@ extension BridgeJSLink { depth: Int, printer: CodeFragmentPrinter, exposeToGlobal: Bool, + exportedSkeletons: [ExportedSkeleton], renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String ) { func hasContent(node: NamespaceNode) -> Bool { @@ -2986,7 +2978,9 @@ extension BridgeJSLink { .enumerated() { let prop = associatedValue.label ?? "param\(associatedValueIndex)" - fields.append("\(prop): \(associatedValue.type.tsType)") + fields.append( + "\(prop): \(BridgeJSLink.resolveTypeScriptType(associatedValue.type, exportedSkeletons: exportedSkeletons))" + ) } unionParts.append("{ \(fields.joined(separator: "; ")) }") } @@ -3005,7 +2999,7 @@ extension BridgeJSLink { let sortedFunctions = childNode.content.functions.sorted { $0.name < $1.name } for function in sortedFunctions { let signature = - "\(function.name)\(renderTSSignatureCallback(function.parameters, function.returnType, function.effects));" + "function \(function.name)\(renderTSSignatureCallback(function.parameters, function.returnType, function.effects));" printer.write(signature) } let sortedProperties = childNode.content.staticProperties.sorted { $0.name < $1.name } @@ -3020,6 +3014,7 @@ extension BridgeJSLink { depth: depth + 1, printer: printer, exposeToGlobal: exposeToGlobal, + exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback ) @@ -3036,7 +3031,7 @@ extension BridgeJSLink { importObjectBuilder: ImportObjectBuilder, function: ImportedFunctionSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) for param in function.parameters { try thunkBuilder.liftParameter(param: param) } @@ -3067,7 +3062,7 @@ extension BridgeJSLink { importObjectBuilder: ImportObjectBuilder, getter: ImportedGetterSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) let jsName = getter.jsName ?? getter.name let importRootExpr = getter.from == .global ? "globalThis" : "imports" let returnExpr = try thunkBuilder.getImportProperty( @@ -3130,6 +3125,32 @@ extension BridgeJSLink { importObjectBuilder.assignToImportObject(name: setterAbiName, function: js) importObjectBuilder.appendDts(dts) } + for method in type.staticMethods { + let abiName = method.abiName(context: type, operation: "static") + let (js, dts) = try renderImportedStaticMethod(context: type, method: method) + importObjectBuilder.assignToImportObject(name: abiName, function: js) + importObjectBuilder.appendDts(dts) + } + if type.from == nil, type.constructor != nil || !type.staticMethods.isEmpty { + let dtsPrinter = CodeFragmentPrinter() + dtsPrinter.write("\(type.name): {") + dtsPrinter.indent { + if let constructor = type.constructor { + let returnType = BridgeType.jsObject(type.name) + dtsPrinter.write( + "new\(renderTSSignature(parameters: constructor.parameters, returnType: returnType, effects: Effects(isAsync: false, isThrows: false)));" + ) + } + for method in type.staticMethods { + let methodName = method.jsName ?? method.name + let signature = + "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: Effects(isAsync: false, isThrows: false)));" + dtsPrinter.write(signature) + } + } + dtsPrinter.write("}") + importObjectBuilder.appendDts(dtsPrinter.lines) + } for method in type.methods { let (js, dts) = try renderImportedMethod(context: type, method: method) importObjectBuilder.assignToImportObject(name: method.abiName(context: type), function: js) @@ -3142,7 +3163,7 @@ extension BridgeJSLink { type: ImportedTypeSkeleton, constructor: ImportedConstructorSkeleton ) throws { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) for param in constructor.parameters { try thunkBuilder.liftParameter(param: param) } @@ -3160,19 +3181,6 @@ extension BridgeJSLink { returnType: returnType ) importObjectBuilder.assignToImportObject(name: abiName, function: funcLines) - - if type.from == nil { - let dtsPrinter = CodeFragmentPrinter() - dtsPrinter.write("\(type.name): {") - dtsPrinter.indent { - dtsPrinter.write( - "new\(renderTSSignature(parameters: constructor.parameters, returnType: returnType, effects: Effects(isAsync: false, isThrows: false)));" - ) - } - dtsPrinter.write("}") - - importObjectBuilder.appendDts(dtsPrinter.lines) - } } func renderImportedGetter( @@ -3180,7 +3188,7 @@ extension BridgeJSLink { abiName: String, emitCall: (ImportedThunkBuilder) throws -> String? ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) thunkBuilder.liftSelf() let returnExpr = try emitCall(thunkBuilder) let funcLines = thunkBuilder.renderFunction( @@ -3196,7 +3204,7 @@ extension BridgeJSLink { abiName: String, emitCall: (ImportedThunkBuilder) throws -> String? ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) thunkBuilder.liftSelf() let returnExpr = try emitCall(thunkBuilder) let funcLines = thunkBuilder.renderFunction( @@ -3207,11 +3215,37 @@ extension BridgeJSLink { return (funcLines, []) } + func renderImportedStaticMethod( + context: ImportedTypeSkeleton, + method: ImportedFunctionSkeleton + ) throws -> (js: [String], dts: [String]) { + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) + for param in method.parameters { + try thunkBuilder.liftParameter(param: param) + } + let importRootExpr = context.from == .global ? "globalThis" : "imports" + let constructorExpr = ImportedThunkBuilder.propertyAccessExpr( + objectExpr: importRootExpr, + propertyName: context.jsName ?? context.name + ) + let returnExpr = try thunkBuilder.callStaticMethod( + on: constructorExpr, + name: method.jsName ?? method.name, + returnType: method.returnType + ) + let funcLines = thunkBuilder.renderFunction( + name: method.abiName(context: context, operation: "static"), + returnExpr: returnExpr, + returnType: method.returnType + ) + return (funcLines, []) + } + func renderImportedMethod( context: ImportedTypeSkeleton, method: ImportedFunctionSkeleton ) throws -> (js: [String], dts: [String]) { - let thunkBuilder = ImportedThunkBuilder() + let thunkBuilder = ImportedThunkBuilder(intrinsicRegistry: intrinsicRegistry) thunkBuilder.liftSelf() for param in method.parameters { try thunkBuilder.liftParameter(param: param) @@ -3238,7 +3272,10 @@ extension BridgeJSLink { className: `protocol`.name ) - let getterThunkBuilder = ImportedThunkBuilder(context: .exportSwift) + let getterThunkBuilder = ImportedThunkBuilder( + context: .exportSwift, + intrinsicRegistry: intrinsicRegistry + ) getterThunkBuilder.liftSelf() let returnExpr = try getterThunkBuilder.callPropertyGetter(name: property.name, returnType: property.type) let getterLines = getterThunkBuilder.renderFunction( @@ -3256,7 +3293,10 @@ extension BridgeJSLink { operation: "set", className: `protocol`.name ) - let setterThunkBuilder = ImportedThunkBuilder(context: .exportSwift) + let setterThunkBuilder = ImportedThunkBuilder( + context: .exportSwift, + intrinsicRegistry: intrinsicRegistry + ) setterThunkBuilder.liftSelf() try setterThunkBuilder.liftParameter( param: Parameter(label: nil, name: "value", type: property.type) @@ -3276,7 +3316,10 @@ extension BridgeJSLink { protocol: ExportedProtocol, method: ExportedFunction ) throws { - let thunkBuilder = ImportedThunkBuilder(context: .exportSwift) + let thunkBuilder = ImportedThunkBuilder( + context: .exportSwift, + intrinsicRegistry: intrinsicRegistry + ) thunkBuilder.liftSelf() for param in method.parameters { try thunkBuilder.liftParameter(param: param) @@ -3399,12 +3442,14 @@ extension BridgeType { return "boolean" case .jsObject(let name): return name ?? "any" + case .jsValue: + return "any" case .swiftHeapObject(let name): return name case .unsafePointer: return "number" - case .optional(let wrappedType): - return "\(wrappedType.tsType) | null" + case .nullable(let wrappedType, let kind): + return "\(wrappedType.tsType) | \(kind.absenceLiteral)" case .caseEnum(let name): return "\(name)Tag" case .rawValueEnum(let name, _): @@ -3417,7 +3462,7 @@ extension BridgeType { return name case .swiftProtocol(let name): return name - case .closure(let signature): + case .closure(let signature, _): let paramTypes = signature.parameters.enumerated().map { index, param in "arg\(index): \(param.tsType)" }.joined(separator: ", ") @@ -3428,6 +3473,8 @@ extension BridgeType { return "(\(inner))[]" } return "\(inner)[]" + case .dictionary(let valueType): + return "Record" } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/CodeFragmentPrinter.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/CodeFragmentPrinter.swift deleted file mode 100644 index c4624e694..000000000 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/CodeFragmentPrinter.swift +++ /dev/null @@ -1,41 +0,0 @@ -/// A printer for code fragments. -final class CodeFragmentPrinter { - private(set) var lines: [String] = [] - private var indentLevel: Int = 0 - - init(header: String = "") { - self.lines.append(contentsOf: header.split(separator: "\n").map { String($0) }) - } - - func nextLine() { - lines.append("") - } - - func write(_ line: S) { - lines.append(String(repeating: " ", count: indentLevel * 4) + String(line)) - } - - func write(lines: [String]) { - for line in lines { - write(line) - } - } - - func write(contentsOf printer: CodeFragmentPrinter) { - self.write(lines: printer.lines) - } - - func indent() { - indentLevel += 1 - } - - func unindent() { - indentLevel -= 1 - } - - func indent(_ body: () throws -> Void) rethrows { - indentLevel += 1 - try body() - indentLevel -= 1 - } -} diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 28f756a43..6f848eb05 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -1,6 +1,9 @@ #if canImport(BridgeJSSkeleton) import BridgeJSSkeleton #endif +#if canImport(BridgeJSUtilities) +import BridgeJSUtilities +#endif /// A scope for variables for JS glue code final class JSGlueVariableScope { @@ -20,19 +23,17 @@ final class JSGlueVariableScope { static let reservedStorageToReturnOptionalHeapObject = "tmpRetOptionalHeapObject" static let reservedTextEncoder = "textEncoder" static let reservedTextDecoder = "textDecoder" - static let reservedTmpRetTag = "tmpRetTag" - static let reservedTmpRetStrings = "tmpRetStrings" - static let reservedTmpRetInts = "tmpRetInts" - static let reservedTmpRetF32s = "tmpRetF32s" - static let reservedTmpRetF64s = "tmpRetF64s" - static let reservedTmpParamInts = "tmpParamInts" - static let reservedTmpParamF32s = "tmpParamF32s" - static let reservedTmpParamF64s = "tmpParamF64s" - static let reservedTmpRetPointers = "tmpRetPointers" - static let reservedTmpParamPointers = "tmpParamPointers" - static let reservedTmpStructCleanups = "tmpStructCleanups" + static let reservedStringStack = "strStack" + static let reservedI32Stack = "i32Stack" + static let reservedF32Stack = "f32Stack" + static let reservedF64Stack = "f64Stack" + static let reservedPointerStack = "ptrStack" static let reservedEnumHelpers = "enumHelpers" static let reservedStructHelpers = "structHelpers" + static let reservedSwiftClosureRegistry = "swiftClosureRegistry" + static let reservedMakeSwiftClosure = "makeClosure" + + private let intrinsicRegistry: JSIntrinsicRegistry private var variables: Set = [ reservedSwift, @@ -49,21 +50,21 @@ final class JSGlueVariableScope { reservedStorageToReturnOptionalHeapObject, reservedTextEncoder, reservedTextDecoder, - reservedTmpRetTag, - reservedTmpRetStrings, - reservedTmpRetInts, - reservedTmpRetF32s, - reservedTmpRetF64s, - reservedTmpParamInts, - reservedTmpParamF32s, - reservedTmpParamF64s, - reservedTmpRetPointers, - reservedTmpParamPointers, - reservedTmpStructCleanups, + reservedStringStack, + reservedI32Stack, + reservedF32Stack, + reservedF64Stack, + reservedPointerStack, reservedEnumHelpers, reservedStructHelpers, + reservedSwiftClosureRegistry, + reservedMakeSwiftClosure, ] + init(intrinsicRegistry: JSIntrinsicRegistry) { + self.intrinsicRegistry = intrinsicRegistry + } + /// Returns a unique variable name in the scope based on the given name hint. /// /// - Parameter hint: A hint for the variable name. @@ -80,37 +81,104 @@ final class JSGlueVariableScope { } while !variables.insert(suffixedName).inserted return suffixedName } + + func registerIntrinsic(_ name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { + try intrinsicRegistry.register(name: name, build: build) + } + + func makeChildScope() -> JSGlueVariableScope { + JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) + } + +} + +extension JSGlueVariableScope { + // MARK: Parameter + + func emitPushI32Parameter(_ value: String, printer: CodeFragmentPrinter) { + printer.write("\(JSGlueVariableScope.reservedI32Stack).push(\(value));") + } + func emitPushF64Parameter(_ value: String, printer: CodeFragmentPrinter) { + printer.write("\(JSGlueVariableScope.reservedF64Stack).push(\(value));") + } + func emitPushF32Parameter(_ value: String, printer: CodeFragmentPrinter) { + printer.write("\(JSGlueVariableScope.reservedF32Stack).push(\(value));") + } + func emitPushPointerParameter(_ value: String, printer: CodeFragmentPrinter) { + printer.write("\(JSGlueVariableScope.reservedPointerStack).push(\(value));") + } + + // MARK: Pop + func popString() -> String { + return "\(JSGlueVariableScope.reservedStringStack).pop()" + } + func popI32() -> String { + return "\(JSGlueVariableScope.reservedI32Stack).pop()" + } + func popF64() -> String { + return "\(JSGlueVariableScope.reservedF64Stack).pop()" + } + func popF32() -> String { + return "\(JSGlueVariableScope.reservedF32Stack).pop()" + } + func popPointer() -> String { + return "\(JSGlueVariableScope.reservedPointerStack).pop()" + } } /// A fragment of JS code used to convert a value between Swift and JS. /// /// See `BridgeJSIntrinsics.swift` in the main JavaScriptKit module for Swift side lowering/lifting implementation. struct IntrinsicJSFragment: Sendable { - /// The names of the parameters that the fragment expects. - let parameters: [String] - /// Prints the fragment code. + struct PrintCodeContext { + /// The scope of the variables. + var scope: JSGlueVariableScope + /// The printer to print the main fragment code. + var printer: CodeFragmentPrinter + /// Whether the fragment has direct access to the SwiftHeapObject classes. + /// If false, the fragment needs to use `_exports[""]` to access the class. + var hasDirectAccessToSwiftClass: Bool = true + + func with(_ keyPath: WritableKeyPath, _ value: T) -> PrintCodeContext { + var new = self + new[keyPath: keyPath] = value + return new + } + } + + /// A function that prints the fragment code. /// /// - Parameters: /// - arguments: The arguments that the fragment expects. An argument may be an expression with side effects, /// so the callee is responsible for evaluating the arguments only once. - /// - scope: The scope of the variables. - /// - printer: The printer to print the main fragment code. - /// - cleanupCode: The printer to print the code that is expected to be executed at the end of the caller of the - /// fragment. + /// - context: The context of the printing. /// - Returns: List of result expressions. - let printCode: + typealias PrintCode = @Sendable ( _ arguments: [String], - _ scope: JSGlueVariableScope, - _ printer: CodeFragmentPrinter, - _ cleanupCode: CodeFragmentPrinter - ) -> [String] + _ context: PrintCodeContext + ) throws -> [String] + + /// The names of the parameters that the fragment expects. + let parameters: [String] + + /// Prints the fragment code. + let printCode: PrintCode + + init(parameters: [String], printCode: @escaping PrintCode) { + self.parameters = parameters + self.printCode = printCode + } + + func printCode(_ arguments: [String], _ context: PrintCodeContext) throws -> [String] { + return try printCode(arguments, context) + } /// A fragment that does nothing static let void = IntrinsicJSFragment( parameters: [], - printCode: { _, _, _, _ in + printCode: { _, _ in return [] } ) @@ -118,57 +186,52 @@ struct IntrinsicJSFragment: Sendable { /// A fragment that returns the argument as is. static let identity = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return [arguments[0]] } ) - /// NOTE: JavaScript engine itself converts booleans to integers when passing them to - /// Wasm functions, so we don't need to do anything here - static let boolLowerParameter = identity + // MARK: - Scalar Coercion Fragments + static let boolLiftReturn = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in - return ["\(arguments[0]) !== 0"] - } - ) - static let boolLiftParameter = IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(arguments[0]) !== 0"] } ) + static let boolLiftParameter = boolLiftReturn static let boolLowerReturn = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(arguments[0]) ? 1 : 0"] } ) - - /// Convert signed Int32 to unsigned for UInt values static let uintLiftReturn = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(arguments[0]) >>> 0"] } ) static let uintLiftParameter = uintLiftReturn + // MARK: - String Fragments + static let stringLowerParameter = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let argument = arguments[0] let bytesLabel = scope.variable("\(argument)Bytes") let bytesIdLabel = scope.variable("\(argument)Id") printer.write("const \(bytesLabel) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(argument));") printer.write("const \(bytesIdLabel) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesLabel));") - cleanupCode.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(bytesIdLabel));") return [bytesIdLabel, "\(bytesLabel).length"] } ) static let stringLiftReturn = IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultLabel = scope.variable("ret") printer.write("const \(resultLabel) = \(JSGlueVariableScope.reservedStorageToReturnString);") printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = undefined;") @@ -177,18 +240,22 @@ struct IntrinsicJSFragment: Sendable { ) static let stringLiftParameter = IntrinsicJSFragment( parameters: ["objectId"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let objectId = arguments[0] let objectLabel = scope.variable("\(objectId)Object") // TODO: Implement "take" operation - printer.write("const \(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));") + printer.write( + "const \(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));" + ) printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(objectId));") return [objectLabel] } ) static let stringLowerReturn = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let printer = context.printer printer.write( "\(JSGlueVariableScope.reservedStorageToReturnBytes) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(arguments[0]));" ) @@ -196,88 +263,325 @@ struct IntrinsicJSFragment: Sendable { } ) + // MARK: - JSObject Fragments + static let jsObjectLowerParameter = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["swift.memory.retain(\(arguments[0]))"] } ) - static let jsObjectLiftReturn = IntrinsicJSFragment( - parameters: ["retId"], - printCode: { arguments, scope, printer, cleanupCode in - // TODO: Implement "take" operation - let resultLabel = scope.variable("ret") - let retId = arguments[0] - printer.write("const \(resultLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(retId));") - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(retId));") - return [resultLabel] - } - ) - static let jsObjectLiftRetainedObjectId = IntrinsicJSFragment( - parameters: ["objectId"], - printCode: { arguments, scope, printer, cleanupCode in - let resultLabel = scope.variable("value") - let objectId = arguments[0] - printer.write( - "const \(resultLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));" - ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(objectId));") - return [resultLabel] - } - ) + private static func jsObjectTakeRetained(hint: String = "ret") -> IntrinsicJSFragment { + IntrinsicJSFragment( + parameters: ["objectId"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + // TODO: Implement "take" operation + let resultLabel = scope.variable(hint) + let objectId = arguments[0] + printer.write( + "const \(resultLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));" + ) + printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(objectId));") + return [resultLabel] + } + ) + } + static let jsObjectLiftReturn = jsObjectTakeRetained(hint: "ret") + static let jsObjectLiftRetainedObjectId = jsObjectTakeRetained(hint: "value") static let jsObjectLiftParameter = IntrinsicJSFragment( parameters: ["objectId"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(JSGlueVariableScope.reservedSwift).memory.getObject(\(arguments[0]))"] } ) static let jsObjectLowerReturn = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(JSGlueVariableScope.reservedSwift).memory.retain(\(arguments[0]))"] } ) + // MARK: - JSValue Fragments + + private static let jsValueLowerHelperName = "__bjs_jsValueLower" + private static let jsValueLiftHelperName = "__bjs_jsValueLift" + + private static func registerJSValueHelpers(scope: JSGlueVariableScope) { + scope.registerIntrinsic("jsValueHelpers") { helperPrinter in + helperPrinter.write("function \(jsValueLowerHelperName)(value) {") + helperPrinter.indent { + emitJSValueLowerBody( + value: "value", + kindVar: "kind", + payload1Var: "payload1", + payload2Var: "payload2", + printer: helperPrinter + ) + helperPrinter.write("return [kind, payload1, payload2];") + } + helperPrinter.write("}") + helperPrinter.write("function \(jsValueLiftHelperName)(kind, payload1, payload2) {") + helperPrinter.indent { + let helperScope = scope.makeChildScope() + let resultVar = emitJSValueConstruction( + kind: "kind", + payload1: "payload1", + payload2: "payload2", + scope: helperScope, + printer: helperPrinter + ) + helperPrinter.write("return \(resultVar);") + } + helperPrinter.write("}") + } + } + + private static func emitJSValueLowerBody( + value: String, + kindVar: String, + payload1Var: String, + payload2Var: String, + printer: CodeFragmentPrinter + ) { + printer.write("let \(kindVar);") + printer.write("let \(payload1Var);") + printer.write("let \(payload2Var);") + printer.write("if (\(value) === null) {") + printer.indent { + printer.write("\(kindVar) = 4;") + printer.write("\(payload1Var) = 0;") + printer.write("\(payload2Var) = 0;") + } + printer.write("} else {") + printer.indent { + printer.write("switch (typeof \(value)) {") + printer.indent { + printer.write("case \"boolean\":") + printer.indent { + printer.write("\(kindVar) = 0;") + printer.write("\(payload1Var) = \(value) ? 1 : 0;") + printer.write("\(payload2Var) = 0;") + printer.write("break;") + } + printer.write("case \"number\":") + printer.indent { + printer.write("\(kindVar) = 2;") + printer.write("\(payload1Var) = 0;") + printer.write("\(payload2Var) = \(value);") + printer.write("break;") + } + func emitRetainCase(_ caseName: String, kind: Int) { + printer.write("case \"\(caseName)\":") + printer.indent { + printer.write("\(kindVar) = \(kind);") + printer.write( + "\(payload1Var) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));" + ) + printer.write("\(payload2Var) = 0;") + printer.write("break;") + } + } + emitRetainCase("string", kind: 1) + printer.write("case \"undefined\":") + printer.indent { + printer.write("\(kindVar) = 5;") + printer.write("\(payload1Var) = 0;") + printer.write("\(payload2Var) = 0;") + printer.write("break;") + } + emitRetainCase("object", kind: 3) + emitRetainCase("function", kind: 3) + emitRetainCase("symbol", kind: 7) + emitRetainCase("bigint", kind: 8) + printer.write("default:") + printer.indent { + printer.write("throw new TypeError(\"Unsupported JSValue type\");") + } + } + printer.write("}") + } + printer.write("}") + } + + static let jsValueLower = IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let kindVar = scope.variable("\(value)Kind") + let payload1Var = scope.variable("\(value)Payload1") + let payload2Var = scope.variable("\(value)Payload2") + registerJSValueHelpers(scope: scope) + printer.write( + "const [\(kindVar), \(payload1Var), \(payload2Var)] = \(jsValueLowerHelperName)(\(value));" + ) + return [kindVar, payload1Var, payload2Var] + } + ) + + private static func emitJSValueConstruction( + kind: String, + payload1: String, + payload2: String, + scope: JSGlueVariableScope, + printer: CodeFragmentPrinter + ) -> String { + let resultVar = scope.variable("jsValue") + printer.write("let \(resultVar);") + printer.write("switch (\(kind)) {") + printer.indent { + printer.write("case 0:") + printer.indent { + printer.write("\(resultVar) = \(payload1) !== 0;") + printer.write("break;") + } + printer.write("case 1:") + printer.indent { + printer.write( + "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" + ) + printer.write("break;") + } + printer.write("case 2:") + printer.indent { + printer.write("\(resultVar) = \(payload2);") + printer.write("break;") + } + printer.write("case 3:") + printer.indent { + printer.write( + "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" + ) + printer.write("break;") + } + printer.write("case 4:") + printer.indent { + printer.write("\(resultVar) = null;") + printer.write("break;") + } + printer.write("case 5:") + printer.indent { + printer.write("\(resultVar) = undefined;") + printer.write("break;") + } + printer.write("case 7:") + printer.indent { + printer.write( + "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" + ) + printer.write("break;") + } + printer.write("case 8:") + printer.indent { + printer.write( + "\(resultVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(payload1));" + ) + printer.write("break;") + } + printer.write("default:") + printer.indent { + printer.write("throw new TypeError(\"Unsupported JSValue kind \" + \(kind));") + } + } + printer.write("}") + return resultVar + } + + static func jsValueLowerReturn(context: BridgeContext) -> IntrinsicJSFragment { + return IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let lowered = try jsValueLower.printCode(arguments, context) + let kindVar = lowered[0] + let payload1Var = lowered[1] + let payload2Var = lowered[2] + scope.emitPushI32Parameter(kindVar, printer: printer) + scope.emitPushI32Parameter(payload1Var, printer: printer) + scope.emitPushF64Parameter(payload2Var, printer: printer) + return [] + } + ) + } + + static let jsValueLift = IntrinsicJSFragment( + parameters: [], + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let payload2 = scope.variable("jsValuePayload2") + let payload1 = scope.variable("jsValuePayload1") + let kind = scope.variable("jsValueKind") + printer.write("const \(payload2) = \(scope.popF64());") + printer.write("const \(payload1) = \(scope.popI32());") + printer.write("const \(kind) = \(scope.popI32());") + let resultVar = scope.variable("jsValue") + registerJSValueHelpers(scope: scope) + printer.write( + "const \(resultVar) = \(jsValueLiftHelperName)(\(kind), \(payload1), \(payload2));" + ) + return [resultVar] + } + ) + static let jsValueLiftParameter = IntrinsicJSFragment( + parameters: ["kind", "payload1", "payload2"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("jsValue") + registerJSValueHelpers(scope: scope) + printer.write( + "const \(resultVar) = \(jsValueLiftHelperName)(\(arguments[0]), \(arguments[1]), \(arguments[2]));" + ) + return [resultVar] + } + ) + + // MARK: - SwiftHeapObject Fragments + static let swiftHeapObjectLowerParameter = IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, _ in return ["\(arguments[0]).pointer"] } ) + static let swiftHeapObjectLowerReturn = IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, _ in + return ["\(arguments[0]).pointer"] + } + ) + static func swiftHeapObjectLiftReturn(_ name: String) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in - return ["\(name).__construct(\(arguments[0]))"] + printCode: { arguments, context in + return [ + "\(context.hasDirectAccessToSwiftClass ? name : "_exports['\(name)']").__construct(\(arguments[0]))" + ] } ) } static func swiftHeapObjectLiftParameter(_ name: String) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["pointer"], - printCode: { arguments, scope, printer, cleanupCode in - return ["\(name).__construct(\(arguments[0]))"] + printCode: { arguments, context in + return ["_exports['\(name)'].__construct(\(arguments[0]))"] } ) } - static let swiftHeapObjectLowerReturn = IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in - return ["\(arguments[0]).pointer"] - } - ) + + // MARK: - Associated Enum Fragments static func associatedEnumLowerParameter(enumBase: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let caseIdName = "\(value)CaseId" - let cleanupName = "\(value)Cleanup" + let caseIdName = scope.variable("\(value)CaseId") printer.write( - "const { caseId: \(caseIdName), cleanup: \(cleanupName) } = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lower(\(value));" + "const \(caseIdName) = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lower(\(value));" ) - cleanup.write("if (\(cleanupName)) { \(cleanupName)(); }") return [caseIdName] } ) @@ -286,472 +590,377 @@ struct IntrinsicJSFragment: Sendable { static func associatedEnumLiftReturn(enumBase: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: [], - printCode: { _, scope, printer, _ in + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) let retName = scope.variable("ret") printer.write( - "const \(retName) = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lift(\(JSGlueVariableScope.reservedTmpRetTag), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" + "const \(retName) = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lift(\(scope.popI32()));" ) return [retName] } ) } - static func optionalLiftParameter(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + // MARK: - Optional Handling + + static func optionalLiftParameter( + wrappedType: BridgeType, + kind: JSOptionalKind, + context bridgeContext: BridgeContext = .importTS + ) throws -> IntrinsicJSFragment { + if wrappedType.isSingleParamScalar { + let coerce = wrappedType.liftCoerce + return IntrinsicJSFragment( + parameters: ["isSome", "wrappedValue"], + printCode: { arguments, _ in + let isSome = arguments[0] + let wrappedValue = arguments[1] + let absenceLiteral = kind.absenceLiteral + if let coerce { + let coerced = coerce.replacingOccurrences(of: "$0", with: wrappedValue) + return ["\(isSome) ? \(coerced) : \(absenceLiteral)"] + } + return ["\(isSome) ? \(wrappedValue) : \(absenceLiteral)"] + } + ) + } + + let innerFragment = try liftParameter(type: wrappedType, context: bridgeContext) + return compositeOptionalLiftParameter( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment + ) + } + + private static func compositeOptionalLiftParameter( + wrappedType: BridgeType, + kind: JSOptionalKind, + innerFragment: IntrinsicJSFragment + ) -> IntrinsicJSFragment { + let isStackConvention = wrappedType.optionalConvention == .stackABI + let absenceLiteral = kind.absenceLiteral + + let outerParams: [String] + if isStackConvention { + outerParams = ["isSome"] + } else { + outerParams = ["isSome"] + innerFragment.parameters + } + return IntrinsicJSFragment( - parameters: ["isSome", "wrappedValue"], - printCode: { arguments, scope, printer, cleanupCode in + parameters: outerParams, + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let isSome = arguments[0] - let wrappedValue = arguments[1] - let resultExpr: String - - switch wrappedType { - case .int, .float, .double, .caseEnum: - resultExpr = "\(isSome) ? \(wrappedValue) : null" - case .bool: - resultExpr = "\(isSome) ? \(wrappedValue) !== 0 : null" - case .string: - let objectLabel = scope.variable("obj") - printer.write("let \(objectLabel);") + let innerArgs = isStackConvention ? [] : Array(arguments.dropFirst()) + + let bufferPrinter = CodeFragmentPrinter() + let innerResults = try innerFragment.printCode( + innerArgs, + context.with(\.printer, bufferPrinter) + ) + + let hasSideEffects = !bufferPrinter.lines.isEmpty + let innerExpr = innerResults.first ?? "undefined" + + if hasSideEffects { + let resultVar = scope.variable("optResult") + printer.write("let \(resultVar);") printer.write("if (\(isSome)) {") printer.indent { - printer.write( - "\(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(wrappedValue));" - ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(wrappedValue));") - } - printer.write("}") - resultExpr = "\(isSome) ? \(objectLabel) : null" - case .swiftHeapObject(let name): - resultExpr = "\(isSome) ? \(name).__construct(\(wrappedValue)) : null" - case .jsObject: - resultExpr = - "\(isSome) ? \(JSGlueVariableScope.reservedSwift).memory.getObject(\(wrappedValue)) : null" - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - let objectLabel = scope.variable("obj") - printer.write("let \(objectLabel);") - printer.write("if (\(isSome)) {") - printer.indent { - printer.write( - "\(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(wrappedValue));" - ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(wrappedValue));") + for line in bufferPrinter.lines { + printer.write(line) } - printer.write("}") - resultExpr = "\(isSome) ? \(objectLabel) : null" - case .bool: - resultExpr = "\(isSome) ? \(wrappedValue) !== 0 : null" - default: - resultExpr = "\(isSome) ? \(wrappedValue) : null" - } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let enumVar = scope.variable("enumValue") - printer.write("let \(enumVar);") - printer.write("if (\(isSome)) {") - printer.indent { - printer.write( - "\(enumVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(wrappedValue), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" - ) - } - printer.write("}") - resultExpr = "\(isSome) ? \(enumVar) : null" - case .swiftStruct(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let structVar = scope.variable("structValue") - printer.write("let \(structVar);") - printer.write("if (\(isSome)) {") - printer.indent { - printer.write( - "\(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" - ) + printer.write("\(resultVar) = \(innerExpr);") } printer.write("} else {") printer.indent { - printer.write("\(structVar) = null;") + printer.write("\(resultVar) = \(absenceLiteral);") } printer.write("}") - resultExpr = structVar - case .array(let elementType): - let arrayVar = scope.variable("arrayValue") - printer.write("let \(arrayVar);") - printer.write("if (\(isSome)) {") - printer.indent { - // Lift array from stacks - reuse array lift return logic - let arrayLiftFragment = try! arrayLift(elementType: elementType) - let liftResults = arrayLiftFragment.printCode([], scope, printer, cleanupCode) - if let liftResult = liftResults.first { - printer.write("\(arrayVar) = \(liftResult);") - } - } - printer.write("} else {") - printer.indent { - printer.write("\(arrayVar) = null;") + return [resultVar] + } else { + return ["\(isSome) ? \(innerExpr) : \(absenceLiteral)"] + } + } + ) + } + + static func optionalLowerParameter( + wrappedType: BridgeType, + kind: JSOptionalKind + ) throws -> IntrinsicJSFragment { + if wrappedType.isSingleParamScalar { + let wasmType = wrappedType.wasmParams[0].type + let coerce = wrappedType.lowerCoerce + return IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr);") + let coerced: String + if let coerce { + coerced = coerce.replacingOccurrences(of: "$0", with: value) + } else { + coerced = value } - printer.write("}") - resultExpr = arrayVar - default: - resultExpr = "\(isSome) ? \(wrappedValue) : null" + return ["+\(isSomeVar)", "\(isSomeVar) ? \(coerced) : \(wasmType.jsZeroLiteral)"] } + ) + } - return [resultExpr] - } + let innerFragment = try lowerParameter(type: wrappedType) + return try compositeOptionalLowerParameter( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment ) } - static func optionalLowerParameter(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + private static func compositeOptionalLowerParameter( + wrappedType: BridgeType, + kind: JSOptionalKind, + innerFragment: IntrinsicJSFragment + ) throws -> IntrinsicJSFragment { + let isStackConvention = wrappedType.optionalConvention == .stackABI + return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(value) != null;") + printer.write("const \(isSomeVar) = \(kind.presenceCheck(value: value));") - switch wrappedType { - case .swiftStruct(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let cleanupVar = scope.variable("\(value)Cleanup") - printer.write("let \(cleanupVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let resultVar = scope.variable("structResult") - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lower(\(value));" - ) - printer.write("\(cleanupVar) = \(resultVar).cleanup;") - } - printer.write("}") - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - return ["+\(isSomeVar)"] - case .string, .rawValueEnum(_, .string): - let bytesVar = scope.variable("\(value)Bytes") - let idVar = scope.variable("\(value)Id") + let ifBodyPrinter = CodeFragmentPrinter() + let innerResults = try innerFragment.printCode( + [value], + context.with(\.printer, ifBodyPrinter) + ) - printer.write("let \(idVar), \(bytesVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));") - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") + let resultVars = innerResults.map { _ in scope.variable("result") } + assert( + isStackConvention || resultVars.count == wrappedType.wasmParams.count, + "Inner fragment result count (\(resultVars.count)) must match wasmParams count (\(wrappedType.wasmParams.count)) for \(wrappedType)" + ) + if !resultVars.isEmpty { + printer.write("let \(resultVars.joined(separator: ", "));") + } + + printer.write("if (\(isSomeVar)) {") + printer.indent { + for line in ifBodyPrinter.lines { + printer.write(line) } - printer.write("}") - cleanupCode.write("if (\(idVar) != undefined) {") - cleanupCode.indent { - cleanupCode.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") + for (resultVar, innerResult) in zip(resultVars, innerResults) { + printer.write("\(resultVar) = \(innerResult);") } - cleanupCode.write("}") - - return ["+\(isSomeVar)", "\(isSomeVar) ? \(idVar) : 0", "\(isSomeVar) ? \(bytesVar).length : 0"] - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let caseIdVar = scope.variable("\(value)CaseId") - let cleanupVar = scope.variable("\(value)Cleanup") + } - printer.write("let \(caseIdVar), \(cleanupVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let resultVar = scope.variable("enumResult") - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" - ) - printer.write("\(caseIdVar) = \(resultVar).caseId;") - printer.write("\(cleanupVar) = \(resultVar).cleanup;") - } - printer.write("}") - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - - return ["+\(isSomeVar)", "\(isSomeVar) ? \(caseIdVar) : 0"] - case .rawValueEnum: - // Raw value enums with optional - falls through to handle based on raw type - return ["+\(isSomeVar)", "\(isSomeVar) ? \(value) : 0"] - case .array(let elementType): - let cleanupArrayVar = scope.variable("\(value)Cleanups") - printer.write("const \(cleanupArrayVar) = [];") - printer.write("if (\(isSomeVar)) {") + let hasPlaceholders = !isStackConvention && !wrappedType.wasmParams.isEmpty + if hasPlaceholders { + printer.write("} else {") printer.indent { - let arrayLowerFragment = try! arrayLower(elementType: elementType) - let arrayCleanup = CodeFragmentPrinter() - let _ = arrayLowerFragment.printCode([value], scope, printer, arrayCleanup) - if !arrayCleanup.lines.isEmpty { - for line in arrayCleanup.lines { - printer.write("\(cleanupArrayVar).push(() => { \(line) });") - } + for (resultVar, param) in zip(resultVars, wrappedType.wasmParams) { + printer.write("\(resultVar) = \(param.type.jsZeroLiteral);") } } - printer.write("}") - cleanupCode.write("for (const cleanup of \(cleanupArrayVar)) { cleanup(); }") - return ["+\(isSomeVar)"] - default: - switch wrappedType { - case .swiftHeapObject: - return ["+\(isSomeVar)", "\(isSomeVar) ? \(value).pointer : 0"] - case .swiftProtocol: - return [ - "+\(isSomeVar)", - "\(isSomeVar) ? \(JSGlueVariableScope.reservedSwift).memory.retain(\(value)) : 0", - ] - case .jsObject: - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - } - printer.write("}") - cleanupCode.write("if (\(idVar) !== undefined) {") - cleanupCode.indent { - cleanupCode.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - } - cleanupCode.write("}") - return ["+\(isSomeVar)", "\(isSomeVar) ? \(idVar) : 0"] - default: - return ["+\(isSomeVar)", "\(isSomeVar) ? \(value) : 0"] - } + } + printer.write("}") + + if isStackConvention { + scope.emitPushI32Parameter("+\(isSomeVar)", printer: printer) + return [] + } else { + return ["+\(isSomeVar)"] + resultVars } } ) } - static func optionalLiftReturn( + private static func optionalLiftReturnFromStorage(storage: String) -> IntrinsicJSFragment { + IntrinsicJSFragment( + parameters: [], + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("optResult") + printer.write("const \(resultVar) = \(storage);") + printer.write("\(storage) = undefined;") + return [resultVar] + } + ) + } + + private static func optionalLiftReturnWithPresenceFlag( wrappedType: BridgeType, - context: BridgeContext = .exportSwift + kind: JSOptionalKind ) -> IntrinsicJSFragment { + let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let isSomeVar = scope.variable("isSome") + printer.write("const \(isSomeVar) = \(scope.popI32());") + + let innerFragment = try liftReturn(type: wrappedType) + + let innerPrinter = CodeFragmentPrinter() + let innerResults = try innerFragment.printCode([], context.with(\.printer, innerPrinter)) + let innerExpr = innerResults.first ?? "undefined" + + if innerPrinter.lines.isEmpty { + return ["\(isSomeVar) ? \(innerExpr) : \(absenceLiteral)"] + } + let resultVar = scope.variable("optResult") - switch wrappedType { - case .bool: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalBool);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalBool) = undefined;") - case .int, .uint: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalInt);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = undefined;") - case .float: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalFloat);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalFloat) = undefined;") - case .double: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalDouble);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalDouble) = undefined;") - case .string: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnString);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = undefined;") - case .jsObject, .swiftProtocol: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnString);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = undefined;") - case .swiftHeapObject(let className): - let pointerVar = scope.variable("pointer") - printer.write( - "const \(pointerVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject);" - ) - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject) = undefined;") - let constructExpr = - context == .exportSwift - ? "\(className).__construct(\(pointerVar))" - : "_exports['\(className)'].__construct(\(pointerVar))" - printer.write( - "const \(resultVar) = \(pointerVar) === null ? null : \(constructExpr);" - ) - case .caseEnum: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalInt);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = undefined;") - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnString);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = undefined;") - case .bool: - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalBool);" - ) - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalBool) = undefined;") - case .float: - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalFloat);" - ) - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalFloat) = undefined;") - case .double: - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalDouble);" - ) - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalDouble) = undefined;") - default: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalInt);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = undefined;") - } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let isNullVar = scope.variable("isNull") - printer.write("const \(isNullVar) = (\(JSGlueVariableScope.reservedTmpRetTag) === -1);") - printer.write("let \(resultVar);") - printer.write("if (\(isNullVar)) {") - printer.indent { - printer.write("\(resultVar) = null;") - } - printer.write("} else {") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetTag), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" - ) - } - printer.write("}") - case .swiftStruct(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - printer.write("let \(resultVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" - ) - } - printer.write("} else {") - printer.indent { - printer.write("\(resultVar) = null;") - } - printer.write("}") - case .array(let elementType): - let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - printer.write("let \(resultVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let arrayLiftFragment = try! arrayLift(elementType: elementType) - let liftResults = arrayLiftFragment.printCode([], scope, printer, cleanupCode) - if let liftResult = liftResults.first { - printer.write("\(resultVar) = \(liftResult);") - } - } - printer.write("} else {") - printer.indent { - printer.write("\(resultVar) = null;") + printer.write("let \(resultVar);") + printer.write("if (\(isSomeVar)) {") + printer.indent { + for line in innerPrinter.lines { + printer.write(line) } - printer.write("}") - default: - printer.write("const \(resultVar) = \(JSGlueVariableScope.reservedStorageToReturnString);") - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = undefined;") + printer.write("\(resultVar) = \(innerExpr);") + } + printer.write("} else {") + printer.indent { + printer.write("\(resultVar) = \(absenceLiteral);") } + printer.write("}") return [resultVar] } ) } - static func optionalLowerReturn(wrappedType: BridgeType) throws -> IntrinsicJSFragment { - switch wrappedType { - case .void, .optional, .namespaceEnum, .closure: - throw BridgeJSLinkError(message: "Unsupported optional wrapped type for protocol export: \(wrappedType)") - default: break - } + private static func optionalLiftReturnAssociatedEnum( + fullName: String, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + let base = fullName.components(separatedBy: ".").last ?? fullName + let absenceLiteral = kind.absenceLiteral + return IntrinsicJSFragment( + parameters: [], + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("optResult") + let tagVar = scope.variable("tag") + printer.write("const \(tagVar) = \(scope.popI32());") + printer.write( + "const \(resultVar) = \(tagVar) === -1 ? \(absenceLiteral) : \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(tagVar));" + ) + return [resultVar] + } + ) + } + + private static func optionalLiftReturnHeapObject( + className: String, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + let absenceLiteral = kind.absenceLiteral + return IntrinsicJSFragment( + parameters: [], + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("optResult") + let pointerVar = scope.variable("pointer") + printer.write( + "const \(pointerVar) = \(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject);" + ) + printer.write( + "\(JSGlueVariableScope.reservedStorageToReturnOptionalHeapObject) = undefined;" + ) + let constructExpr = + context.hasDirectAccessToSwiftClass + ? "\(className).__construct(\(pointerVar))" + : "_exports['\(className)'].__construct(\(pointerVar))" + printer.write( + "const \(resultVar) = \(pointerVar) === null ? \(absenceLiteral) : \(constructExpr);" + ) + return [resultVar] + } + ) + } + private static func optionalLiftReturnStruct( + fullName: String, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + let base = fullName.components(separatedBy: ".").last ?? fullName + let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( + parameters: [], + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let isSomeVar = scope.variable("isSome") + let resultVar = scope.variable("optResult") + printer.write("const \(isSomeVar) = \(scope.popI32());") + printer.write( + "const \(resultVar) = \(isSomeVar) ? \(JSGlueVariableScope.reservedStructHelpers).\(base).lift() : \(absenceLiteral);" + ) + return [resultVar] + } + ) + } + + static func optionalLiftReturn( + wrappedType: BridgeType, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + if let scalarKind = wrappedType.optionalScalarKind { + return optionalLiftReturnFromStorage(storage: scalarKind.storageName) + } + if case .sideChannelReturn(let mode) = wrappedType.optionalConvention, mode != .none { + return optionalLiftReturnFromStorage(storage: JSGlueVariableScope.reservedStorageToReturnString) + } + + if case .swiftHeapObject(let className) = wrappedType { + return optionalLiftReturnHeapObject(className: className, kind: kind) + } + + if case .swiftStruct(let fullName) = wrappedType { + return optionalLiftReturnStruct(fullName: fullName, kind: kind) + } + + if wrappedType.nilSentinel.hasSentinel, case .associatedValueEnum(let fullName) = wrappedType { + return optionalLiftReturnAssociatedEnum(fullName: fullName, kind: kind) + } + + return optionalLiftReturnWithPresenceFlag(wrappedType: wrappedType, kind: kind) + } + + private static func optionalLowerReturnToSideChannel( + mode: OptionalSideChannel, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(value) != null;") + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr);") - switch wrappedType { - case .bool: + if mode == .storage { printer.write( - "bjs[\"swift_js_return_optional_bool\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? (\(value) ? 1 : 0) : 0);" + "\(JSGlueVariableScope.reservedStorageToReturnString) = \(isSomeVar) ? \(value) : \(kind.absenceLiteral);" ) - case .int, .uint: - printer.write( - "bjs[\"swift_js_return_optional_int\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? (\(value) | 0) : 0);" - ) - case .caseEnum: - printer.write("return \(isSomeVar) ? (\(value) | 0) : -1;") - case .float: - printer.write( - "bjs[\"swift_js_return_optional_float\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? Math.fround(\(value)) : 0.0);" - ) - case .double: - printer.write( - "bjs[\"swift_js_return_optional_double\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? \(value) : 0.0);" - ) - case .string: - let bytesVar = scope.variable("bytes") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write( - "const \(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));" - ) - printer.write("bjs[\"swift_js_return_optional_string\"](1, \(bytesVar), \(bytesVar).length);") - printer.write("return \(bytesVar).length;") - } - printer.write("} else {") - printer.indent { - printer.write("bjs[\"swift_js_return_optional_string\"](0, 0, 0);") - printer.write("return -1;") - } - printer.write("}") - case .jsObject, .swiftProtocol: + } else { let idVar = scope.variable("id") printer.write("let \(idVar) = 0;") printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - } - printer.write("}") - printer.write("bjs[\"swift_js_return_optional_object\"](\(isSomeVar) ? 1 : 0, \(idVar));") - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - let bytesVar = scope.variable("bytes") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write( - "const \(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));" - ) - printer.write( - "bjs[\"swift_js_return_optional_string\"](1, \(bytesVar), \(bytesVar).length);" - ) - } - printer.write("} else {") - printer.indent { - printer.write("bjs[\"swift_js_return_optional_string\"](0, 0, 0);") - } - printer.write("}") - default: - switch rawType { - case .bool: - printer.write( - "bjs[\"swift_js_return_optional_bool\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? (\(value) ? 1 : 0) : 0);" - ) - case .float: - printer.write( - "bjs[\"swift_js_return_optional_float\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? Math.fround(\(value)) : 0.0);" - ) - case .double: - printer.write( - "bjs[\"swift_js_return_optional_double\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? \(value) : 0.0);" - ) - default: - printer.write( - "bjs[\"swift_js_return_optional_int\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? (\(value) | 0) : 0);" - ) - } - } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("cleanup") - printer.write("if (\(isSomeVar)) {") printer.indent { printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" + "\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));" ) - printer.write("return \(caseIdVar);") - } - printer.write("} else {") - printer.indent { - printer.write("return -1;") } printer.write("}") - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - default: - () + printer.write("bjs[\"swift_js_return_optional_object\"](\(isSomeVar) ? 1 : 0, \(idVar));") } return [] @@ -759,426 +968,151 @@ struct IntrinsicJSFragment: Sendable { ) } - // MARK: - Protocol Support - - static func protocolPropertyOptionalToSideChannel(wrappedType: BridgeType) throws -> IntrinsicJSFragment { - switch wrappedType { - case .string, .int, .float, .double, .jsObject, .swiftProtocol: - break - case .rawValueEnum(_, let rawType): - switch rawType { - case .string, .int, .float, .double: - break - default: - throw BridgeJSLinkError( - message: "Unsupported raw value enum type for protocol property side channel: \(rawType)" - ) - } - default: - throw BridgeJSLinkError( - message: "Type \(wrappedType) does not use side channel for protocol property returns" - ) - } - - return IntrinsicJSFragment( + private static func optionalLowerReturnWithPresenceFlag( + wrappedType: BridgeType, + kind: JSOptionalKind, + innerFragment: IntrinsicJSFragment + ) -> IntrinsicJSFragment { + IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] + let isSomeVar = scope.variable("isSome") + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr);") - switch wrappedType { - case .string, .rawValueEnum(_, .string): - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = \(value);") - case .int, .rawValueEnum(_, .int): - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = \(value);") - case .float, .rawValueEnum(_, .float): - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalFloat) = \(value);") - case .double, .rawValueEnum(_, .double): - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalDouble) = \(value);") - case .jsObject, .swiftProtocol: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = \(value);") - default: - fatalError("Unsupported type in protocolPropertyOptionalToSideChannel: \(wrappedType)") + let innerPrinter = CodeFragmentPrinter() + let innerResults = try innerFragment.printCode( + [value], + context.with(\.printer, innerPrinter) + ) + if !innerResults.isEmpty { + throw BridgeJSLinkError( + message: "Unsupported wrapped type for returning from JS function: \(wrappedType)" + ) + } + + printer.write("if (\(isSomeVar)) {") + printer.indent { + for line in innerPrinter.lines { + printer.write(line) + } } + printer.write("}") + scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) return [] } ) } - // MARK: - Closure Support + static func optionalLowerReturn(wrappedType: BridgeType, kind: JSOptionalKind) throws -> IntrinsicJSFragment { + switch wrappedType { + case .void, .nullable, .namespaceEnum, .closure: + throw BridgeJSLinkError(message: "Unsupported optional wrapped type for protocol export: \(wrappedType)") + default: break + } - /// Lifts a WASM parameter to JS for passing to a JS callback (invoke_js_callback_*) - static func closureLiftParameter(type: BridgeType) throws -> IntrinsicJSFragment { - switch type { - case .int, .float, .double, .caseEnum: + if let scalarKind = wrappedType.optionalScalarKind, + !wrappedType.nilSentinel.hasSentinel, wrappedType.wasmParams.count == 1 + { + let wasmType = wrappedType.wasmParams[0].type + let funcName = scalarKind.funcName + let stackCoerce = wrappedType.stackLowerCoerce return IntrinsicJSFragment( - parameters: ["value", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("let \(arguments[1]) = \(arguments[0]);") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["value", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLiftParameter - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("let \(arguments[1]) = \(lifted[0]);") - return [] - } - ) - case .string: - return IntrinsicJSFragment( - parameters: ["objectId", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = stringLiftParameter - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("let \(arguments[1]) = String(\(lifted[0]));") - return [] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: ["objectId", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = stringLiftParameter - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("let \(arguments[1]) = String(\(lifted[0]));") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["value", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLiftParameter - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("let \(arguments[1]) = \(lifted[0]);") - return [] - } - ) - default: - return IntrinsicJSFragment( - parameters: ["value", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("let \(arguments[1]) = \(arguments[0]);") - return [] + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr);") + var coerced: String + if let coerce = stackCoerce { + coerced = coerce.replacingOccurrences(of: "$0", with: value) + if coerced.contains("?") && !coerced.hasPrefix("(") { + coerced = "(\(coerced))" + } + } else { + coerced = value } - ) - } - case .jsObject: - return IntrinsicJSFragment( - parameters: ["objectId", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let objectId = arguments[0] - let targetVar = arguments[1] - printer.write( - "let \(targetVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(objectId));" - ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(objectId));") - return [] - } - ) - case .swiftHeapObject(let name): - return IntrinsicJSFragment( - parameters: ["pointer", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let pointer = arguments[0] - let targetVar = arguments[1] - printer.write("let \(targetVar) = _exports['\(name)'].__construct(\(pointer));") - return [] - } - ) - case .associatedValueEnum(let fullName): - return IntrinsicJSFragment( - parameters: ["caseId", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let caseId = arguments[0] - let targetVar = arguments[1] - let base = fullName.components(separatedBy: ".").last ?? fullName printer.write( - "let \(targetVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseId), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" + "bjs[\"\(funcName)\"](\(isSomeVar) ? 1 : 0, \(isSomeVar) ? \(coerced) : \(wasmType.jsZeroLiteral));" ) return [] } ) - case .optional(let wrappedType): - return try closureOptionalLiftParameter(wrappedType: wrappedType) - default: - throw BridgeJSLinkError(message: "Unsupported closure parameter type for lifting: \(type)") } - } - /// Handles optional parameter lifting for closure invocation - private static func closureOptionalLiftParameter(wrappedType: BridgeType) throws -> IntrinsicJSFragment { - switch wrappedType { - case .string, .rawValueEnum, .int, .bool, .double, .float, .jsObject, .swiftHeapObject, .caseEnum, - .associatedValueEnum: - break - default: - throw BridgeJSLinkError( - message: "Unsupported optional wrapped type in closure parameter lifting: \(wrappedType)" - ) + if case .sideChannelReturn(let mode) = wrappedType.optionalConvention { + if mode == .none { + throw BridgeJSLinkError( + message: "Unsupported wrapped type for returning from JS function: \(wrappedType)" + ) + } + return optionalLowerReturnToSideChannel(mode: mode, kind: kind) } - return IntrinsicJSFragment( - parameters: ["isSome", "value", "targetVar"], - printCode: { arguments, scope, printer, cleanupCode in - let isSome = arguments[0] - let value = arguments[1] - let targetVar = arguments[2] - - printer.write("let \(targetVar);") - printer.write("if (\(isSome)) {") - printer.indent() - switch wrappedType { - case .string, .rawValueEnum(_, .string): - let objectLabel = scope.variable("\(targetVar)Object") - printer.write( - "const \(objectLabel) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(value));" - ) - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(value));") - printer.write("\(targetVar) = String(\(objectLabel));") - case .int, .uint: - printer.write("\(targetVar) = \(value) | 0;") - case .bool: - printer.write("\(targetVar) = \(value) !== 0;") - case .double: - printer.write("\(targetVar) = \(value);") - case .float: - printer.write("\(targetVar) = Math.fround(\(value));") - case .jsObject: - printer.write("\(targetVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(value));") - printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(value));") - case .swiftHeapObject(let typeName): - printer.write("\(targetVar) = _exports['\(typeName)'].__construct(\(value));") - case .caseEnum: - printer.write("\(targetVar) = \(value);") - case .rawValueEnum(_, let rawType): - switch rawType { - case .bool: - printer.write("\(targetVar) = \(value) !== 0;") - default: - printer.write("\(targetVar) = \(value);") - } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - printer.write( - "\(targetVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(value), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" - ) - default: - fatalError("Unsupported optional wrapped type in closure parameter lifting: \(wrappedType)") - } - printer.unindent() - printer.write("} else {") - printer.indent() - printer.write("\(targetVar) = null;") - printer.unindent() - printer.write("}") + if wrappedType.nilSentinel.hasSentinel { + let innerFragment = try lowerReturn(type: wrappedType, context: .exportSwift) + return sentinelOptionalLowerReturn( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment + ) + } - return [] - } + let innerFragment = try lowerReturn(type: wrappedType, context: .exportSwift) + return optionalLowerReturnWithPresenceFlag( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment ) } - /// Lowers a JS return value to WASM for returning from callback (invoke_js_callback_*) - static func closureLowerReturn(type: BridgeType) throws -> IntrinsicJSFragment { - switch type { - case .void: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { _, _, printer, _ in - printer.write("return;") - return [] - } - ) - case .int, .caseEnum: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]) | 0;") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return Math.fround(\(arguments[0]));") - return [] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]);") - return [] - } - ) - case .string: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = stringLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - case .jsObject: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = jsObjectLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - case .swiftHeapObject: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = swiftHeapObjectLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = stringLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLowerReturn - let lowered = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lowered[0]);") - return [] - } - ) - default: - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]) | 0;") - return [] - } - ) - } - case .associatedValueEnum(let fullName): - return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let result = arguments[0] - let base = fullName.components(separatedBy: ".").last ?? fullName - let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("cleanup") - printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(result));" - ) - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - printer.write("return \(caseIdVar);") - return [] - } - ) - case .optional(let wrappedType): - return try closureOptionalLowerReturn(wrappedType: wrappedType) - default: - throw BridgeJSLinkError(message: "Unsupported closure return type for lowering: \(type)") - } - } + private static func sentinelOptionalLowerReturn( + wrappedType: BridgeType, + kind: JSOptionalKind, + innerFragment: IntrinsicJSFragment + ) -> IntrinsicJSFragment { + let sentinelLiteral = wrappedType.nilSentinel.jsLiteral - /// Handles optional return lowering for closure invocation - private static func closureOptionalLowerReturn(wrappedType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( - parameters: ["result"], - printCode: { arguments, scope, printer, cleanupCode in - let result = arguments[0] - - switch wrappedType { - case .swiftHeapObject: - printer.write("return \(result) ? \(result).pointer : 0;") - case .string: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = \(result);") - printer.write("return;") - case .int, .uint: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = \(result);") - printer.write("return;") - case .bool: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalBool) = \(result);") - printer.write("return;") - case .float: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalFloat) = \(result);") - printer.write("return;") - case .double: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalDouble) = \(result);") - printer.write("return;") - case .caseEnum: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = \(result);") - printer.write("return;") - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = \(result);") - printer.write("return;") - case .bool: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalBool) = \(result);") - printer.write("return;") - case .float: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalFloat) = \(result);") - printer.write("return;") - case .double: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalDouble) = \(result);") - printer.write("return;") - default: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = \(result);") - printer.write("return;") + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr);") + + let bufferPrinter = CodeFragmentPrinter() + let innerResults = try innerFragment.printCode( + [value], + context.with(\.printer, bufferPrinter) + ) + + let hasSideEffects = !bufferPrinter.lines.isEmpty + let innerExpr = innerResults.first + + if hasSideEffects { + printer.write("if (\(isSomeVar)) {") + printer.indent { + for line in bufferPrinter.lines { + printer.write(line) + } + if let expr = innerExpr { + printer.write("return \(expr);") + } } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("cleanup") - printer.write("if (\(result)) {") - printer.indent() - printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(result));" - ) - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = \(caseIdVar);") - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - printer.unindent() printer.write("} else {") - printer.indent() - printer.write("\(JSGlueVariableScope.reservedStorageToReturnOptionalInt) = null;") - printer.unindent() + printer.indent { + printer.write("return \(sentinelLiteral);") + } printer.write("}") - printer.write("return;") - default: - fatalError("Unsupported optional wrapped type in closure return lowering: \(wrappedType)") + } else if let expr = innerExpr { + printer.write("return \(isSomeVar) ? \(expr) : \(sentinelLiteral);") } return [] @@ -1186,185 +1120,126 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Lifts a WASM return value to JS from Swift closure (lower_closure_*) - static func closureLiftReturn(type: BridgeType) throws -> IntrinsicJSFragment { - switch type { - case .void: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("\(arguments[0]);") - printer.write("return;") - return [] - } - ) - case .int, .caseEnum: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]) | 0;") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLiftReturn - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lifted[0]);") - return [] - } - ) - case .float, .double: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]);") - return [] - } - ) - case .string: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("const resultLen = \(arguments[0]);") - let baseFragment = stringLiftReturn - let lifted = baseFragment.printCode([], scope, printer, cleanupCode) - printer.write("return \(lifted[0]);") - return [] - } - ) - case .jsObject: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("const resultId = \(arguments[0]);") - let baseFragment = jsObjectLiftReturn - let lifted = baseFragment.printCode(["resultId"], scope, printer, cleanupCode) - printer.write("return \(lifted[0]);") - return [] - } - ) - case .swiftHeapObject(let className): - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("const resultPtr = \(arguments[0]);") - printer.write("return _exports['\(className)'].__construct(resultPtr);") - return [] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("const resultLen = \(arguments[0]);") - let baseFragment = stringLiftReturn - let lifted = baseFragment.printCode([], scope, printer, cleanupCode) - printer.write("return \(lifted[0]);") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - let baseFragment = boolLiftReturn - let lifted = baseFragment.printCode([arguments[0]], scope, printer, cleanupCode) - printer.write("return \(lifted[0]);") - return [] - } - ) - default: - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("return \(arguments[0]) | 0;") - return [] - } - ) - } - case .associatedValueEnum(let fullName): + // MARK: - Protocol Support + + static func protocolPropertyOptionalToSideChannel(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + if let scalarKind = wrappedType.optionalScalarKind { + let storage = scalarKind.storageName return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - printer.write("\(arguments[0]);") - let base = fullName.components(separatedBy: ".").last ?? fullName - let resultVar = scope.variable("result") - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetTag), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" - ) - printer.write("return \(resultVar);") + parameters: ["value"], + printCode: { arguments, context in + context.printer.write("\(storage) = \(arguments[0]);") return [] } ) - case .optional(let wrappedType): - return try closureOptionalLiftReturn(wrappedType: wrappedType) - default: - throw BridgeJSLinkError(message: "Unsupported closure return type for lifting: \(type)") } - } - /// Handles optional return lifting for Swift closure returns - private static func closureOptionalLiftReturn(wrappedType: BridgeType) throws -> IntrinsicJSFragment { - return IntrinsicJSFragment( - parameters: ["invokeCall"], - printCode: { arguments, scope, printer, cleanupCode in - let invokeCall = arguments[0] - printer.write("\(invokeCall);") - let baseFragment = optionalLiftReturn(wrappedType: wrappedType, context: .importTS) - let lifted = baseFragment.printCode([], scope, printer, cleanupCode) - if !lifted.isEmpty { - printer.write("return \(lifted[0]);") + if case .sideChannelReturn(let mode) = wrappedType.optionalConvention, + mode != .none + { + return IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let printer = context.printer + let value = arguments[0] + + printer.write("\(JSGlueVariableScope.reservedStorageToReturnString) = \(value);") + + return [] } - return [] - } + ) + } + + throw BridgeJSLinkError( + message: "Type \(wrappedType) does not use side channel for protocol property returns" ) } - /// Provides appropriate default values for error cases in closure invocation - static func closureErrorReturn(type: BridgeType) -> IntrinsicJSFragment { - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanupCode in - switch type { - case .void: - printer.write("return;") - case .string: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnBytes) = new Uint8Array(0);") - printer.write("return 0;") - case .int, .bool, .caseEnum: - printer.write("return 0;") - case .float, .double: - printer.write("return 0.0;") - case .jsObject, .swiftHeapObject: - printer.write("return 0;") - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - printer.write("\(JSGlueVariableScope.reservedStorageToReturnBytes) = new Uint8Array(0);") - printer.write("return 0;") - case .bool, .int, .int32, .int64, .uint, .uint32, .uint64: - printer.write("return 0;") - case .float, .double: - printer.write("return 0.0;") - } - case .associatedValueEnum: - printer.write("return;") - case .optional(let wrappedType): - switch wrappedType { - case .swiftHeapObject: - printer.write("return 0;") - default: - printer.write("return;") + // MARK: - JS Glue Descriptor Helpers + + private static func popExpression(for wasmType: WasmCoreType, scope: JSGlueVariableScope) -> String { + switch wasmType { + case .i32: return scope.popI32() + case .f32: return scope.popF32() + case .f64: return scope.popF64() + case .pointer: return scope.popPointer() + case .i64: return scope.popI32() + } + } + + private static func emitPush( + for wasmType: WasmCoreType, + value: String, + scope: JSGlueVariableScope, + printer: CodeFragmentPrinter + ) { + switch wasmType { + case .i32: scope.emitPushI32Parameter(value, printer: printer) + case .f32: scope.emitPushF32Parameter(value, printer: printer) + case .f64: scope.emitPushF64Parameter(value, printer: printer) + case .pointer: scope.emitPushPointerParameter(value, printer: printer) + case .i64: scope.emitPushI32Parameter(value, printer: printer) + } + } + + @discardableResult + private static func emitOptionalPlaceholders( + for wrappedType: BridgeType, + scope: JSGlueVariableScope, + printer: CodeFragmentPrinter + ) -> Bool { + let params = wrappedType.wasmParams + if params.isEmpty { + return false + } + for param in params { + emitPush(for: param.type, value: param.type.jsZeroLiteral, scope: scope, printer: printer) + } + return true + } + + private static func stackOptionalLower( + wrappedType: BridgeType, + kind: JSOptionalKind, + innerFragment: IntrinsicJSFragment + ) -> IntrinsicJSFragment { + IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + printer.write("const \(isSomeVar) = \(kind.presenceCheck(value: value));") + + let ifBodyPrinter = CodeFragmentPrinter() + try ifBodyPrinter.indent { + let _ = try innerFragment.printCode( + [value], + context.with(\.printer, ifBodyPrinter) + ) + } + printer.write("if (\(isSomeVar)) {") + for line in ifBodyPrinter.lines { + printer.write(line) + } + let placeholderPrinter = CodeFragmentPrinter() + let hasPlaceholders = emitOptionalPlaceholders( + for: wrappedType, + scope: scope, + printer: placeholderPrinter + ) + if hasPlaceholders { + printer.write("} else {") + printer.indent { + for line in placeholderPrinter.lines { + printer.write(line) + } } - default: - printer.write("return 0;") + printer.write("}") + } else { + printer.write("}") } - + scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) return [] } ) @@ -1375,21 +1250,19 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lowers a JS value to Wasm core values for parameters static func lowerParameter(type: BridgeType) throws -> IntrinsicJSFragment { switch type { - case .int, .uint, .float, .double, .bool, .unsafePointer: return .identity + case .bool, .int, .uint, .float, .double, .unsafePointer, .caseEnum: + return .identity + case .rawValueEnum(_, let rawType) where rawType != .string: + return .identity case .string: return .stringLowerParameter case .jsObject: return .jsObjectLowerParameter - case .swiftHeapObject: - return .swiftHeapObjectLowerParameter + case .jsValue: return .jsValueLower + case .swiftHeapObject: return .swiftHeapObjectLowerParameter case .swiftProtocol: return .jsObjectLowerParameter case .void: return .void - case .optional(let wrappedType): - return try .optionalLowerParameter(wrappedType: wrappedType) - case .caseEnum: return .identity - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: return .stringLowerParameter - default: return .identity - } + case .nullable(let wrappedType, let kind): + return try .optionalLowerParameter(wrappedType: wrappedType, kind: kind) + case .rawValueEnum(_, .string): return .stringLowerParameter case .associatedValueEnum(let fullName): let base = fullName.components(separatedBy: ".").last ?? fullName return .associatedEnumLowerParameter(enumBase: base) @@ -1399,7 +1272,8 @@ struct IntrinsicJSFragment: Sendable { case .closure: return IntrinsicJSFragment( parameters: ["closure"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let closure = arguments[0] let callbackIdVar = scope.variable("callbackId") printer.write( @@ -1412,43 +1286,45 @@ struct IntrinsicJSFragment: Sendable { throw BridgeJSLinkError(message: "Namespace enums are not supported to be passed as parameters: \(string)") case .array(let elementType): return try arrayLower(elementType: elementType) + case .dictionary(let valueType): + return try dictionaryLower(valueType: valueType) + default: + throw BridgeJSLinkError(message: "Unhandled type in lowerParameter: \(type)") } } /// Returns a fragment that lifts a Wasm core value to a JS value for return values static func liftReturn(type: BridgeType) throws -> IntrinsicJSFragment { switch type { - case .int, .float, .double: return .identity - case .uint: return .uintLiftReturn - case .bool: return .boolLiftReturn + case .bool, .rawValueEnum(_, .bool): + return .boolLiftReturn + case .uint: + return .uintLiftReturn + case .int, .float, .double, .unsafePointer, .caseEnum: + return .identity + case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: + return .identity case .string: return .stringLiftReturn case .jsObject: return .jsObjectLiftReturn + case .jsValue: return .jsValueLift case .swiftHeapObject(let name): return .swiftHeapObjectLiftReturn(name) - case .unsafePointer: return .identity case .swiftProtocol: return .jsObjectLiftReturn case .void: return .void - case .optional(let wrappedType): return .optionalLiftReturn(wrappedType: wrappedType) - case .caseEnum: return .identity - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: return .stringLiftReturn - case .bool: return .boolLiftReturn - default: return .identity - } + case .nullable(let wrappedType, let kind): + return .optionalLiftReturn(wrappedType: wrappedType, kind: kind) + case .rawValueEnum(_, .string): return .stringLiftReturn case .associatedValueEnum(let fullName): let base = fullName.components(separatedBy: ".").last ?? fullName return .associatedEnumLiftReturn(enumBase: base) case .swiftStruct(let fullName): let base = fullName.components(separatedBy: ".").last ?? fullName return swiftStructLiftReturn(structBase: base) - case .closure(let signature): - let lowerFuncName = "lower_closure_\(signature.moduleName)_\(signature.mangleName)" + case .closure: return IntrinsicJSFragment( - parameters: ["boxPtr"], - printCode: { arguments, scope, printer, cleanupCode in - let boxPtr = arguments[0] - printer.write("return bjs[\"\(lowerFuncName)\"](\(boxPtr));") - return [] + parameters: ["funcRef"], + printCode: { arguments, context in + let funcRef = arguments[0] + return ["\(JSGlueVariableScope.reservedSwift).memory.getObject(\(funcRef))"] } ) case .namespaceEnum(let string): @@ -1457,6 +1333,10 @@ struct IntrinsicJSFragment: Sendable { ) case .array(let elementType): return try arrayLift(elementType: elementType) + case .dictionary(let valueType): + return try dictionaryLift(valueType: valueType) + default: + throw BridgeJSLinkError(message: "Unhandled type in liftReturn: \(type)") } } @@ -1465,42 +1345,27 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lifts Wasm core values to JS values for parameters static func liftParameter(type: BridgeType, context: BridgeContext = .importTS) throws -> IntrinsicJSFragment { switch type { - case .int, .float, .double: return .identity - case .uint: return .uintLiftParameter - case .bool: return .boolLiftParameter + case .bool, .rawValueEnum(_, .bool): + return .boolLiftParameter + case .uint: + return .uintLiftParameter + case .int, .float, .double, .unsafePointer, .caseEnum: + return .identity + case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: + return .identity case .string: return .stringLiftParameter case .jsObject: return .jsObjectLiftParameter - case .unsafePointer: return .identity + case .jsValue: return .jsValueLiftParameter case .swiftHeapObject(let name): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "swiftHeapObject '\(name)' can only be used in protocol exports, not in \(context)" - ) - case .exportSwift: - return .swiftHeapObjectLiftParameter(name) - } + return .swiftHeapObjectLiftParameter(name) case .swiftProtocol: return .jsObjectLiftParameter case .void: throw BridgeJSLinkError( message: "Void can't appear in parameters of imported JS functions" ) - case .optional(let wrappedType): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "Optional types are not supported for imported JS functions: \(wrappedType)" - ) - case .exportSwift: - return try .optionalLiftParameter(wrappedType: wrappedType) - } - case .caseEnum: return .identity - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: return .stringLiftParameter - case .bool: return .boolLiftParameter - default: return .identity - } + case .nullable(let wrappedType, let kind): + return try .optionalLiftParameter(wrappedType: wrappedType, kind: kind, context: context) + case .rawValueEnum(_, .string): return .stringLiftParameter case .associatedValueEnum(let fullName): switch context { case .importTS: @@ -1512,11 +1377,12 @@ struct IntrinsicJSFragment: Sendable { let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["caseId"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let caseId = arguments[0] let resultVar = scope.variable("enumValue") printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseId), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" + "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseId));" ) return [resultVar] } @@ -1530,21 +1396,22 @@ struct IntrinsicJSFragment: Sendable { let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("structValue") printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" + "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift();" ) return [resultVar] } ) } - case .closure(let signature): - let lowerFuncName = "lower_closure_\(signature.moduleName)_\(signature.mangleName)" + case .closure: return IntrinsicJSFragment( - parameters: ["boxPtr"], - printCode: { arguments, scope, printer, cleanupCode in - return ["bjs[\"\(lowerFuncName)\"](\(arguments[0]))"] + parameters: ["funcRef"], + printCode: { arguments, context in + let funcRef = arguments[0] + return ["\(JSGlueVariableScope.reservedSwift).memory.getObject(\(funcRef))"] } ) case .namespaceEnum(let string): @@ -1553,52 +1420,32 @@ struct IntrinsicJSFragment: Sendable { "Namespace enums are not supported to be passed as parameters to imported JS functions: \(string)" ) case .array(let elementType): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "Arrays are not yet supported to be passed as parameters to imported JS functions" - ) - case .exportSwift: - return try arrayLift(elementType: elementType) - } + return try arrayLift(elementType: elementType) + case .dictionary(let valueType): + return try dictionaryLift(valueType: valueType) + default: + throw BridgeJSLinkError(message: "Unhandled type in liftParameter: \(type)") } } /// Returns a fragment that lowers a JS value to Wasm core values for return values static func lowerReturn(type: BridgeType, context: BridgeContext = .importTS) throws -> IntrinsicJSFragment { switch type { - case .int, .uint, .float, .double: return .identity - case .bool: return .boolLowerReturn + case .bool, .rawValueEnum(_, .bool): + return .boolLowerReturn + case .int, .uint, .float, .double, .unsafePointer, .caseEnum: + return .identity + case .rawValueEnum(_, let rawType) where rawType != .string && rawType != .bool: + return .identity case .string: return .stringLowerReturn case .jsObject: return .jsObjectLowerReturn - case .unsafePointer: return .identity - case .swiftHeapObject(let name): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "swiftHeapObject '\(name)' can only be used in protocol exports, not in \(context)" - ) - case .exportSwift: - return .swiftHeapObjectLowerReturn - } + case .jsValue: return .jsValueLowerReturn(context: context) + case .swiftHeapObject: return .swiftHeapObjectLowerReturn case .swiftProtocol: return .jsObjectLowerReturn case .void: return .void - case .optional(let wrappedType): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "Optional types are not supported for imported JS functions: \(wrappedType)" - ) - case .exportSwift: - return try .optionalLowerReturn(wrappedType: wrappedType) - } - case .caseEnum: return .identity - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: return .stringLowerReturn - case .bool: return .boolLowerReturn - default: return .identity - } + case .nullable(let wrappedType, let kind): + return try .optionalLowerReturn(wrappedType: wrappedType, kind: kind) + case .rawValueEnum(_, .string): return .stringLowerReturn case .associatedValueEnum(let fullName): switch context { case .importTS: @@ -1612,7 +1459,6 @@ struct IntrinsicJSFragment: Sendable { case .swiftStruct(let fullName): switch context { case .importTS: - // ImportTS expects Swift structs to come back as a retained JS object ID. return .jsObjectLowerReturn case .exportSwift: return swiftStructLowerReturn(fullName: fullName) @@ -1620,7 +1466,8 @@ struct IntrinsicJSFragment: Sendable { case .closure: return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let printer = context.printer let value = arguments[0] printer.write("if (typeof \(value) !== \"function\") {") printer.indent { @@ -1635,14 +1482,11 @@ struct IntrinsicJSFragment: Sendable { message: "Namespace enums are not supported to be returned from imported JS functions: \(string)" ) case .array(let elementType): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: "Arrays are not yet supported to be returned from imported JS functions" - ) - case .exportSwift: - return try arrayLower(elementType: elementType) - } + return try arrayLower(elementType: elementType) + case .dictionary(let valueType): + return try dictionaryLower(valueType: valueType) + default: + throw BridgeJSLinkError(message: "Unhandled type in lowerReturn: \(type)") } } @@ -1652,27 +1496,28 @@ struct IntrinsicJSFragment: Sendable { let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("cleanup") printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" + "const \(caseIdVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" ) - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") printer.write("return \(caseIdVar);") return [] } ) } /// Fragment for generating an entire associated value enum helper - static func associatedValueEnumHelper(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { + /// Generates the enum tag constants (e.g. `const XValues = { Tag: { ... } }`) + /// This is placed at module level for exports/imports. + static func associatedValueEnumValues(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["enumName"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let printer = context.printer let enumName = arguments[0] - // Generate the enum tag object printer.write("const \(enumName) = {") printer.indent { printer.write("Tag: {") @@ -1685,109 +1530,97 @@ struct IntrinsicJSFragment: Sendable { printer.write("},") } printer.write("};") - printer.nextLine() - // Generate the helper function - printer.write("const __bjs_create\(enumName)Helpers = () => {") - printer.indent() - printer.write( - "return (\(JSGlueVariableScope.reservedTmpParamInts), \(JSGlueVariableScope.reservedTmpParamF32s), \(JSGlueVariableScope.reservedTmpParamF64s), textEncoder, \(JSGlueVariableScope.reservedSwift)) => ({" - ) - printer.indent() + return [] + } + ) + } - // Generate lower function - printer.write("lower: (value) => {") - printer.indent { - printer.write("const enumTag = value.tag;") - printer.write("switch (enumTag) {") - printer.indent { - let lowerPrinter = CodeFragmentPrinter() - for enumCase in enumDefinition.cases { - let caseName = enumCase.name.capitalizedFirstLetter - let caseScope = JSGlueVariableScope() - let caseCleanup = CodeFragmentPrinter() - caseCleanup.indent() - let fragment = IntrinsicJSFragment.associatedValuePushPayload(enumCase: enumCase) - _ = fragment.printCode(["value", enumName, caseName], caseScope, lowerPrinter, caseCleanup) - } + /// Generates the enum helper factory function (lower/lift closures). + /// This is placed inside `createInstantiator` alongside struct helpers, + /// so it has access to `_exports` for class references. + static func associatedValueEnumHelperFactory(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { + return IntrinsicJSFragment( + parameters: ["enumName"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let enumName = arguments[0] - for line in lowerPrinter.lines { - printer.write(line) - } + printer.write("const __bjs_create\(enumName)Helpers = () => ({") + try printer.indent { + printer.write("lower: (value) => {") + try printer.indent { + printer.write("const enumTag = value.tag;") + printer.write("switch (enumTag) {") + try printer.indent { + let lowerPrinter = CodeFragmentPrinter() + for enumCase in enumDefinition.cases { + let caseName = enumCase.name.capitalizedFirstLetter + let caseScope = scope.makeChildScope() + let fragment = IntrinsicJSFragment.associatedValuePushPayload( + enumCase: enumCase + ) + _ = try fragment.printCode( + ["value", enumName, caseName], + context.with(\.scope, caseScope).with(\.printer, lowerPrinter) + ) + } + + for line in lowerPrinter.lines { + printer.write(line) + } - printer.write("default: throw new Error(\"Unknown \(enumName) tag: \" + String(enumTag));") + printer.write( + "default: throw new Error(\"Unknown \(enumName) tag: \" + String(enumTag));" + ) + } + printer.write("}") } - printer.write("}") - } - printer.write("},") + printer.write("},") - // Generate lift function - printer.write( - "lift: (\(JSGlueVariableScope.reservedTmpRetTag), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s)) => {" - ) - printer.indent { - printer.write("const tag = tmpRetTag | 0;") - printer.write("switch (tag) {") - printer.indent { - let liftPrinter = CodeFragmentPrinter() - for enumCase in enumDefinition.cases { - let caseName = enumCase.name.capitalizedFirstLetter - let caseScope = JSGlueVariableScope() - let caseCleanup = CodeFragmentPrinter() + printer.write("lift: (tag) => {") + try printer.indent { + printer.write("tag = tag | 0;") + printer.write("switch (tag) {") + try printer.indent { + let liftPrinter = CodeFragmentPrinter() + for enumCase in enumDefinition.cases { + let caseName = enumCase.name.capitalizedFirstLetter + let caseScope = scope.makeChildScope() + + let fragment = IntrinsicJSFragment.associatedValuePopPayload( + enumCase: enumCase + ) + _ = try fragment.printCode( + [enumName, caseName], + context.with(\.scope, caseScope).with(\.printer, liftPrinter) + ) + } - let fragment = IntrinsicJSFragment.associatedValuePopPayload(enumCase: enumCase) - _ = fragment.printCode([enumName, caseName], caseScope, liftPrinter, caseCleanup) - } + for line in liftPrinter.lines { + printer.write(line) + } - for line in liftPrinter.lines { - printer.write(line) + printer.write( + "default: throw new Error(\"Unknown \(enumName) tag returned from Swift: \" + String(tag));" + ) } - - printer.write( - "default: throw new Error(\"Unknown \(enumName) tag returned from Swift: \" + String(tag));" - ) + printer.write("}") } printer.write("}") } - printer.write("}") - printer.unindent() printer.write("});") - printer.unindent() - printer.write("};") - - return [] - } - ) - } - - static func simpleEnumHelper(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { - return IntrinsicJSFragment( - parameters: ["enumName"], - printCode: { arguments, scope, printer, cleanup in - let enumName = arguments[0] - printer.write("const \(enumName) = {") - printer.indent { - for (index, enumCase) in enumDefinition.cases.enumerated() { - let caseName = enumCase.name.capitalizedFirstLetter - let value = enumCase.jsValue( - rawType: enumDefinition.rawType, - index: index - ) - printer.write("\(caseName): \(value),") - } - } - printer.write("};") - printer.nextLine() return [] } ) } - static func rawValueEnumHelper(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { + static func caseEnumHelper(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["enumName"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let printer = context.printer let enumName = arguments[0] printer.write("const \(enumName) = {") printer.indent { @@ -1811,35 +1644,29 @@ struct IntrinsicJSFragment: Sendable { private static func associatedValuePushPayload(enumCase: EnumCase) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["value", "enumName", "caseName"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let printer = context.printer let enumName = arguments[1] let caseName = arguments[2] printer.write("case \(enumName).Tag.\(caseName): {") - printer.indent { + try printer.indent { if enumCase.associatedValues.isEmpty { - printer.write("const cleanup = undefined;") - printer.write("return { caseId: \(enumName).Tag.\(caseName), cleanup };") + printer.write("return \(enumName).Tag.\(caseName);") } else { - // Process associated values in reverse order (to match the order they'll be popped) let reversedValues = enumCase.associatedValues.enumerated().reversed() for (associatedValueIndex, associatedValue) in reversedValues { let prop = associatedValue.label ?? "param\(associatedValueIndex)" - let fragment = IntrinsicJSFragment.associatedValuePushPayload(type: associatedValue.type) + let fragment = try IntrinsicJSFragment.associatedValuePushPayload( + type: associatedValue.type + ) - _ = fragment.printCode(["value.\(prop)"], scope, printer, cleanup) + _ = try fragment.printCode(["value.\(prop)"], context) } - if cleanup.lines.isEmpty { - printer.write("const cleanup = undefined;") - } else { - printer.write("const cleanup = () => {") - printer.write(contentsOf: cleanup) - printer.write("};") - } - printer.write("return { caseId: \(enumName).Tag.\(caseName), cleanup };") + printer.write("return \(enumName).Tag.\(caseName);") } } @@ -1853,7 +1680,8 @@ struct IntrinsicJSFragment: Sendable { private static func associatedValuePopPayload(enumCase: EnumCase) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["enumName", "caseName"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let printer = context.printer let enumName = arguments[0] let caseName = arguments[1] @@ -1866,9 +1694,9 @@ struct IntrinsicJSFragment: Sendable { // Process associated values in reverse order (to match the order they'll be popped) for (associatedValueIndex, associatedValue) in enumCase.associatedValues.enumerated().reversed() { let prop = associatedValue.label ?? "param\(associatedValueIndex)" - let fragment = IntrinsicJSFragment.associatedValuePopPayload(type: associatedValue.type) + let fragment = try IntrinsicJSFragment.associatedValuePopPayload(type: associatedValue.type) - let result = fragment.printCode([], scope, casePrinter, cleanup) + let result = try fragment.printCode([], context.with(\.printer, casePrinter)) let varName = result.first ?? "value_\(associatedValueIndex)" fieldPairs.append("\(prop): \(varName)") @@ -1877,263 +1705,156 @@ struct IntrinsicJSFragment: Sendable { printer.write("case \(enumName).Tag.\(caseName): {") printer.indent { for line in casePrinter.lines { - printer.write(line) - } - printer.write( - "return { tag: \(enumName).Tag.\(caseName), \(fieldPairs.reversed().joined(separator: ", ")) };" - ) - } - printer.write("}") - } - - return [] - } - ) - } - - private static func associatedValuePushPayload(type: BridgeType) -> IntrinsicJSFragment { - switch type { - case .string: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let bytesVar = scope.variable("bytes") - let idVar = scope.variable("id") - printer.write("const \(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(arguments[0]) ? 1 : 0);") - return [] - } - ) - case .int, .uint: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") - return [] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(Math.fround(\(arguments[0])));") - return [] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(\(arguments[0]));") - return [] - } - ) - case .optional(let wrappedType): - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(value) != null;") - - switch wrappedType { - case .string: - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let bytesVar = scope.variable("bytes") - printer.write( - "let \(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));" - ) - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write("if(\(idVar)) {") - cleanup.indent { - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - } - cleanup.write("}") - case .int, .uint: - printer.write( - "\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? (\(value) | 0) : 0);" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - case .bool: - printer.write( - "\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? (\(value) ? 1 : 0) : 0);" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - case .float: - printer.write( - "\(JSGlueVariableScope.reservedTmpParamF32s).push(\(isSomeVar) ? Math.fround(\(value)) : 0.0);" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - case .double: + printer.write(line) + } printer.write( - "\(JSGlueVariableScope.reservedTmpParamF64s).push(\(isSomeVar) ? \(value) : 0.0);" + "return { tag: \(enumName).Tag.\(caseName), \(fieldPairs.reversed().joined(separator: ", ")) };" ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - default: - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") } - - return [] + printer.write("}") } - ) + + return [] + } + ) + } + + private static func associatedValuePushPayload(type: BridgeType) throws -> IntrinsicJSFragment { + switch type { + case .nullable(let wrappedType, let kind): + return try associatedValueOptionalPushPayload(wrappedType: wrappedType, kind: kind) default: + return try stackLowerFragment(elementType: type) + } + } + + private static func associatedValueOptionalPushPayload( + wrappedType: BridgeType, + kind: JSOptionalKind + ) throws -> IntrinsicJSFragment { + if wrappedType.isSingleParamScalar { + let wasmType = wrappedType.wasmParams[0].type + let stackCoerce = wrappedType.stackLowerCoerce return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + printer.write("const \(isSomeVar) = \(kind.presenceCheck(value: value));") + var coerced: String + if let coerce = stackCoerce { + coerced = coerce.replacingOccurrences(of: "$0", with: value) + if coerced.contains("?") && !coerced.hasPrefix("(") { + coerced = "(\(coerced))" + } + } else { + coerced = value + } + emitPush( + for: wasmType, + value: "\(isSomeVar) ? \(coerced) : \(wasmType.jsZeroLiteral)", + scope: scope, + printer: printer + ) + scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) return [] } ) } + + let innerFragment = try stackLowerFragment(elementType: wrappedType) + return stackOptionalLower( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment + ) } - private static func associatedValuePopPayload(type: BridgeType) -> IntrinsicJSFragment { + private static func associatedValuePopPayload(type: BridgeType) throws -> IntrinsicJSFragment { switch type { - case .string: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let strVar = scope.variable("string") - printer.write("const \(strVar) = \(JSGlueVariableScope.reservedTmpRetStrings).pop();") - return [strVar] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let bVar = scope.variable("bool") - printer.write("const \(bVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [bVar] - } - ) - case .int, .uint: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let iVar = scope.variable("int") - printer.write("const \(iVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [iVar] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let fVar = scope.variable("f32") - printer.write("const \(fVar) = \(JSGlueVariableScope.reservedTmpRetF32s).pop();") - return [fVar] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let dVar = scope.variable("f64") - printer.write("const \(dVar) = \(JSGlueVariableScope.reservedTmpRetF64s).pop();") - return [dVar] - } - ) - case .optional(let wrappedType): - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let optVar = scope.variable("optional") - let isSomeVar = scope.variable("isSome") + case .nullable(let wrappedType, let kind): + return associatedValueOptionalPopPayload(wrappedType: wrappedType, kind: kind) + default: + return try stackLiftFragment(elementType: type) + } + } - printer.write("const \(isSomeVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - printer.write("let \(optVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let wrappedFragment = associatedValuePopPayload(type: wrappedType) - let wrappedResults = wrappedFragment.printCode([], scope, printer, cleanup) + private static func associatedValueOptionalPopPayload( + wrappedType: BridgeType, + kind: JSOptionalKind + ) -> IntrinsicJSFragment { + return IntrinsicJSFragment( + parameters: [], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let optVar = scope.variable("optional") + let isSomeVar = scope.variable("isSome") + + printer.write("const \(isSomeVar) = \(scope.popI32());") + printer.write("let \(optVar);") + printer.write("if (\(isSomeVar)) {") + try printer.indent { + // For optional associated value enums, Swift uses bridgeJSLowerParameter() + // which pushes caseId to i32Stack (same as bridgeJSLowerReturn()). + if case .associatedValueEnum(let fullName) = wrappedType { + let base = fullName.components(separatedBy: ".").last ?? fullName + let caseIdVar = scope.variable("caseId") + printer.write("const \(caseIdVar) = \(scope.popI32());") + printer.write( + "\(optVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar));" + ) + } else { + let wrappedFragment = try associatedValuePopPayload(type: wrappedType) + let wrappedResults = try wrappedFragment.printCode([], context) if let wrappedResult = wrappedResults.first { printer.write("\(optVar) = \(wrappedResult);") } else { printer.write("\(optVar) = undefined;") } } - printer.write("} else {") - printer.indent { - printer.write("\(optVar) = null;") - } - printer.write("}") - - return [optVar] } - ) - default: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - return ["undefined"] + printer.write("} else {") + printer.indent { + printer.write("\(optVar) = \(kind.absenceLiteral);") } - ) - } - } + printer.write("}") - static func swiftStructLowerReturn(fullName: String) -> IntrinsicJSFragment { - let base = fullName.components(separatedBy: ".").last ?? fullName - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in - let value = arguments[0] - let cleanupVar = scope.variable("cleanup") - printer.write( - "const { cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedStructHelpers).\(base).lower(\(value));" - ) - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - return [] + return [optVar] } ) } - static func swiftStructLowerParameter(structBase: String) -> IntrinsicJSFragment { - return IntrinsicJSFragment( + private static func swiftStructLower(structBase: String) -> IntrinsicJSFragment { + IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let printer = context.printer let value = arguments[0] - let cleanupVar = scope.variable("cleanup") printer.write( - "const { cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lower(\(value));" + "\(JSGlueVariableScope.reservedStructHelpers).\(structBase).lower(\(value));" ) - cleanupCode.write("if (\(cleanupVar)) { \(cleanupVar)(); }") return [] } ) } + static func swiftStructLowerReturn(fullName: String) -> IntrinsicJSFragment { + swiftStructLower(structBase: fullName.components(separatedBy: ".").last ?? fullName) + } + + static func swiftStructLowerParameter(structBase: String) -> IntrinsicJSFragment { + swiftStructLower(structBase: structBase) + } + static func swiftStructLiftReturn(structBase: String) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("structValue") printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" + "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lift();" ) return [resultVar] } @@ -2146,30 +1867,57 @@ struct IntrinsicJSFragment: Sendable { static func arrayLower(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["arr"], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let arr = arguments[0] - let cleanupArrayVar = scope.variable("arrayCleanups") - printer.write("const \(cleanupArrayVar) = [];") let elemVar = scope.variable("elem") printer.write("for (const \(elemVar) of \(arr)) {") - printer.indent { - let elementFragment = try! arrayElementLowerFragment(elementType: elementType) - let elementCleanup = CodeFragmentPrinter() - let _ = elementFragment.printCode([elemVar], scope, printer, elementCleanup) - if !elementCleanup.lines.isEmpty { - printer.write("\(cleanupArrayVar).push(() => {") - printer.indent { - for line in elementCleanup.lines { - printer.write(line) - } - } - printer.write("});") - } + try printer.indent { + let elementFragment = try stackLowerFragment(elementType: elementType) + let _ = try elementFragment.printCode( + [elemVar], + context + ) + } + printer.write("}") + scope.emitPushI32Parameter("\(arr).length", printer: printer) + return [] + } + ) + } + + /// Lowers a dictionary from JS to Swift by iterating entries and pushing to stacks + static func dictionaryLower(valueType: BridgeType) throws -> IntrinsicJSFragment { + return IntrinsicJSFragment( + parameters: ["dict"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let dict = arguments[0] + + let entriesVar = scope.variable("entries") + let entryVar = scope.variable("entry") + printer.write("const \(entriesVar) = Object.entries(\(dict));") + printer.write("for (const \(entryVar) of \(entriesVar)) {") + try printer.indent { + let keyVar = scope.variable("key") + let valueVar = scope.variable("value") + printer.write("const [\(keyVar), \(valueVar)] = \(entryVar);") + + let keyFragment = try stackLowerFragment(elementType: .string) + let _ = try keyFragment.printCode( + [keyVar], + context + ) + + let valueFragment = try stackLowerFragment(elementType: valueType) + let _ = try valueFragment.printCode( + [valueVar], + context + ) } printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(arr).length);") - cleanupCode.write("for (const cleanup of \(cleanupArrayVar)) { cleanup(); }") + scope.emitPushI32Parameter("\(entriesVar).length", printer: printer) return [] } ) @@ -2179,17 +1927,18 @@ struct IntrinsicJSFragment: Sendable { static func arrayLift(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanupCode in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("arrayResult") let lenVar = scope.variable("arrayLen") let iVar = scope.variable("i") - printer.write("const \(lenVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") + printer.write("const \(lenVar) = \(scope.popI32());") printer.write("const \(resultVar) = [];") printer.write("for (let \(iVar) = 0; \(iVar) < \(lenVar); \(iVar)++) {") - printer.indent { - let elementFragment = try! arrayElementRaiseFragment(elementType: elementType) - let elementResults = elementFragment.printCode([], scope, printer, cleanupCode) + try printer.indent { + let elementFragment = try stackLiftFragment(elementType: elementType) + let elementResults = try elementFragment.printCode([], context) if let elementExpr = elementResults.first { printer.write("\(resultVar).push(\(elementExpr));") } @@ -2201,105 +1950,120 @@ struct IntrinsicJSFragment: Sendable { ) } - private static func arrayElementRaiseFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { - switch elementType { - case .string: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let strVar = scope.variable("string") - printer.write("const \(strVar) = \(JSGlueVariableScope.reservedTmpRetStrings).pop();") - return [strVar] + /// Lifts a dictionary from Swift to JS by popping key/value pairs from stacks + static func dictionaryLift(valueType: BridgeType) throws -> IntrinsicJSFragment { + return IntrinsicJSFragment( + parameters: [], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("dictResult") + let lenVar = scope.variable("dictLen") + let iVar = scope.variable("i") + + printer.write("const \(lenVar) = \(scope.popI32());") + printer.write("const \(resultVar) = {};") + printer.write("for (let \(iVar) = 0; \(iVar) < \(lenVar); \(iVar)++) {") + try printer.indent { + let valueFragment = try stackLiftFragment(elementType: valueType) + let valueResults = try valueFragment.printCode([], context) + let keyFragment = try stackLiftFragment(elementType: .string) + let keyResults = try keyFragment.printCode([], context) + if let keyExpr = keyResults.first, let valueExpr = valueResults.first { + printer.write("\(resultVar)[\(keyExpr)] = \(valueExpr);") + } } - ) - case .bool: + printer.write("}") + return [resultVar] + } + ) + } + + private static func stackLiftFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + if case .nullable(let wrappedType, let kind) = elementType { + return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) + } + if elementType.isSingleParamScalar { + let wasmType = elementType.wasmParams[0].type + let coerce = elementType.liftCoerce + let varHint = elementType.varHint return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let bVar = scope.variable("bool") - printer.write("const \(bVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop() !== 0;") - return [bVar] + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let popExpr = popExpression(for: wasmType, scope: scope) + let varName = scope.variable(varHint) + if let transform = coerce { + let inlined = transform.replacingOccurrences(of: "$0", with: popExpr) + printer.write("const \(varName) = \(inlined);") + } else { + printer.write("const \(varName) = \(popExpr);") + } + return [varName] } ) - case .int, .uint: + } + switch elementType { + case .jsValue: return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let iVar = scope.variable("int") - printer.write("const \(iVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [iVar] + printCode: { _, context in + let (scope, printer) = (context.scope, context.printer) + let payload2Var = scope.variable("jsValuePayload2") + let payload1Var = scope.variable("jsValuePayload1") + let kindVar = scope.variable("jsValueKind") + printer.write("const \(payload2Var) = \(scope.popF64());") + printer.write("const \(payload1Var) = \(scope.popI32());") + printer.write("const \(kindVar) = \(scope.popI32());") + let resultVar = scope.variable("jsValue") + registerJSValueHelpers(scope: scope) + printer.write( + "const \(resultVar) = \(jsValueLiftHelperName)(\(kindVar), \(payload1Var), \(payload2Var));" + ) + return [resultVar] } ) - case .float: + case .string: return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let fVar = scope.variable("f32") - printer.write("const \(fVar) = \(JSGlueVariableScope.reservedTmpRetF32s).pop();") - return [fVar] + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let strVar = scope.variable("string") + printer.write("const \(strVar) = \(scope.popString());") + return [strVar] } ) - case .double: + case .rawValueEnum(_, .string): return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let dVar = scope.variable("f64") - printer.write("const \(dVar) = \(JSGlueVariableScope.reservedTmpRetF64s).pop();") - return [dVar] + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let varName = scope.variable("rawValue") + printer.write("const \(varName) = \(scope.popString());") + return [varName] } ) case .swiftStruct(let fullName): let structBase = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("struct") printer.write( - "const \(resultVar) = structHelpers.\(structBase).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" + "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lift();" ) return [resultVar] } ) - case .caseEnum: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("caseId") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [varName] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("rawValue") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetStrings).pop();") - return [varName] - } - ) - default: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("rawValue") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [varName] - } - ) - } case .associatedValueEnum(let fullName): let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let caseIdVar = scope.variable("caseId") + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let resultVar = scope.variable("enumValue") - printer.write("const \(caseIdVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") printer.write( - "const \(resultVar) = enumHelpers.\(base).lift(\(caseIdVar), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" + "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(scope.popI32()));" ) return [resultVar] } @@ -2307,223 +2071,182 @@ struct IntrinsicJSFragment: Sendable { case .swiftHeapObject(let className): return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let ptrVar = scope.variable("ptr") let objVar = scope.variable("obj") - printer.write("const \(ptrVar) = \(JSGlueVariableScope.reservedTmpRetPointers).pop();") - printer.write("const \(objVar) = \(className).__construct(\(ptrVar));") + printer.write("const \(ptrVar) = \(scope.popPointer());") + printer.write("const \(objVar) = _exports['\(className)'].__construct(\(ptrVar));") return [objVar] } ) case .jsObject, .swiftProtocol: return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let idVar = scope.variable("objId") let objVar = scope.variable("obj") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - printer.write("const \(objVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(idVar));") + printer.write("const \(idVar) = \(scope.popI32());") + printer.write( + "const \(objVar) = \(JSGlueVariableScope.reservedSwift).memory.getObject(\(idVar));" + ) printer.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") return [objVar] } ) case .array(let innerElementType): - return try! arrayLift(elementType: innerElementType) - case .optional(let wrappedType): - return try optionalElementRaiseFragment(wrappedType: wrappedType) - case .unsafePointer: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let pVar = scope.variable("pointer") - printer.write("const \(pVar) = \(JSGlueVariableScope.reservedTmpRetPointers).pop();") - return [pVar] - } - ) - case .void, .closure, .namespaceEnum: + return try arrayLift(elementType: innerElementType) + case .dictionary(let valueType): + return try dictionaryLift(valueType: valueType) + default: throw BridgeJSLinkError(message: "Unsupported array element type: \(elementType)") } } - private static func arrayElementLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { - switch elementType { - case .string: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let bytesVar = scope.variable("bytes") - let idVar = scope.variable("id") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - return [] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(arguments[0]) ? 1 : 0);") - return [] - } - ) - case .int, .uint: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") - return [] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(Math.fround(\(arguments[0])));") - return [] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(\(arguments[0]));") - return [] - } - ) - case .swiftStruct(let fullName): - let structBase = fullName.components(separatedBy: ".").last ?? fullName + private static func stackLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + if case .nullable(let wrappedType, let kind) = elementType { + return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) + } + if elementType.isSingleParamScalar { + let wasmType = elementType.wasmParams[0].type + let stackCoerce = elementType.stackLowerCoerce return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let cleanupVar = scope.variable("cleanup") - printer.write("const { cleanup: \(cleanupVar) } = structHelpers.\(structBase).lower(\(value));") - cleanup.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - return [] - } - ) - case .caseEnum: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") + let pushExpr: String + if let coerce = stackCoerce { + pushExpr = coerce.replacingOccurrences(of: "$0", with: value) + } else { + pushExpr = value + } + emitPush(for: wasmType, value: pushExpr, scope: scope, printer: printer) return [] } ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let bytesVar = scope.variable("bytes") - let idVar = scope.variable("id") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") - printer.write( - "const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - return [] - } - ) - default: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") - return [] - } - ) - } - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName + } + switch elementType { + case .jsValue: + return IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + registerJSValueHelpers(scope: scope) + let lowered = try jsValueLower.printCode([arguments[0]], context) + let kindVar = lowered[0] + let payload1Var = lowered[1] + let payload2Var = lowered[2] + scope.emitPushI32Parameter(kindVar, printer: printer) + scope.emitPushI32Parameter(payload1Var, printer: printer) + scope.emitPushF64Parameter(payload2Var, printer: printer) + return [] + } + ) + case .string, .rawValueEnum(_, .string): return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("enumCleanup") + let bytesVar = scope.variable("bytes") + let idVar = scope.variable("id") + printer.write( + "const \(bytesVar) = \(JSGlueVariableScope.reservedTextEncoder).encode(\(value));" + ) printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = enumHelpers.\(base).lower(\(value));" + "const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));" ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(caseIdVar));") - cleanup.write("if (\(cleanupVar)) { \(cleanupVar)(); }") + scope.emitPushI32Parameter("\(bytesVar).length", printer: printer) + scope.emitPushI32Parameter(idVar, printer: printer) return [] } ) - case .swiftHeapObject: + case .swiftStruct(let fullName): + let structBase = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push(\(arguments[0]).pointer);") + printCode: { arguments, context in + let printer = context.printer + let value = arguments[0] + printer.write( + "\(JSGlueVariableScope.reservedStructHelpers).\(structBase).lower(\(value));" + ) return [] } ) - case .jsObject: + + case .associatedValueEnum(let fullName): + let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let idVar = scope.variable("objId") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") + let caseIdVar = scope.variable("caseId") + printer.write( + "const \(caseIdVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" + ) + scope.emitPushI32Parameter(caseIdVar, printer: printer) return [] } ) - case .array(let innerElementType): - return try! arrayLower(elementType: innerElementType) - case .optional(let wrappedType): - return try optionalElementLowerFragment(wrappedType: wrappedType) - case .swiftProtocol: - // Same as jsObject but no cleanup — Swift's AnyProtocol wrapper releases via deinit + case .swiftHeapObject: return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let idVar = scope.variable("objId") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") + scope.emitPushPointerParameter("\(value).pointer", printer: printer) return [] } ) - case .unsafePointer: + case .jsObject, .swiftProtocol: return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push((\(arguments[0]) | 0));") + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let idVar = scope.variable("objId") + printer.write( + "const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));" + ) + scope.emitPushI32Parameter(idVar, printer: printer) return [] } ) - case .void, .closure, .namespaceEnum: + case .array(let innerElementType): + return try arrayLower(elementType: innerElementType) + case .dictionary(let valueType): + return try dictionaryLower(valueType: valueType) + default: throw BridgeJSLinkError(message: "Unsupported array element type for lowering: \(elementType)") } } - private static func optionalElementRaiseFragment(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + private static func optionalElementRaiseFragment( + wrappedType: BridgeType, + kind: JSOptionalKind + ) throws -> IntrinsicJSFragment { + let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let isSomeVar = scope.variable("isSome") let resultVar = scope.variable("optValue") - printer.write("const \(isSomeVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") + printer.write("const \(isSomeVar) = \(scope.popI32());") printer.write("let \(resultVar);") printer.write("if (\(isSomeVar) === 0) {") printer.indent { - printer.write("\(resultVar) = null;") + printer.write("\(resultVar) = \(absenceLiteral);") } printer.write("} else {") - printer.indent { - let innerFragment = try! arrayElementRaiseFragment(elementType: wrappedType) - let innerResults = innerFragment.printCode([], scope, printer, cleanup) + try printer.indent { + let innerFragment = try stackLiftFragment(elementType: wrappedType) + let innerResults = try innerFragment.printCode([], context) if let innerResult = innerResults.first { printer.write("\(resultVar) = \(innerResult);") } else { @@ -2537,153 +2260,135 @@ struct IntrinsicJSFragment: Sendable { ) } - private static func optionalElementLowerFragment(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + private static func optionalElementLowerFragment( + wrappedType: BridgeType, + kind: JSOptionalKind + ) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(value) != null ? 1 : 0;") - // Cleanup is written inside the if block so retained id is in scope - let localCleanupWriter = CodeFragmentPrinter() + let presenceExpr = kind.presenceCheck(value: value) + printer.write("const \(isSomeVar) = \(presenceExpr) ? 1 : 0;") printer.write("if (\(isSomeVar)) {") - printer.indent { - let innerFragment = try! arrayElementLowerFragment(elementType: wrappedType) - let _ = innerFragment.printCode([value], scope, printer, localCleanupWriter) - let localCleanupLines = localCleanupWriter.lines.filter { - !$0.trimmingCharacters(in: .whitespaces).isEmpty - } - if !localCleanupLines.isEmpty { - let localCleanupCode = localCleanupLines.joined(separator: " ") - printer.write("arrayCleanups.push(() => { \(localCleanupCode) });") - } + try printer.indent { + let innerFragment = try stackLowerFragment(elementType: wrappedType) + let _ = try innerFragment.printCode( + [value], + context + ) } - printer.write("} else {") - printer.indent { - // Push placeholders so Swift can unconditionally pop value slots - switch wrappedType { - case .float: - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(0.0);") - case .double: - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(0.0);") - case .swiftStruct: - // No placeholder — Swift only pops struct fields when isSome=1 - break - case .string, .rawValueEnum(_, .string): - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - case .swiftHeapObject: - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push(0);") - default: - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") + let placeholderPrinter = CodeFragmentPrinter() + let hasPlaceholders = emitOptionalPlaceholders( + for: wrappedType, + scope: scope, + printer: placeholderPrinter + ) + if hasPlaceholders { + printer.write("} else {") + printer.indent { + for line in placeholderPrinter.lines { + printer.write(line) + } } + printer.write("}") + } else { + printer.write("}") } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar));") + scope.emitPushI32Parameter(isSomeVar, printer: printer) return [] } ) } + // MARK: - Struct Helpers + static func structHelper(structDefinition: ExportedStruct, allStructs: [ExportedStruct]) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["structName"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let printer = context.printer let structName = arguments[0] let capturedStructDef = structDefinition let capturedAllStructs = allStructs - printer.write("const __bjs_create\(structName)Helpers = () => {") - printer.indent() - printer.write( - "return (\(JSGlueVariableScope.reservedTmpParamInts), \(JSGlueVariableScope.reservedTmpParamF32s), \(JSGlueVariableScope.reservedTmpParamF64s), \(JSGlueVariableScope.reservedTmpParamPointers), \(JSGlueVariableScope.reservedTmpRetPointers), textEncoder, \(JSGlueVariableScope.reservedSwift), \(JSGlueVariableScope.reservedEnumHelpers)) => ({" - ) - printer.indent() - - printer.write("lower: (value) => {") - printer.indent { - generateStructLowerCode( - structDef: capturedStructDef, - allStructs: capturedAllStructs, - printer: printer - ) - } - printer.write("},") + printer.write("const __bjs_create\(structName)Helpers = () => ({") + try printer.indent { + printer.write("lower: (value) => {") + try printer.indent { + try generateStructLowerCode( + structDef: capturedStructDef, + allStructs: capturedAllStructs, + context: context + ) + } + printer.write("},") - printer.write( - "lift: (\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers)) => {" - ) - printer.indent { - generateStructLiftCode( - structDef: capturedStructDef, - allStructs: capturedAllStructs, - printer: printer, - attachMethods: true - ) + printer.write("lift: () => {") + try printer.indent { + try generateStructLiftCode( + structDef: capturedStructDef, + allStructs: capturedAllStructs, + context: context, + attachMethods: true + ) + } + printer.write("}") } - printer.write("}") - printer.unindent() printer.write("});") - printer.unindent() - printer.write("};") return [] } ) } - private static func findStruct(name: String, structs: [ExportedStruct]) -> ExportedStruct? { - return structs.first(where: { $0.swiftCallName == name || $0.name == name }) - } - private static func generateStructLowerCode( structDef: ExportedStruct, allStructs: [ExportedStruct], - printer: CodeFragmentPrinter - ) { + context: IntrinsicJSFragment.PrintCodeContext + ) throws { + let (scope, printer) = (context.scope, context.printer) let lowerPrinter = CodeFragmentPrinter() - let lowerScope = JSGlueVariableScope() - let lowerCleanup = CodeFragmentPrinter() - lowerCleanup.indent() + let lowerScope = scope.makeChildScope() let instanceProps = structDef.properties.filter { !$0.isStatic } for property in instanceProps { - let fragment = structFieldLowerFragment(field: property, allStructs: allStructs) + let fragment = try structFieldLowerFragment( + type: property.type, + fieldName: property.name, + allStructs: allStructs + ) let fieldValue = "value.\(property.name)" - _ = fragment.printCode([fieldValue], lowerScope, lowerPrinter, lowerCleanup) + _ = try fragment.printCode( + [fieldValue], + context.with(\.scope, lowerScope).with(\.printer, lowerPrinter) + ) } for line in lowerPrinter.lines { printer.write(line) } - - if !lowerCleanup.lines.isEmpty { - printer.write("const cleanup = () => {") - printer.write(contentsOf: lowerCleanup) - printer.write("};") - printer.write("return { cleanup };") - } else { - printer.write("return { cleanup: undefined };") - } } private static func generateStructLiftCode( structDef: ExportedStruct, allStructs: [ExportedStruct], - printer: CodeFragmentPrinter, + context: IntrinsicJSFragment.PrintCodeContext, attachMethods: Bool = false - ) { - let liftScope = JSGlueVariableScope() - let liftCleanup = CodeFragmentPrinter() + ) throws { + let printer = context.printer + let liftScope = context.scope.makeChildScope() var fieldExpressions: [(name: String, expression: String)] = [] let instanceProps = structDef.properties.filter { !$0.isStatic } for property in instanceProps.reversed() { - let fragment = structFieldLiftFragment(field: property, allStructs: allStructs) - let results = fragment.printCode([], liftScope, printer, liftCleanup) + let fragment = try structFieldLiftFragment(field: property, allStructs: allStructs) + let results = try fragment.printCode([], context) if let resultExpr = results.first { fieldExpressions.append((property.name, resultExpr)) @@ -2708,25 +2413,18 @@ struct IntrinsicJSFragment: Sendable { printer.write( "\(instanceVar).\(method.name) = function(\(paramList)) {" ) - printer.indent { - let methodScope = JSGlueVariableScope() - let methodCleanup = CodeFragmentPrinter() - - // Lower the struct instance (this) using the helper's lower function - let structCleanupVar = methodScope.variable("structCleanup") + try printer.indent { printer.write( - "const { cleanup: \(structCleanupVar) } = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(this);" + "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.name).lower(this);" ) - // Lower each parameter and collect forwarding expressions var paramForwardings: [String] = [] for param in method.parameters { - let fragment = try! IntrinsicJSFragment.lowerParameter(type: param.type) - let loweredValues = fragment.printCode([param.name], methodScope, printer, methodCleanup) + let fragment = try IntrinsicJSFragment.lowerParameter(type: param.type) + let loweredValues = try fragment.printCode([param.name], context) paramForwardings.append(contentsOf: loweredValues) } - // Call the Swift function with all lowered parameters let callExpr = "instance.exports.\(method.abiName)(\(paramForwardings.joined(separator: ", ")))" if method.returnType == .void { printer.write("\(callExpr);") @@ -2734,18 +2432,13 @@ struct IntrinsicJSFragment: Sendable { printer.write("const ret = \(callExpr);") } - // Cleanup - printer.write("if (\(structCleanupVar)) { \(structCleanupVar)(); }") - printer.write(contentsOf: methodCleanup) - // Lift return value if needed if method.returnType != .void { - let liftFragment = try! IntrinsicJSFragment.liftReturn(type: method.returnType) - if !liftFragment.parameters.isEmpty { - let lifted = liftFragment.printCode(["ret"], methodScope, printer, methodCleanup) - if let liftedValue = lifted.first { - printer.write("return \(liftedValue);") - } + let liftFragment = try IntrinsicJSFragment.liftReturn(type: method.returnType) + let liftArgs = liftFragment.parameters.isEmpty ? [] : ["ret"] + let lifted = try liftFragment.printCode(liftArgs, context) + if let liftedValue = lifted.first { + printer.write("return \(liftedValue);") } } } @@ -2755,574 +2448,139 @@ struct IntrinsicJSFragment: Sendable { printer.write("return \(instanceVar);") } else { printer.write("return { \(reconstructedFields.joined(separator: ", ")) };") - } - } - - private static func structFieldLowerFragment( - field: ExportedProperty, - allStructs: [ExportedStruct] - ) -> IntrinsicJSFragment { - switch field.type { - case .string: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let bytesVar = scope.variable("bytes") - let idVar = scope.variable("id") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") - printer.write("const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - return [idVar] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(arguments[0]) ? 1 : 0);") - return [] - } - ) - case .int, .uint: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") - return [] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(Math.fround(\(arguments[0])));") - return [] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(\(arguments[0]));") - return [] - } - ) - case .unsafePointer: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push((\(arguments[0]) | 0));") - return [] - } - ) - case .jsObject: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(value) != null) {") - printer.indent { - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - } - printer.write("} else {") - printer.indent { - printer.write("\(idVar) = undefined;") - } - printer.write("}") - printer.write( - "\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar) !== undefined ? \(idVar) : 0);" - ) - cleanup.write("if(\(idVar) !== undefined && \(idVar) !== 0) {") - cleanup.indent { - cleanup.write("try {") - cleanup.indent { - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.getObject(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - } - cleanup.write("} catch(e) {}") - } - cleanup.write("}") - return [idVar] - } - ) - case .optional(let wrappedType): - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(value) != null;") - - if case .caseEnum = wrappedType { - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(value) | 0));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - return [] - } else if case .rawValueEnum(_, let rawType) = wrappedType { - switch rawType { - case .string: - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let bytesVar = scope.variable("bytes") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") - printer.write( - "\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write( - "if(\(idVar) !== undefined) { \(JSGlueVariableScope.reservedSwift).memory.release(\(idVar)); }" - ) - return [idVar] - case .float: - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write( - "\(JSGlueVariableScope.reservedTmpParamF32s).push(Math.fround(\(value)));" - ) - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(0.0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - return [] - case .double: - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(\(value));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(0.0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - return [] - default: - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(value) | 0));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - return [] - } - } else if case .swiftHeapObject = wrappedType { - let ptrVar = scope.variable("ptr") - printer.write("let \(ptrVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(ptrVar) = \(value).pointer;") - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push(\(ptrVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - return [] - } else if case .swiftStruct(let structName) = wrappedType { - let nestedCleanupVar = scope.variable("nestedCleanup") - printer.write("let \(nestedCleanupVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let structResultVar = scope.variable("structResult") - printer.write( - "const \(structResultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structName).lower(\(value));" - ) - printer.write("\(nestedCleanupVar) = \(structResultVar).cleanup;") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write("if (\(nestedCleanupVar)) { \(nestedCleanupVar)(); }") - return [] - } else if case .string = wrappedType { - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let bytesVar = scope.variable("bytes") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write( - "if(\(idVar) !== undefined) { \(JSGlueVariableScope.reservedSwift).memory.release(\(idVar)); }" - ) - return [idVar] - } else if case .jsObject = wrappedType { - let idVar = scope.variable("id") - printer.write("let \(idVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - printer.write("\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(idVar) = undefined;") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write("if(\(idVar) !== undefined && \(idVar) !== 0) {") - cleanup.indent { - cleanup.write("try {") - cleanup.indent { - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.getObject(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - } - cleanup.write("} catch(e) {}") - } - cleanup.write("}") - return [idVar] - } else { - // Handle optional primitive types using helper - switch wrappedType { - case .int, .uint: - pushOptionalPrimitive( - value: value, - isSomeVar: isSomeVar, - stack: .tmpParamInts, - convert: "| 0", - zeroValue: "0", - printer: printer - ) - case .bool: - pushOptionalPrimitive( - value: value, - isSomeVar: isSomeVar, - stack: .tmpParamInts, - convert: "? 1 : 0", - zeroValue: "0", - printer: printer - ) - case .float: - pushOptionalPrimitive( - value: value, - isSomeVar: isSomeVar, - stack: .tmpParamF32s, - convert: "Math.fround", - zeroValue: "0.0", - printer: printer - ) - case .double: - pushOptionalPrimitive( - value: value, - isSomeVar: isSomeVar, - stack: .tmpParamF64s, - convert: nil, - zeroValue: "0.0", - printer: printer - ) - case .associatedValueEnum(let enumName): - let base = enumName.components(separatedBy: ".").last ?? enumName - let caseIdVar = scope.variable("enumCaseId") - let enumCleanupVar = scope.variable("enumCleanup") - printer.write("let \(caseIdVar), \(enumCleanupVar);") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let enumResultVar = scope.variable("enumResult") - printer.write( - "const \(enumResultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" - ) - printer.write("\(caseIdVar) = \(enumResultVar).caseId;") - printer.write("\(enumCleanupVar) = \(enumResultVar).cleanup;") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(caseIdVar));") - } - printer.write("} else {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(0);") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - cleanup.write("if (\(enumCleanupVar)) { \(enumCleanupVar)(); }") - default: - // For other types (nested structs, etc.), original logic applies - let wrappedFragment = structFieldLowerFragment( - field: ExportedProperty( - name: field.name, - type: wrappedType, - isReadonly: true, - isStatic: false - ), - allStructs: allStructs - ) - printer.write("if (\(isSomeVar)) {") - printer.indent { - _ = wrappedFragment.printCode([value], scope, printer, cleanup) - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - } - return [] - } - } - ) - case .swiftStruct(let nestedName): - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let structResultVar = scope.variable("structResult") - printer.write( - "const \(structResultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lower(\(value));" - ) - cleanup.write("if (\(structResultVar).cleanup) { \(structResultVar).cleanup(); }") - return [] - } - ) - case .swiftHeapObject: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - printer.write("\(JSGlueVariableScope.reservedTmpParamPointers).push(\(value).pointer);") - return [] - } - ) - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName + } + } + + private static func structFieldLowerFragment( + type: BridgeType, + fieldName: String, + allStructs: [ExportedStruct] + ) throws -> IntrinsicJSFragment { + switch type { + case .jsValue: + preconditionFailure("Struct field of JSValue is not supported yet") + case .jsObject: return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let value = arguments[0] - let caseIdVar = scope.variable("caseId") - let cleanupVar = scope.variable("enumCleanup") - printer.write( - "const { caseId: \(caseIdVar), cleanup: \(cleanupVar) } = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" - ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(caseIdVar));") - cleanup.write("if (\(cleanupVar)) { \(cleanupVar)(); }") - return [cleanupVar] - } - ) - case .caseEnum: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") - return [] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - let value = arguments[0] - let bytesVar = scope.variable("bytes") - let idVar = scope.variable("id") - printer.write("const \(bytesVar) = textEncoder.encode(\(value));") + let idVar = scope.variable("id") + printer.write("let \(idVar);") + printer.write("if (\(value) != null) {") + printer.indent { printer.write( - "const \(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(bytesVar));" + "\(idVar) = \(JSGlueVariableScope.reservedSwift).memory.retain(\(value));" ) - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(bytesVar).length);") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(idVar));") - cleanup.write("\(JSGlueVariableScope.reservedSwift).memory.release(\(idVar));") - return [idVar] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF32s).push(Math.fround(\(arguments[0])));") - return [] } - ) - case .double: - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamF64s).push(\(arguments[0]));") - return [] + printer.write("} else {") + printer.indent { + printer.write("\(idVar) = undefined;") } - ) - default: + printer.write("}") + scope.emitPushI32Parameter("\(idVar) !== undefined ? \(idVar) : 0", printer: printer) + return [idVar] + } + ) + case .nullable(let wrappedType, let kind): + if wrappedType.isSingleParamScalar { + let wasmType = wrappedType.wasmParams[0].type + let stackCoerce = wrappedType.stackLowerCoerce return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push((\(arguments[0]) | 0));") + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let value = arguments[0] + let isSomeVar = scope.variable("isSome") + printer.write("const \(isSomeVar) = \(kind.presenceCheck(value: value));") + let coerced: String + if let coerce = stackCoerce { + coerced = coerce.replacingOccurrences(of: "$0", with: value) + } else { + coerced = value + } + printer.write("if (\(isSomeVar)) {") + printer.indent { + emitPush(for: wasmType, value: coerced, scope: scope, printer: printer) + } + printer.write("} else {") + printer.indent { + emitPush(for: wasmType, value: wasmType.jsZeroLiteral, scope: scope, printer: printer) + } + printer.write("}") + scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) return [] } ) } + + let innerFragment = try structFieldLowerFragment( + type: wrappedType, + fieldName: fieldName, + allStructs: allStructs + ) + return stackOptionalLower( + wrappedType: wrappedType, + kind: kind, + innerFragment: innerFragment + ) + case .swiftStruct(let nestedName): + return IntrinsicJSFragment( + parameters: ["value"], + printCode: { arguments, context in + let printer = context.printer + let value = arguments[0] + printer.write( + "\(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lower(\(value));" + ) + return [] + } + ) case .void, .swiftProtocol, .namespaceEnum, .closure: // These types should not appear as struct fields - return error fragment return IntrinsicJSFragment( parameters: ["value"], - printCode: { arguments, scope, printer, cleanup in - printer.write("throw new Error(\"Unsupported struct field type for lowering: \(field.type)\");") + printCode: { arguments, context in + context.printer.write( + "throw new Error(\"Unsupported struct field type for lowering: \(type)\");" + ) return [] } ) - case .array(let elementType): - return try! arrayLower(elementType: elementType) + default: + return try stackLowerFragment(elementType: type) } } /// Helper to push optional primitive values to stack-based parameters - private static func pushOptionalPrimitive( - value: String, - isSomeVar: String, - stack: StackType, - convert: String?, - zeroValue: String, - printer: CodeFragmentPrinter - ) { - let stackName: String - switch stack { - case .tmpParamInts: stackName = JSGlueVariableScope.reservedTmpParamInts - case .tmpParamF32s: stackName = JSGlueVariableScope.reservedTmpParamF32s - case .tmpParamF64s: stackName = JSGlueVariableScope.reservedTmpParamF64s - } - - printer.write("if (\(isSomeVar)) {") - printer.indent { - let converted: String - if let convert = convert { - if convert.starts(with: "Math.") { - converted = "\(convert)(\(value))" - } else { - converted = "\(value) \(convert)" - } - } else { - converted = value - } - printer.write("\(stackName).push(\(converted));") - } - printer.write("} else {") - printer.indent { - printer.write("\(stackName).push(\(zeroValue));") - } - printer.write("}") - printer.write("\(JSGlueVariableScope.reservedTmpParamInts).push(\(isSomeVar) ? 1 : 0);") - } - - private enum StackType { - case tmpParamInts - case tmpParamF32s - case tmpParamF64s - } - private static func structFieldLiftFragment( field: ExportedProperty, allStructs: [ExportedStruct] - ) -> IntrinsicJSFragment { + ) throws -> IntrinsicJSFragment { switch field.type { - case .string: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let strVar = scope.variable("string") - printer.write("const \(strVar) = \(JSGlueVariableScope.reservedTmpRetStrings).pop();") - return [strVar] - } - ) - case .bool: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let bVar = scope.variable("bool") - printer.write("const \(bVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop() !== 0;") - return [bVar] - } - ) - case .int, .uint: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let iVar = scope.variable("int") - printer.write("const \(iVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [iVar] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let fVar = scope.variable("f32") - printer.write("const \(fVar) = \(JSGlueVariableScope.reservedTmpRetF32s).pop();") - return [fVar] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let dVar = scope.variable("f64") - printer.write("const \(dVar) = \(JSGlueVariableScope.reservedTmpRetF64s).pop();") - return [dVar] - } - ) - case .unsafePointer: + case .jsValue: + preconditionFailure("Struct field of JSValue is not supported yet") + case .nullable(let wrappedType, let kind): return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - let pVar = scope.variable("pointer") - printer.write("const \(pVar) = \(JSGlueVariableScope.reservedTmpRetPointers).pop();") - return [pVar] - } - ) - case .optional(let wrappedType): - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let isSomeVar = scope.variable("isSome") let optVar = scope.variable("optional") - printer.write("const \(isSomeVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") + printer.write("const \(isSomeVar) = \(scope.popI32());") printer.write("let \(optVar);") printer.write("if (\(isSomeVar)) {") - printer.indent { - // Special handling for associated value enum - in struct fields, case ID is pushed to tmpRetInts + try printer.indent { + // Special handling for associated value enum - in struct fields, case ID is pushed to i32Stack if case .associatedValueEnum(let enumName) = wrappedType { let base = enumName.components(separatedBy: ".").last ?? enumName let caseIdVar = scope.variable("enumCaseId") - printer.write("const \(caseIdVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") + printer.write("const \(caseIdVar) = \(scope.popI32());") printer.write( - "\(optVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" + "\(optVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar));" ) } else { - let wrappedFragment = structFieldLiftFragment( + let wrappedFragment = try structFieldLiftFragment( field: ExportedProperty( name: field.name, type: wrappedType, @@ -3331,7 +2589,7 @@ struct IntrinsicJSFragment: Sendable { ), allStructs: allStructs ) - let wrappedResults = wrappedFragment.printCode([], scope, printer, cleanup) + let wrappedResults = try wrappedFragment.printCode([], context) if let wrappedResult = wrappedResults.first { printer.write("\(optVar) = \(wrappedResult);") } else { @@ -3341,7 +2599,7 @@ struct IntrinsicJSFragment: Sendable { } printer.write("} else {") printer.indent { - printer.write("\(optVar) = null;") + printer.write("\(optVar) = \(kind.absenceLiteral);") } printer.write("}") return [optVar] @@ -3350,80 +2608,23 @@ struct IntrinsicJSFragment: Sendable { case .swiftStruct(let nestedName): return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let structVar = scope.variable("struct") printer.write( - "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lift(\(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s), \(JSGlueVariableScope.reservedTmpRetPointers));" + "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName).lift();" ) return [structVar] } ) - case .caseEnum: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [varName] - } - ) - case .rawValueEnum(_, let rawType): - switch rawType { - case .string: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetStrings).pop();") - return [varName] - } - ) - case .float: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetF32s).pop();") - return [varName] - } - ) - case .double: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetF64s).pop();") - return [varName] - } - ) - default: - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write("const \(varName) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") - return [varName] - } - ) - } - case .swiftHeapObject(let className): - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let ptrVar = scope.variable("ptr") - let varName = scope.variable("value") - printer.write("const \(ptrVar) = \(JSGlueVariableScope.reservedTmpRetPointers).pop();") - printer.write("const \(varName) = _exports['\(className)'].__construct(\(ptrVar));") - return [varName] - } - ) case .jsObject: return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) let objectIdVar = scope.variable("objectId") let varName = scope.variable("value") - printer.write("const \(objectIdVar) = \(JSGlueVariableScope.reservedTmpRetInts).pop();") + printer.write("const \(objectIdVar) = \(scope.popI32());") printer.write("let \(varName);") printer.write("if (\(objectIdVar) !== 0) {") printer.indent { @@ -3440,29 +2641,235 @@ struct IntrinsicJSFragment: Sendable { return [varName] } ) - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, scope, printer, cleanup in - let varName = scope.variable("value") - printer.write( - "const \(varName) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(JSGlueVariableScope.reservedTmpRetTag), \(JSGlueVariableScope.reservedTmpRetStrings), \(JSGlueVariableScope.reservedTmpRetInts), \(JSGlueVariableScope.reservedTmpRetF32s), \(JSGlueVariableScope.reservedTmpRetF64s));" - ) - return [varName] - } - ) case .void, .swiftProtocol, .namespaceEnum, .closure: // These types should not appear as struct fields return IntrinsicJSFragment( parameters: [], - printCode: { arguments, scope, printer, cleanup in - printer.write("throw new Error(\"Unsupported struct field type: \(field.type)\");") + printCode: { arguments, context in + context.printer.write("throw new Error(\"Unsupported struct field type: \(field.type)\");") return [] } ) - case .array(let elementType): - return try! arrayLift(elementType: elementType) + default: + return try stackLiftFragment(elementType: field.type) + } + } +} + +// MARK: - Local type helpers + +fileprivate extension WasmCoreType { + var jsZeroLiteral: String { + switch self { + case .f32, .f64: return "0.0" + case .i32, .i64, .pointer: return "0" + } + } +} + +private enum OptionalConvention: Equatable { + case stackABI + case inlineFlag + case sideChannelReturn(OptionalSideChannel) +} + +private enum OptionalSideChannel: Equatable { + case none + case storage + case retainedObject +} + +private enum NilSentinel: Equatable { + case none + case i32(Int32) + case pointer + + var jsLiteral: String { + switch self { + case .none: fatalError("No sentinel value for .none") + case .i32(let value): return "\(value)" + case .pointer: return "0" + } + } + + var hasSentinel: Bool { + self != .none + } +} + +private enum OptionalScalarKind: String { + case bool, int, float, double + + var storageName: String { "tmpRetOptional\(rawValue.prefix(1).uppercased())\(rawValue.dropFirst())" } + var funcName: String { "swift_js_return_optional_\(rawValue)" } +} + +private extension BridgeType { + var optionalConvention: OptionalConvention { + switch self { + case .bool: + return .inlineFlag + case .int, .uint: + return .sideChannelReturn(.none) + case .float: + return .sideChannelReturn(.none) + case .double: + return .sideChannelReturn(.none) + case .string: + return .sideChannelReturn(.storage) + case .jsObject: + return .sideChannelReturn(.retainedObject) + case .jsValue: + return .inlineFlag + case .swiftHeapObject: + return .inlineFlag + case .unsafePointer: + return .inlineFlag + case .swiftProtocol: + return .sideChannelReturn(.retainedObject) + case .caseEnum: + return .inlineFlag + case .rawValueEnum(_, let rawType): + switch rawType { + case .string: + return .sideChannelReturn(.storage) + case .float, .double: + return .sideChannelReturn(.none) + case .bool: + return .inlineFlag + case .int, .int32, .int64, .uint, .uint32, .uint64: + return .sideChannelReturn(.none) + } + case .associatedValueEnum: + return .inlineFlag + case .closure: + return .inlineFlag + case .swiftStruct, .array, .dictionary, .void, .namespaceEnum: + return .stackABI + case .nullable(let wrapped, _): + return wrapped.optionalConvention + } + } + + var nilSentinel: NilSentinel { + switch self { + case .jsObject, .swiftProtocol: + return .i32(0) + case .swiftHeapObject: + return .pointer + case .caseEnum, .associatedValueEnum: + return .i32(-1) + case .nullable(let wrapped, _): + return wrapped.nilSentinel + default: + return .none + } + } + + var optionalScalarKind: OptionalScalarKind? { + switch self { + case .bool, .rawValueEnum(_, .bool): return .bool + case .int, .uint, .caseEnum, + .rawValueEnum(_, .int), .rawValueEnum(_, .int32), .rawValueEnum(_, .int64), + .rawValueEnum(_, .uint), .rawValueEnum(_, .uint32), .rawValueEnum(_, .uint64): + return .int + case .float, .rawValueEnum(_, .float): return .float + case .double, .rawValueEnum(_, .double): return .double + case .nullable(let wrapped, _): return wrapped.optionalScalarKind + default: return nil + } + } + + var wasmParams: [(name: String, type: WasmCoreType)] { + switch self { + case .bool, .int, .uint: + return [("value", .i32)] + case .float: + return [("value", .f32)] + case .double: + return [("value", .f64)] + case .string: + return [("bytes", .i32), ("length", .i32)] + case .jsObject: + return [("value", .i32)] + case .jsValue: + return [("kind", .i32), ("payload1", .i32), ("payload2", .f64)] + case .swiftHeapObject: + return [("pointer", .pointer)] + case .unsafePointer: + return [("pointer", .pointer)] + case .swiftProtocol: + return [("value", .i32)] + case .caseEnum: + return [("value", .i32)] + case .rawValueEnum(_, let rawType): + switch rawType { + case .string: + return [("bytes", .i32), ("length", .i32)] + case .float: + return [("value", .f32)] + case .double: + return [("value", .f64)] + case .bool, .int, .int32, .int64, .uint, .uint32, .uint64: + return [("value", .i32)] + } + case .associatedValueEnum: + return [("caseId", .i32)] + case .closure: + return [("funcRef", .i32)] + case .void, .namespaceEnum, .swiftStruct, .array, .dictionary: + return [] + case .nullable(let wrapped, _): + return wrapped.wasmParams + } + } + + var isSingleParamScalar: Bool { + switch self { + case .bool, .int, .uint, .float, .double, .unsafePointer, .caseEnum: return true + case .rawValueEnum(_, let rawType): return rawType != .string + default: return false + } + } + + var stackLowerCoerce: String? { + switch self { + case .bool, .rawValueEnum(_, .bool): return "$0 ? 1 : 0" + case .int, .uint, .unsafePointer, .caseEnum, + .rawValueEnum(_, .int), .rawValueEnum(_, .int32), .rawValueEnum(_, .int64), + .rawValueEnum(_, .uint), .rawValueEnum(_, .uint32), .rawValueEnum(_, .uint64): + return "($0 | 0)" + case .float, .rawValueEnum(_, .float): return "Math.fround($0)" + case .double, .rawValueEnum(_, .double): return nil + default: return nil + } + } + + var liftCoerce: String? { + switch self { + case .bool, .rawValueEnum(_, .bool): return "$0 !== 0" + case .uint: return "$0 >>> 0" + default: return nil + } + } + + var lowerCoerce: String? { + switch self { + case .bool, .rawValueEnum(_, .bool): return "$0 ? 1 : 0" + default: return nil + } + } + + var varHint: String { + switch self { + case .bool: return "bool" + case .int, .uint: return "int" + case .float: return "f32" + case .double: return "f64" + case .unsafePointer: return "pointer" + case .caseEnum: return "caseId" + case .rawValueEnum: return "rawValue" + default: return "value" } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift new file mode 100644 index 000000000..c3e77d83f --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift @@ -0,0 +1,37 @@ +#if canImport(BridgeJSUtilities) +import BridgeJSUtilities +#endif + +/// Registry for JS helper intrinsics used during code generation. +final class JSIntrinsicRegistry { + private var entries: [String: [String]] = [:] + + var isEmpty: Bool { + entries.isEmpty + } + + func register(name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { + guard entries[name] == nil else { return } + let printer = CodeFragmentPrinter() + try build(printer) + entries[name] = printer.lines + } + + func reset() { + entries.removeAll() + } + + func emitLines() -> [String] { + var emitted: [String] = [] + for key in entries.keys.sorted() { + if let lines = entries[key] { + emitted.append(contentsOf: lines) + emitted.append("") + } + } + if emitted.last == "" { + emitted.removeLast() + } + return emitted + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSClassMacro.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSClassMacro.swift index 8a3f83f05..c44655c7e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSClassMacro.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSClassMacro.swift @@ -13,13 +13,55 @@ extension JSClassMacro: MemberMacro { in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard declaration.is(StructDeclSyntax.self) else { + var fixIts: [FixIt] = [] + let note = Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "Use @JSClass on a struct wrapper to synthesize jsObject and JS bridging members." + ) + ) + + if let classDecl = declaration.as(ClassDeclSyntax.self) { + let structKeyword = classDecl.classKeyword.with(\.tokenKind, .keyword(.struct)) + fixIts.append( + FixIt( + message: JSMacroFixItMessage(message: "Change 'class' to 'struct'"), + changes: [ + .replace( + oldNode: Syntax(classDecl.classKeyword), + newNode: Syntax(structKeyword) + ) + ] + ) + ) + } context.diagnose( - Diagnostic(node: Syntax(declaration), message: JSMacroMessage.unsupportedJSClassDeclaration) + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedJSClassDeclaration, + notes: [note], + fixIts: fixIts + ) ) return [] } var members: [DeclSyntax] = [] + guard let structDecl = declaration.as(StructDeclSyntax.self) else { return members } + + if let accessLevel = accessLevel(from: structDecl.modifiers), + accessLevel == .private || accessLevel == .fileprivate + { + context.diagnose( + Diagnostic( + node: Syntax(structDecl), + message: JSMacroMessage.jsClassRequiresAtLeastInternal + ) + ) + return [] + } + + let memberAccessModifier = synthesizedMemberAccessModifier(for: declaration).map { "\($0) " } ?? "" let existingMembers = declaration.memberBlock.members let hasJSObjectProperty = existingMembers.contains { member in @@ -30,7 +72,7 @@ extension JSClassMacro: MemberMacro { } if !hasJSObjectProperty { - members.append(DeclSyntax("let jsObject: JSObject")) + members.append(DeclSyntax("\(raw: memberAccessModifier)let jsObject: JSObject")) } let hasUnsafelyWrappingInit = existingMembers.contains { member in @@ -46,7 +88,7 @@ extension JSClassMacro: MemberMacro { members.append( DeclSyntax( """ - init(unsafelyWrapping jsObject: JSObject) { + \(raw: memberAccessModifier)init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } """ @@ -66,12 +108,57 @@ extension JSClassMacro: ExtensionMacro { conformingTo protocols: [TypeSyntax], in context: some MacroExpansionContext ) throws -> [ExtensionDeclSyntax] { - guard declaration.is(StructDeclSyntax.self) else { return [] } + guard let structDecl = declaration.as(StructDeclSyntax.self) else { return [] } guard !protocols.isEmpty else { return [] } + if let accessLevel = accessLevel(from: structDecl.modifiers), + accessLevel == .private || accessLevel == .fileprivate + { + return [] + } + + // Do not add extension if the struct already conforms to _JSBridgedClass + if let clause = structDecl.inheritanceClause, + clause.inheritedTypes.contains(where: { $0.type.trimmed.description == "_JSBridgedClass" }) + { + return [] + } let conformanceList = protocols.map { $0.trimmed.description }.joined(separator: ", ") return [ try ExtensionDeclSyntax("extension \(type.trimmed): \(raw: conformanceList) {}") ] } + + private static func synthesizedMemberAccessModifier(for declaration: some DeclGroupSyntax) -> String? { + guard let structDecl = declaration.as(StructDeclSyntax.self) else { return nil } + switch accessLevel(from: structDecl.modifiers) { + case .public: return "public" + case .package: return "package" + case .internal: return "internal" + case .fileprivate, .private, .none: return nil + } + } + + private enum AccessLevel { + case `public` + case package + case `internal` + case `fileprivate` + case `private` + } + + private static func accessLevel(from modifiers: DeclModifierListSyntax?) -> AccessLevel? { + guard let modifiers else { return nil } + for modifier in modifiers { + switch modifier.name.tokenKind { + case .keyword(.public): return .public + case .keyword(.package): return .package + case .keyword(.internal): return .internal + case .keyword(.fileprivate): return .fileprivate + case .keyword(.private): return .private + default: continue + } + } + return nil + } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSFunctionMacro.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSFunctionMacro.swift index 7dfd635f9..0fff3546a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSFunctionMacro.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSFunctionMacro.swift @@ -14,7 +14,17 @@ extension JSFunctionMacro: BodyMacro { if let functionDecl = declaration.as(FunctionDeclSyntax.self) { let enclosingTypeName = JSMacroHelper.enclosingTypeName(from: context) let isStatic = JSMacroHelper.isStatic(functionDecl.modifiers) - let isInstanceMember = enclosingTypeName != nil && !isStatic + let isTopLevel = enclosingTypeName == nil + let isInstanceMember = !isTopLevel && !isStatic + if !isTopLevel { + JSMacroHelper.diagnoseMissingJSClass(node: node, for: "JSFunction", in: context) + } + + JSMacroHelper.diagnoseThrowsRequiresJSException( + signature: functionDecl.signature, + on: Syntax(functionDecl), + in: context + ) // Strip backticks from function name (e.g., "`prefix`" -> "prefix") // Backticks are only needed for Swift identifiers, not function names @@ -34,8 +44,7 @@ extension JSFunctionMacro: BodyMacro { let effects = functionDecl.signature.effectSpecifiers let isAsync = effects?.asyncSpecifier != nil - let isThrows = effects?.throwsClause != nil - let prefix = JSMacroHelper.tryAwaitPrefix(isAsync: isAsync, isThrows: isThrows) + let prefix = JSMacroHelper.tryAwaitPrefix(isAsync: isAsync, isThrows: true) let isVoid = JSMacroHelper.isVoidReturn(functionDecl.signature.returnClause?.type) let line = isVoid ? "\(prefix)\(call)" : "return \(prefix)\(call)" @@ -45,11 +54,29 @@ extension JSFunctionMacro: BodyMacro { if let initializerDecl = declaration.as(InitializerDeclSyntax.self) { guard let enclosingTypeName = JSMacroHelper.enclosingTypeName(from: context) else { context.diagnose( - Diagnostic(node: Syntax(declaration), message: JSMacroMessage.unsupportedDeclaration) + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedDeclaration, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "Move this initializer inside a JS wrapper type annotated with @JSClass." + ) + ) + ] + ) ) - return [] + return [CodeBlockItemSyntax(stringLiteral: "fatalError(\"@JSFunction init must be inside a type\")")] } + JSMacroHelper.diagnoseMissingJSClass(node: node, for: "JSFunction", in: context) + JSMacroHelper.diagnoseThrowsRequiresJSException( + signature: initializerDecl.signature, + on: Syntax(initializerDecl), + in: context + ) + let glueName = JSMacroHelper.glueName(baseName: "init", enclosingTypeName: enclosingTypeName) let parameters = initializerDecl.signature.parameterClause.parameters let arguments = JSMacroHelper.parameterNames(parameters) @@ -57,8 +84,7 @@ extension JSFunctionMacro: BodyMacro { let effects = initializerDecl.signature.effectSpecifiers let isAsync = effects?.asyncSpecifier != nil - let isThrows = effects?.throwsClause != nil - let prefix = JSMacroHelper.tryAwaitPrefix(isAsync: isAsync, isThrows: isThrows) + let prefix = JSMacroHelper.tryAwaitPrefix(isAsync: isAsync, isThrows: true) return [ CodeBlockItemSyntax(stringLiteral: "let jsObject = \(prefix)\(call)"), @@ -66,7 +92,50 @@ extension JSFunctionMacro: BodyMacro { ] } - context.diagnose(Diagnostic(node: Syntax(declaration), message: JSMacroMessage.unsupportedDeclaration)) + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedDeclaration, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "Apply @JSFunction to a function or initializer on your @JSClass wrapper type." + ) + ) + ] + ) + ) + return [] + } +} + +extension JSFunctionMacro: PeerMacro { + /// Emits a diagnostic when @JSFunction is applied to a declaration that is not a function or initializer. + /// BodyMacro is only invoked for declarations with optional code blocks (e.g. functions, initializers), + /// so for vars and other decls we need PeerMacro to run and diagnose. + public static func expansion( + of node: AttributeSyntax, + providingPeersOf declaration: some DeclSyntaxProtocol, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + if declaration.is(FunctionDeclSyntax.self) { return [] } + if declaration.is(InitializerDeclSyntax.self) { return [] } + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedDeclaration, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: + "Place @JSFunction on a function or initializer; use @JSGetter/@JSSetter for properties." + ) + ) + ] + ) + ) return [] } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSGetterMacro.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSGetterMacro.swift index b996facfa..a3b9435ea 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSGetterMacro.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSGetterMacro.swift @@ -15,13 +15,30 @@ extension JSGetterMacro: AccessorMacro { let binding = variableDecl.bindings.first, let identifier = binding.pattern.as(IdentifierPatternSyntax.self) else { - context.diagnose(Diagnostic(node: Syntax(declaration), message: JSMacroMessage.unsupportedVariable)) + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedVariable, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "@JSGetter must be attached to a single stored or computed property." + ) + ) + ] + ) + ) return [] } let enclosingTypeName = JSMacroHelper.enclosingTypeName(from: context) let isStatic = JSMacroHelper.isStatic(variableDecl.modifiers) - let isInstanceMember = enclosingTypeName != nil && !isStatic + let isTopLevel = enclosingTypeName == nil + let isInstanceMember = !isTopLevel && !isStatic + if !isTopLevel { + JSMacroHelper.diagnoseMissingJSClass(node: node, for: "JSGetter", in: context) + } // Strip backticks from property name (e.g., "`prefix`" -> "prefix") // Backticks are only needed for Swift identifiers, not function names @@ -60,3 +77,33 @@ extension JSGetterMacro: AccessorMacro { ] } } + +extension JSGetterMacro: PeerMacro { + /// Emits a diagnostic when @JSGetter is applied to a declaration that is not a variable (e.g. a function). + /// AccessorMacro may not be invoked for non-property declarations. For variables with multiple + /// bindings, the compiler emits its own diagnostic; we only diagnose non-variable decls here. + public static func expansion( + of node: AttributeSyntax, + providingPeersOf declaration: some DeclSyntaxProtocol, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + guard declaration.is(VariableDeclSyntax.self) else { + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedVariable, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "@JSGetter must be attached to a single stored or computed property." + ) + ) + ] + ) + ) + return [] + } + return [] + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift index 59fa1c4c2..224462ddb 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSMacroSupport.swift @@ -11,26 +11,45 @@ enum JSMacroMessage: String, DiagnosticMessage { case invalidSetterName = "@JSSetter function name must start with 'set' followed by a property name (e.g., 'setFoo')." case setterRequiresParameter = "@JSSetter function must have at least one parameter." + case setterRequiresThrows = "@JSSetter function must declare throws(JSException)." + case jsFunctionRequiresThrows = "@JSFunction throws must be declared as throws(JSException)." + case requiresJSClass = "JavaScript members must be declared inside a @JSClass struct." + case jsClassRequiresAtLeastInternal = + "@JSClass does not support private/fileprivate access level. Use internal, package, or public." + case jsClassMemberRequiresAtLeastInternal = + "@JSClass requires jsObject and init(unsafelyWrapping:) to be at least internal." var message: String { rawValue } var diagnosticID: MessageID { MessageID(domain: "JavaScriptKitMacros", id: rawValue) } var severity: DiagnosticSeverity { .error } } +struct JSMacroNoteMessage: NoteMessage { + let message: String + var noteID: MessageID { MessageID(domain: "JavaScriptKitMacros", id: message) } +} + +struct JSMacroFixItMessage: FixItMessage { + let message: String + var fixItID: MessageID { MessageID(domain: "JavaScriptKitMacros", id: message) } +} + +enum JSMacroText { + static let jsExceptionPropagation = "@JSFunction must propagate JavaScript errors as JSException." + static let jsSetterExceptionPropagation = "@JSSetter must propagate JavaScript errors as JSException." +} + enum JSMacroHelper { static func enclosingTypeName(from context: some MacroExpansionContext) -> String? { + enclosingTypeSyntax(from: context).flatMap(typeName(of:)) + } + + static func enclosingTypeSyntax(from context: some MacroExpansionContext) -> Syntax? { for syntax in context.lexicalContext { - if let decl = syntax.as(ClassDeclSyntax.self) { - return decl.name.text - } - if let decl = syntax.as(StructDeclSyntax.self) { - return decl.name.text - } - if let decl = syntax.as(EnumDeclSyntax.self) { - return decl.name.text - } - if let decl = syntax.as(ActorDeclSyntax.self) { - return decl.name.text + if syntax.is(ClassDeclSyntax.self) || syntax.is(StructDeclSyntax.self) + || syntax.is(EnumDeclSyntax.self) || syntax.is(ActorDeclSyntax.self) + { + return Syntax(syntax) } } return nil @@ -98,4 +117,155 @@ enum JSMacroHelper { } return name } + + static func capitalizingFirstLetter(_ value: String) -> String { + guard let first = value.first else { return value } + return first.uppercased() + value.dropFirst() + } + + static func hasJSClassAttribute(_ typeSyntax: Syntax) -> Bool { + guard let attributes = attributes(of: typeSyntax) else { return false } + for attribute in attributes.compactMap({ $0.as(AttributeSyntax.self) }) { + let name = attribute.attributeName.trimmedDescription + if name == "JSClass" || name == "@JSClass" { + return true + } + } + return false + } + + static func typeName(of syntax: Syntax) -> String? { + switch syntax.as(SyntaxEnum.self) { + case .structDecl(let decl): return decl.name.text + case .classDecl(let decl): return decl.name.text + case .enumDecl(let decl): return decl.name.text + case .actorDecl(let decl): return decl.name.text + default: return nil + } + } + + private static func attributes(of syntax: Syntax) -> AttributeListSyntax? { + switch syntax.as(SyntaxEnum.self) { + case .structDecl(let decl): return decl.attributes + case .classDecl(let decl): return decl.attributes + case .enumDecl(let decl): return decl.attributes + case .actorDecl(let decl): return decl.attributes + default: return nil + } + } + + static func diagnoseThrowsRequiresJSException( + signature: FunctionSignatureSyntax, + on node: Syntax, + in context: some MacroExpansionContext, + additionalNotes: [Note] = [] + ) { + let throwsClause = signature.effectSpecifiers?.throwsClause + let throwsTypeName = throwsClause?.type?.as(IdentifierTypeSyntax.self)?.name.text + let isJSException = throwsTypeName == "JSException" + let isAllowedGenericError = + throwsClause != nil + && (throwsTypeName == nil || throwsTypeName == "Error" || throwsTypeName == "Swift.Error") + guard !isJSException else { return } + guard !isAllowedGenericError else { return } + + let newThrowsClause = jsExceptionThrowsClause(from: throwsClause) + + let fixIt: FixIt + if let throwsClause = signature.effectSpecifiers?.throwsClause { + fixIt = FixIt( + message: JSMacroFixItMessage(message: "Declare throws(JSException)"), + changes: [.replace(oldNode: Syntax(throwsClause), newNode: Syntax(newThrowsClause))] + ) + } else { + let adjustedParameterClause = signature.parameterClause.with(\.rightParen.trailingTrivia, .spaces(0)) + let newEffects = FunctionEffectSpecifiersSyntax( + asyncSpecifier: signature.effectSpecifiers?.asyncSpecifier, + throwsClause: newThrowsClause + ) + let newSignature = + signature + .with(\.parameterClause, adjustedParameterClause) + .with(\.effectSpecifiers, newEffects) + fixIt = FixIt( + message: JSMacroFixItMessage(message: "Declare throws(JSException)"), + changes: [.replace(oldNode: Syntax(signature), newNode: Syntax(newSignature))] + ) + } + + var notes: [Note] = [ + jsExceptionPropagationNote(on: node) + ] + notes.append(contentsOf: additionalNotes) + + context.diagnose( + Diagnostic( + node: node, + message: JSMacroMessage.jsFunctionRequiresThrows, + notes: notes, + fixIts: [fixIt] + ) + ) + } + + static func diagnoseMissingJSClass( + node: some SyntaxProtocol, + for macroName: String, + in context: some MacroExpansionContext + ) { + guard let typeSyntax = enclosingTypeSyntax(from: context) else { return } + guard !hasJSClassAttribute(typeSyntax) else { return } + context.diagnose(Diagnostic(node: node, message: JSMacroMessage.requiresJSClass)) + } + + static func setterPropertyBase(from parameter: FunctionParameterSyntax?) -> String? { + guard let parameter else { return nil } + let candidateNames = [ + parameter.secondName, + parameter.firstName.tokenKind == .wildcard ? nil : parameter.firstName, + ].compactMap { $0?.text }.filter { $0 != "_" } + if let explicitName = candidateNames.first(where: { name in name != "value" && name != "newValue" }) { + return explicitName + } + if let identifierType = parameter.type.as(IdentifierTypeSyntax.self) { + let typeName = identifierType.name.text + guard let first = typeName.first else { return nil } + return first.lowercased() + typeName.dropFirst() + } + return candidateNames.first + } + + static func suggestedSetterName(rawFunctionName: String, firstParameter: FunctionParameterSyntax?) -> String? { + guard let base = setterPropertyBase(from: firstParameter) else { return nil } + return "set" + capitalizingFirstLetter(base) + } + + /// Build a typed throws(JSException) clause preserving trivia when possible. + static func jsExceptionThrowsClause(from throwsClause: ThrowsClauseSyntax?) -> ThrowsClauseSyntax { + let throwsSpecifier = (throwsClause?.throwsSpecifier ?? .keyword(.throws, leadingTrivia: .space)) + .with(\.trailingTrivia, .spaces(0)) + .with(\.leadingTrivia, throwsClause?.throwsSpecifier.leadingTrivia ?? .space) + let leftParen = throwsClause?.leftParen ?? .leftParenToken() + let rightParen = (throwsClause?.rightParen ?? .rightParenToken()) + .with(\.trailingTrivia, throwsClause?.rightParen?.trailingTrivia ?? .space) + + return ThrowsClauseSyntax( + throwsSpecifier: throwsSpecifier, + leftParen: leftParen, + type: TypeSyntax(IdentifierTypeSyntax(name: .identifier("JSException"))), + rightParen: rightParen + ) + } + + static func jsExceptionPropagationNote( + on node: Syntax, + message: String = JSMacroText.jsExceptionPropagation + ) -> Note { + Note( + node: node, + message: JSMacroNoteMessage( + message: message + ) + ) + } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSSetterMacro.swift b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSSetterMacro.swift index bb9fd1f21..4d32db449 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSMacros/JSSetterMacro.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSMacros/JSSetterMacro.swift @@ -13,25 +13,117 @@ extension JSSetterMacro: BodyMacro { ) throws -> [CodeBlockItemSyntax] { guard let functionDecl = declaration.as(FunctionDeclSyntax.self) else { context.diagnose( - Diagnostic(node: Syntax(declaration), message: JSMacroMessage.unsupportedSetterDeclaration) + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedSetterDeclaration, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "@JSSetter can only be used on methods that set a JavaScript property." + ) + ) + ] + ) ) return [] } let functionName = functionDecl.name.text + let parameters = functionDecl.signature.parameterClause.parameters + let suggestedSetterName = JSMacroHelper.suggestedSetterName( + rawFunctionName: JSMacroHelper.stripBackticks(functionName), + firstParameter: parameters.first + ) + let renameFixIts: [FixIt] + if let name = suggestedSetterName { + let replacement = functionDecl.name.with(\.tokenKind, .identifier(name)) + .with(\.leadingTrivia, functionDecl.name.leadingTrivia) + .with(\.trailingTrivia, functionDecl.name.trailingTrivia) + renameFixIts = [ + FixIt( + message: JSMacroFixItMessage(message: "Rename setter to '\(name)'"), + changes: [.replace(oldNode: Syntax(functionDecl.name), newNode: Syntax(replacement))] + ) + ] + } else { + renameFixIts = [] + } + let addParameterFixIts: [FixIt] = { + let placeholderParameter = FunctionParameterSyntax( + firstName: .wildcardToken(trailingTrivia: .space), + secondName: .identifier("value"), + colon: .colonToken(trailingTrivia: .space), + type: IdentifierTypeSyntax(name: TokenSyntax(.identifier("<#Type#>"), presence: .present)) + ) + let newClause = FunctionParameterClauseSyntax( + leftParen: .leftParenToken(), + parameters: FunctionParameterListSyntax([placeholderParameter]), + rightParen: .rightParenToken(trailingTrivia: .space) + ) + return [ + FixIt( + message: JSMacroFixItMessage(message: "Add a value parameter to the setter"), + changes: [ + .replace( + oldNode: Syntax(functionDecl.signature.parameterClause), + newNode: Syntax(newClause) + ) + ] + ) + ] + }() // Extract property name from setter function name (e.g., "setFoo" -> "foo") // Strip backticks if present (e.g., "set`prefix`" -> "prefix") let rawFunctionName = JSMacroHelper.stripBackticks(functionName) guard rawFunctionName.hasPrefix("set"), rawFunctionName.count > 3 else { - context.diagnose(Diagnostic(node: Syntax(declaration), message: JSMacroMessage.invalidSetterName)) - return [] + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.invalidSetterName, + notes: [ + Note( + node: Syntax(functionDecl.name), + message: JSMacroNoteMessage( + message: "Setter names must start with 'set' followed by the property name." + ) + ) + ], + fixIts: renameFixIts + ) + ) + return [ + CodeBlockItemSyntax( + stringLiteral: + "fatalError(\"@JSSetter function name must start with 'set' followed by a property name\")" + ) + ] } let propertyName = String(rawFunctionName.dropFirst(3)) guard !propertyName.isEmpty else { - context.diagnose(Diagnostic(node: Syntax(declaration), message: JSMacroMessage.invalidSetterName)) - return [] + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.invalidSetterName, + notes: [ + Note( + node: Syntax(functionDecl.name), + message: JSMacroNoteMessage( + message: "Setter names must include the property after 'set'." + ) + ) + ], + fixIts: renameFixIts + ) + ) + return [ + CodeBlockItemSyntax( + stringLiteral: + "fatalError(\"@JSSetter function name must start with 'set' followed by a property name\")" + ) + ] } // Convert first character to lowercase (e.g., "Foo" -> "foo") @@ -39,7 +131,11 @@ extension JSSetterMacro: BodyMacro { let enclosingTypeName = JSMacroHelper.enclosingTypeName(from: context) let isStatic = JSMacroHelper.isStatic(functionDecl.modifiers) - let isInstanceMember = enclosingTypeName != nil && !isStatic + let isTopLevel = enclosingTypeName == nil + let isInstanceMember = !isTopLevel && !isStatic + if !isTopLevel { + JSMacroHelper.diagnoseMissingJSClass(node: node, for: "JSSetter", in: context) + } let glueName = JSMacroHelper.glueName( baseName: baseName, @@ -53,15 +149,70 @@ extension JSSetterMacro: BodyMacro { } // Get the parameter name(s) - setters typically have one parameter - let parameters = functionDecl.signature.parameterClause.parameters guard let firstParam = parameters.first else { - context.diagnose(Diagnostic(node: Syntax(declaration), message: JSMacroMessage.setterRequiresParameter)) - return [] + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.setterRequiresParameter, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "@JSSetter needs a parameter for the value being assigned." + ) + ) + ], + fixIts: addParameterFixIts + ) + ) + return [ + CodeBlockItemSyntax( + stringLiteral: "fatalError(\"@JSSetter function must have at least one parameter\")" + ) + ] } let paramName = firstParam.secondName ?? firstParam.firstName arguments.append(paramName.text) + // Ensure throws(JSException) is declared to match the generated body. + let existingThrowsClause = functionDecl.signature.effectSpecifiers?.throwsClause + let existingThrowsType = existingThrowsClause?.type + .flatMap { $0.as(IdentifierTypeSyntax.self)?.name.text } + let hasTypedJSException = existingThrowsType == "JSException" + let isAllowedGenericError = + existingThrowsClause != nil + && (existingThrowsType == nil || existingThrowsType == "Error" || existingThrowsType == "Swift.Error") + + if !hasTypedJSException && !isAllowedGenericError { + let throwsClause = JSMacroHelper.jsExceptionThrowsClause( + from: existingThrowsClause + ) + let newEffects = + (functionDecl.signature.effectSpecifiers + ?? FunctionEffectSpecifiersSyntax(asyncSpecifier: nil, throwsClause: nil)) + .with(\.throwsClause, throwsClause) + let newSignature = functionDecl.signature.with(\.effectSpecifiers, newEffects) + let fixIt = FixIt( + message: JSMacroFixItMessage(message: "Declare throws(JSException)"), + changes: [.replace(oldNode: Syntax(functionDecl.signature), newNode: Syntax(newSignature))] + ) + let notes: [Note] = [ + JSMacroHelper.jsExceptionPropagationNote( + on: Syntax(functionDecl), + message: JSMacroText.jsSetterExceptionPropagation + ) + ] + context.diagnose( + Diagnostic( + node: Syntax(functionDecl), + message: JSMacroMessage.setterRequiresThrows, + notes: notes, + fixIts: [fixIt] + ) + ) + } + let argsJoined = arguments.joined(separator: ", ") let call = "\(glueName)(\(argsJoined))" @@ -69,3 +220,32 @@ extension JSSetterMacro: BodyMacro { return [CodeBlockItemSyntax(stringLiteral: "try \(call)")] } } + +extension JSSetterMacro: PeerMacro { + /// Emits a diagnostic when @JSSetter is applied to a declaration that is not a function. + /// BodyMacro is only invoked for declarations with optional code blocks (e.g. functions). + public static func expansion( + of node: AttributeSyntax, + providingPeersOf declaration: some DeclSyntaxProtocol, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + guard declaration.is(FunctionDeclSyntax.self) else { + context.diagnose( + Diagnostic( + node: Syntax(declaration), + message: JSMacroMessage.unsupportedSetterDeclaration, + notes: [ + Note( + node: Syntax(declaration), + message: JSMacroNoteMessage( + message: "@JSSetter should be attached to a method that writes a JavaScript property." + ) + ) + ] + ) + ) + return [] + } + return [] + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 33cc94479..dab5fae33 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -126,18 +126,41 @@ public struct UnsafePointerType: Codable, Equatable, Hashable, Sendable { } } +/// JS semantics for optional/nullable types: which value represents "absent". +public enum JSOptionalKind: String, Codable, Equatable, Hashable, Sendable { + case null + case undefined + + /// The JS literal for absence (e.g. in generated glue). + public var absenceLiteral: String { + switch self { + case .null: return "null" + case .undefined: return "undefined" + } + } + + /// JS expression that is true when the value is present. `value` is the variable name. + public func presenceCheck(value: String) -> String { + switch self { + case .null: return "\(value) != null" + case .undefined: return "\(value) !== undefined" + } + } +} + public enum BridgeType: Codable, Equatable, Hashable, Sendable { - case int, uint, float, double, string, bool, jsObject(String?), swiftHeapObject(String), void + case int, uint, float, double, string, bool, jsObject(String?), jsValue, swiftHeapObject(String), void case unsafePointer(UnsafePointerType) - indirect case optional(BridgeType) + indirect case nullable(BridgeType, JSOptionalKind) indirect case array(BridgeType) + indirect case dictionary(BridgeType) case caseEnum(String) case rawValueEnum(String, SwiftEnumRawType) case associatedValueEnum(String) case namespaceEnum(String) case swiftProtocol(String) case swiftStruct(String) - indirect case closure(ClosureSignature) + indirect case closure(ClosureSignature, useJSTypedClosure: Bool) } public enum WasmCoreType: String, Codable, Sendable { @@ -224,6 +247,138 @@ public struct Parameter: Codable, Equatable, Sendable { } } +// MARK: - BridgeType Visitor + +public protocol BridgeTypeVisitor { + mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) +} + +public struct BridgeTypeWalker { + public var visitor: Visitor + + public init(visitor: Visitor) { + self.visitor = visitor + } + + public mutating func walk(_ type: BridgeType) { + switch type { + case .closure(let signature, let useJSTypedClosure): + visitor.visitClosure(signature, useJSTypedClosure: useJSTypedClosure) + for paramType in signature.parameters { + walk(paramType) + } + walk(signature.returnType) + case .nullable(let wrapped, _): + walk(wrapped) + case .array(let element): + walk(element) + case .dictionary(let value): + walk(value) + default: + break + } + } + public mutating func walk(_ parameters: [Parameter]) { + for param in parameters { + walk(param.type) + } + } + public mutating func walk(_ function: ExportedFunction) { + walk(function.parameters) + walk(function.returnType) + } + public mutating func walk(_ constructor: ExportedConstructor) { + walk(constructor.parameters) + } + public mutating func walk(_ skeleton: ExportedSkeleton) { + for function in skeleton.functions { + walk(function) + } + for klass in skeleton.classes { + if let constructor = klass.constructor { + walk(constructor.parameters) + } + for method in klass.methods { + walk(method) + } + for property in klass.properties { + walk(property.type) + } + } + for proto in skeleton.protocols { + for method in proto.methods { + walk(method) + } + for property in proto.properties { + walk(property.type) + } + } + for structDecl in skeleton.structs { + for property in structDecl.properties { + walk(property.type) + } + if let constructor = structDecl.constructor { + walk(constructor.parameters) + } + for method in structDecl.methods { + walk(method) + } + } + for enumDecl in skeleton.enums { + for enumCase in enumDecl.cases { + for associatedValue in enumCase.associatedValues { + walk(associatedValue.type) + } + } + for method in enumDecl.staticMethods { + walk(method) + } + for property in enumDecl.staticProperties { + walk(property.type) + } + } + } + public mutating func walk(_ function: ImportedFunctionSkeleton) { + walk(function.parameters) + walk(function.returnType) + } + public mutating func walk(_ skeleton: ImportedModuleSkeleton) { + for fileSkeleton in skeleton.children { + for getter in fileSkeleton.globalGetters { + walk(getter.type) + } + for setter in fileSkeleton.globalSetters { + walk(setter.type) + } + for function in fileSkeleton.functions { + walk(function) + } + for type in fileSkeleton.types { + if let constructor = type.constructor { + walk(constructor.parameters) + } + for getter in type.getters { + walk(getter.type) + } + for setter in type.setters { + walk(setter.type) + } + for method in type.methods + type.staticMethods { + walk(method) + } + } + } + } + public mutating func walk(_ skeleton: BridgeJSSkeleton) { + if let exported = skeleton.exported { + walk(exported) + } + if let imported = skeleton.imported { + walk(imported) + } + } +} + public struct Effects: Codable, Equatable, Sendable { public var isAsync: Bool public var isThrows: Bool @@ -242,7 +397,7 @@ public enum StaticContext: Codable, Equatable, Sendable { case className(String) case structName(String) case enumName(String) - case namespaceEnum + case namespaceEnum(String) } // MARK: - Struct Skeleton @@ -533,13 +688,9 @@ public struct ExportedProperty: Codable, Equatable, Sendable { public func callName(prefix: String? = nil) -> String { if let staticContext = staticContext { switch staticContext { - case .className(let baseName), .enumName(let baseName), .structName(let baseName): + case .className(let baseName), .enumName(let baseName), .structName(let baseName), + .namespaceEnum(let baseName): return "\(baseName).\(name)" - case .namespaceEnum: - if let namespace = namespace, !namespace.isEmpty { - let namespacePath = namespace.joined(separator: ".") - return "\(namespacePath).\(name)" - } } } if let prefix = prefix { @@ -606,6 +757,10 @@ public struct ExportedSkeleton: Codable { self.protocols.append(contentsOf: other.protocols) assert(self.exposeToGlobal == other.exposeToGlobal) } + + public var isEmpty: Bool { + functions.isEmpty && classes.isEmpty && enums.isEmpty && structs.isEmpty && protocols.isEmpty + } } // MARK: - Imported Skeleton @@ -644,9 +799,14 @@ public struct ImportedFunctionSkeleton: Codable { } public func abiName(context: ImportedTypeSkeleton?) -> String { + return abiName(context: context, operation: nil) + } + + public func abiName(context: ImportedTypeSkeleton?, operation: String?) -> String { return ABINameGenerator.generateImportedABIName( baseName: name, - context: context + context: context, + operation: operation ) } } @@ -756,6 +916,8 @@ public struct ImportedTypeSkeleton: Codable { public let from: JSImportFrom? public let constructor: ImportedConstructorSkeleton? public let methods: [ImportedFunctionSkeleton] + /// Static methods available on the JavaScript constructor. + public var staticMethods: [ImportedFunctionSkeleton] public let getters: [ImportedGetterSkeleton] public let setters: [ImportedSetterSkeleton] public let documentation: String? @@ -765,7 +927,8 @@ public struct ImportedTypeSkeleton: Codable { jsName: String? = nil, from: JSImportFrom? = nil, constructor: ImportedConstructorSkeleton? = nil, - methods: [ImportedFunctionSkeleton], + methods: [ImportedFunctionSkeleton] = [], + staticMethods: [ImportedFunctionSkeleton] = [], getters: [ImportedGetterSkeleton] = [], setters: [ImportedSetterSkeleton] = [], documentation: String? = nil @@ -775,6 +938,7 @@ public struct ImportedTypeSkeleton: Codable { self.from = from self.constructor = constructor self.methods = methods + self.staticMethods = staticMethods self.getters = getters self.setters = setters self.documentation = documentation @@ -827,6 +991,10 @@ public struct ImportedFileSkeleton: Codable { try container.encode(globalSetters, forKey: .globalSetters) } } + + public var isEmpty: Bool { + functions.isEmpty && types.isEmpty && globalGetters.isEmpty && globalSetters.isEmpty + } } public struct ImportedModuleSkeleton: Codable { @@ -837,6 +1005,20 @@ public struct ImportedModuleSkeleton: Codable { } } +// MARK: - Closure signature collection visitor + +public struct ClosureSignatureCollectorVisitor: BridgeTypeVisitor { + public var signatures: Set = [] + + public init(signatures: Set = []) { + self.signatures = signatures + } + + public mutating func visitClosure(_ signature: ClosureSignature, useJSTypedClosure: Bool) { + signatures.insert(signature) + } +} + // MARK: - Unified Skeleton /// Unified skeleton containing both exported and imported API definitions @@ -870,6 +1052,8 @@ extension BridgeType { self = .string case "Bool": self = .bool + case "JSValue": + self = .jsValue case "Void": self = .void case "JSObject": @@ -894,12 +1078,13 @@ extension BridgeType { case .double: return .f64 case .string: return nil case .jsObject: return .i32 + case .jsValue: return nil case .swiftHeapObject: // UnsafeMutableRawPointer is returned as an i32 pointer return .pointer case .unsafePointer: return .pointer - case .optional(_): + case .nullable: return nil case .caseEnum: return .i32 @@ -921,12 +1106,15 @@ extension BridgeType { case .array: // Arrays use stack-based return with length prefix (no direct WASM return type) return nil + case .dictionary: + // Dictionaries use stack-based return with entry count (no direct WASM return type) + return nil } } - /// Returns true if this type is optional + /// Returns true if this type is optional (nullable with null or undefined). public var isOptional: Bool { - if case .optional = self { return true } + if case .nullable = self { return true } return false } @@ -944,6 +1132,8 @@ extension BridgeType { case .jsObject(let name): let typeName = name ?? "JSObject" return "\(typeName.count)\(typeName)C" + case .jsValue: + return "7JSValueV" case .swiftHeapObject(let name): return "\(name.count)\(name)C" case .unsafePointer(let ptr): @@ -963,8 +1153,9 @@ extension BridgeType { return "\(kindCode)\(p.count)\(p)" } return kindCode - case .optional(let wrapped): - return "Sq\(wrapped.mangleTypeName)" + case .nullable(let wrapped, let kind): + let prefix = kind == .null ? "Sq" : "Su" + return "\(prefix)\(wrapped.mangleTypeName)" case .caseEnum(let name), .rawValueEnum(let name, _), .associatedValueEnum(let name), @@ -974,15 +1165,18 @@ extension BridgeType { return "\(name.count)\(name)P" case .swiftStruct(let name): return "\(name.count)\(name)V" - case .closure(let signature): + case .closure(let signature, let useJSTypedClosure): let params = signature.parameters.isEmpty ? "y" : signature.parameters.map { $0.mangleTypeName }.joined() - return "K\(params)_\(signature.returnType.mangleTypeName)" + return "K\(params)_\(signature.returnType.mangleTypeName)\(useJSTypedClosure ? "J" : "")" case .array(let elementType): // Array mangling: "Sa" prefix followed by element type return "Sa\(elementType.mangleTypeName)" + case .dictionary(let valueType): + // Dictionary mangling: "SD" prefix followed by value type (key is always String) + return "SD\(valueType.mangleTypeName)" } } @@ -991,7 +1185,9 @@ extension BridgeType { /// Side channels are needed when the wrapped type cannot be directly returned via WASM, /// or when we need to distinguish null from absent value for certain primitives. public func usesSideChannelForOptionalReturn() -> Bool { - guard case .optional(let wrappedType) = self else { return false } + guard case .nullable(let wrappedType, _) = self else { + return false + } switch wrappedType { case .string, .int, .float, .double, .jsObject, .swiftProtocol: @@ -1010,3 +1206,15 @@ extension BridgeType { } } } + +extension WasmCoreType { + public var swiftReturnPlaceholderStmt: String { + switch self { + case .i32: return "return 0" + case .i64: return "return 0" + case .f32: return "return 0.0" + case .f64: return "return 0.0" + case .pointer: return "return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped" + } + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index f75619489..a71aaee44 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -1,10 +1,17 @@ @preconcurrency import func Foundation.exit @preconcurrency import func Foundation.fputs +@preconcurrency import func Foundation.open +@preconcurrency import func Foundation.strerror @preconcurrency import var Foundation.stderr +@preconcurrency import var Foundation.errno +@preconcurrency import var Foundation.O_WRONLY +@preconcurrency import var Foundation.O_CREAT +@preconcurrency import var Foundation.O_TRUNC @preconcurrency import struct Foundation.URL @preconcurrency import struct Foundation.Data @preconcurrency import struct Foundation.ObjCBool @preconcurrency import class Foundation.JSONEncoder +@preconcurrency import class Foundation.FileHandle @preconcurrency import class Foundation.FileManager @preconcurrency import class Foundation.JSONDecoder @preconcurrency import class Foundation.ProcessInfo @@ -50,9 +57,17 @@ import BridgeJSUtilities static func main() throws { do { - try run() + try Profiling.with(Profiling.make) { + try run() + } } catch { - printStderr("error: \(error)") + if let diagError = error as? BridgeJSCoreDiagnosticError { + diagError.diagnostics.forEach { file, diagnostic in + printStderr(diagnostic.formattedDescription(fileName: file)) + } + } else { + printStderr("error: \(error)") + } exit(1) } } @@ -113,6 +128,7 @@ import BridgeJSUtilities let bridgeJsGlobalDtsPath = targetDirectory.appending(path: "bridge-js.global.d.ts") let hasDts = FileManager.default.fileExists(atPath: bridgeJsDtsPath.path) let hasGlobalDts = FileManager.default.fileExists(atPath: bridgeJsGlobalDtsPath.path) + var generatedMacrosPath: String? = nil if hasDts || hasGlobalDts { guard let tsconfigPath = doubleDashOptions["project"] else { throw BridgeJSToolError("--project option is required when processing .d.ts files") @@ -120,33 +136,60 @@ import BridgeJSUtilities let bridgeJSMacrosPath = outputDirectory.appending(path: "BridgeJS.Macros.swift") let primaryDtsPath = hasDts ? bridgeJsDtsPath.path : bridgeJsGlobalDtsPath.path let globalDtsFiles = (hasDts && hasGlobalDts) ? [bridgeJsGlobalDtsPath.path] : [] - _ = try invokeTS2Swift( - dtsFile: primaryDtsPath, - globalDtsFiles: globalDtsFiles, - tsconfigPath: tsconfigPath, - nodePath: nodePath, - progress: progress, - outputPath: bridgeJSMacrosPath.path - ) + try withSpan("invokeTS2Swift") { + _ = try invokeTS2Swift( + dtsFile: primaryDtsPath, + globalDtsFiles: globalDtsFiles, + tsconfigPath: tsconfigPath, + nodePath: nodePath, + progress: progress, + outputPath: bridgeJSMacrosPath.path + ) + } + generatedMacrosPath = bridgeJSMacrosPath.path + } + + var inputFiles = withSpan("Collecting Swift files") { + return inputSwiftFiles(targetDirectory: targetDirectory, positionalArguments: positionalArguments) } - let inputFiles = inputSwiftFiles(targetDirectory: targetDirectory, positionalArguments: positionalArguments) + // BridgeJS.Macros.swift contains imported declarations (@JSFunction, @JSClass, etc.) that need + // to be processed by SwiftToSkeleton to populate the imported skeleton. The command plugin + // filters out Generated/ files, so we explicitly add it here after generation. + if let macrosPath = generatedMacrosPath, FileManager.default.fileExists(atPath: macrosPath) { + // Only add if not already present (when running directly vs through plugin) + if !inputFiles.contains(macrosPath) { + inputFiles.append(macrosPath) + } + } let swiftToSkeleton = SwiftToSkeleton( progress: progress, moduleName: moduleName, exposeToGlobal: config.exposeToGlobal ) for inputFile in inputFiles.sorted() { - let content = try String(contentsOf: URL(fileURLWithPath: inputFile), encoding: .utf8) - if hasBridgeJSSkipComment(content) { - continue + try withSpan("Parsing \(inputFile)") { + let inputURL = URL(fileURLWithPath: inputFile) + // Skip directories (e.g. .docc catalogs included in target.sourceFiles) + var isDirectory: ObjCBool = false + if FileManager.default.fileExists(atPath: inputFile, isDirectory: &isDirectory), + isDirectory.boolValue + { + return + } + let content = try String(contentsOf: inputURL, encoding: .utf8) + if hasBridgeJSSkipComment(content) { + return + } + + let sourceFile = Parser.parse(source: content) + swiftToSkeleton.addSourceFile(sourceFile, inputFilePath: inputFile) } - - let sourceFile = Parser.parse(source: content) - swiftToSkeleton.addSourceFile(sourceFile, inputFilePath: inputFile) } - let skeleton = try swiftToSkeleton.finalize() + let skeleton = try withSpan("SwiftToSkeleton.finalize") { + return try swiftToSkeleton.finalize() + } var exporter: ExportSwift? if let skeleton = skeleton.exported { @@ -166,10 +209,16 @@ import BridgeJSUtilities } // Generate unified closure support for both import/export to avoid duplicate symbols when concatenating. - let closureSupport = try ClosureCodegen().renderSupport(for: skeleton) + let closureSupport = try withSpan("ClosureCodegen.renderSupport") { + return try ClosureCodegen().renderSupport(for: skeleton) + } - let importResult = try importer?.finalize() - let exportResult = try exporter?.finalize() + let importResult = try withSpan("ImportTS.finalize") { + return try importer?.finalize() + } + let exportResult = try withSpan("ExportSwift.finalize") { + return try exporter?.finalize() + } // Combine and write unified Swift output let outputSwiftURL = outputDirectory.appending(path: "BridgeJS.swift") @@ -177,26 +226,30 @@ import BridgeJSUtilities let outputSwift = combineGeneratedSwift(combinedSwift) let shouldWrite = doubleDashOptions["always-write"] == "true" || !outputSwift.isEmpty if shouldWrite { + try withSpan("Writing output Swift") { + try FileManager.default.createDirectory( + at: outputSwiftURL.deletingLastPathComponent(), + withIntermediateDirectories: true, + attributes: nil + ) + try writeIfChanged(outputSwift, to: outputSwiftURL) + } + } + + // Write unified skeleton + let outputSkeletonURL = outputDirectory.appending(path: "JavaScript/BridgeJS.json") + try withSpan("Writing output skeleton") { try FileManager.default.createDirectory( - at: outputSwiftURL.deletingLastPathComponent(), + at: outputSkeletonURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil ) - try outputSwift.write(to: outputSwiftURL, atomically: true, encoding: .utf8) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let skeletonData = try encoder.encode(skeleton) + try writeIfChanged(skeletonData, to: outputSkeletonURL) } - // Write unified skeleton - let outputSkeletonURL = outputDirectory.appending(path: "JavaScript/BridgeJS.json") - try FileManager.default.createDirectory( - at: outputSkeletonURL.deletingLastPathComponent(), - withIntermediateDirectories: true, - attributes: nil - ) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let skeletonData = try encoder.encode(skeleton) - try skeletonData.write(to: outputSkeletonURL) - if skeleton.exported != nil || skeleton.imported != nil { progress.print("Generated BridgeJS code") } @@ -236,6 +289,18 @@ private func hasBridgeJSSkipComment(_ content: String) -> Bool { BridgeJSGeneratedFile.hasSkipComment(content) } +private func writeIfChanged(_ content: String, to url: URL) throws { + let existing = try? String(contentsOf: url, encoding: .utf8) + guard existing != content else { return } + try content.write(to: url, atomically: true, encoding: .utf8) +} + +private func writeIfChanged(_ data: Data, to url: URL) throws { + let existing = try? Data(contentsOf: url) + guard existing != data else { return } + try data.write(to: url) +} + private func combineGeneratedSwift(_ pieces: [String]) -> String { let trimmedPieces = pieces @@ -279,6 +344,21 @@ private func inputSwiftFiles(targetDirectory: URL, positionalArguments: [String] return positionalArguments } +extension Profiling { + static func make() -> Profiling? { + guard let outputPath = ProcessInfo.processInfo.environment["BRIDGEJS_PROFILING"] else { + return nil + } + let fd = open(outputPath, O_WRONLY | O_CREAT | O_TRUNC, 0o644) + guard fd >= 0 else { + let error = String(cString: strerror(errno)) + fatalError("Failed to open profiling output file \(outputPath): \(error)") + } + let output = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + return Profiling.traceEvent(output: { output.write($0.data(using: .utf8) ?? Data()) }) + } +} + // MARK: - Minimal Argument Parsing struct OptionRule { diff --git a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift index 2791aa5be..68c07f225 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSUtilities/Utilities.swift @@ -27,3 +27,56 @@ public enum BridgeJSGeneratedFile { """ } } + +/// A printer for code fragments. +public final class CodeFragmentPrinter { + public private(set) var lines: [String] = [] + private var indentLevel: Int = 0 + + public init(header: String = "") { + self.lines.append(contentsOf: header.split(separator: "\n").map { String($0) }) + } + + public func nextLine() { + lines.append("") + } + + public func write(_ line: S) { + if line.isEmpty { + // Empty lines should not have trailing spaces + lines.append("") + return + } + lines.append(String(repeating: " ", count: indentLevel * 4) + String(line)) + } + + public func write(lines: [String]) { + for line in lines { + write(line) + } + } + + public func write(contentsOf printer: CodeFragmentPrinter) { + self.write(lines: printer.lines) + } + + public func write(multilineString: String) { + for line in multilineString.split(separator: "\n") { + write(line) + } + } + + public func indent() { + indentLevel += 1 + } + + public func unindent() { + indentLevel -= 1 + } + + public func indent(_ body: () throws -> Void) rethrows { + indentLevel += 1 + try body() + indentLevel -= 1 + } +} diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/package.json b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/package.json index d6b34558d..0c8a50c48 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/package.json +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/package.json @@ -5,5 +5,9 @@ }, "bin": { "ts2swift": "./bin/ts2swift.js" + }, + "scripts": { + "test": "vitest run", + "tsc": "tsc --noEmit" } } diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js index 645be1f5a..17086e92e 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/cli.js @@ -1,13 +1,14 @@ // @ts-check import * as fs from 'fs'; -import { TypeProcessor } from './processor.js'; +import os from 'os'; +import path from 'path'; import { parseArgs } from 'util'; import ts from 'typescript'; -import path from 'path'; +import { TypeProcessor } from './processor.js'; class DiagnosticEngine { /** - * @param {string} level + * @param {keyof typeof DiagnosticEngine.LEVELS} level */ constructor(level) { const levelInfo = DiagnosticEngine.LEVELS[level]; @@ -73,7 +74,106 @@ class DiagnosticEngine { } function printUsage() { - console.error('Usage: ts2swift -p [--global ]... [-o output.swift]'); + console.error(`Usage: ts2swift [options] + + Path to a .d.ts file, or "-" to read from stdin + +Options: + -o, --output Write Swift to . Use "-" for stdout (default). + -p, --project Path to tsconfig.json (default: tsconfig.json). + --global Add a .d.ts as a global declaration file (repeatable). + --log-level One of: verbose, info, warning, error (default: info). + -h, --help Show this help. + +Examples: + ts2swift lib.d.ts + ts2swift lib.d.ts -o Generated.swift + ts2swift lib.d.ts -p ./tsconfig.build.json -o Sources/Bridge/API.swift + cat lib.d.ts | ts2swift - -o Generated.swift + ts2swift lib.d.ts --global dom.d.ts --global lib.d.ts +`); +} + +/** + * Run ts2swift for a single input file (programmatic API, no process I/O). + * @param {string[]} filePaths - Paths to the .d.ts files + * @param {{ tsconfigPath: string, logLevel?: keyof typeof DiagnosticEngine.LEVELS, globalFiles?: string[], diagnosticEngine?: DiagnosticEngine }} options + * @returns {string} Generated Swift source + * @throws {Error} on parse/type-check errors (diagnostics are included in the message) + */ +export function run(filePaths, options) { + const { tsconfigPath, logLevel = 'info', globalFiles = [], diagnosticEngine } = options; + const engine = diagnosticEngine ?? new DiagnosticEngine(logLevel); + + const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile); + const configParseResult = ts.parseJsonConfigFileContent( + configFile.config, + ts.sys, + path.dirname(path.resolve(tsconfigPath)) + ); + + if (configParseResult.errors.length > 0) { + const message = ts.formatDiagnosticsWithColorAndContext(configParseResult.errors, { + getCanonicalFileName: (fileName) => fileName, + getNewLine: () => ts.sys.newLine, + getCurrentDirectory: () => ts.sys.getCurrentDirectory(), + }); + throw new Error(`TypeScript config/parse errors:\n${message}`); + } + + const program = TypeProcessor.createProgram([...filePaths, ...globalFiles], configParseResult.options); + + const formatDiagnostics = (diagnostics, kind) => { + if (diagnostics.length === 0) return null; + const message = ts.formatDiagnosticsWithColorAndContext(diagnostics, { + getCanonicalFileName: (fileName) => fileName, + getNewLine: () => ts.sys.newLine, + getCurrentDirectory: () => ts.sys.getCurrentDirectory(), + }); + return `${kind} errors:\n${message}`; + }; + + const syntaxErrors = formatDiagnostics(program.getSyntacticDiagnostics(), "TypeScript syntax"); + if (syntaxErrors) { + throw new Error(syntaxErrors); + } + + const optionErrors = formatDiagnostics(program.getOptionsDiagnostics(), "TypeScript option"); + if (optionErrors) { + throw new Error(optionErrors); + } + + const semanticErrors = formatDiagnostics(program.getSemanticDiagnostics(), "TypeScript semantic"); + if (semanticErrors) { + throw new Error(semanticErrors); + } + + const prelude = [ + "// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit,", + "// DO NOT EDIT.", + "//", + "// To update this file, just rebuild your project or run", + "// `swift package bridge-js`.", + "", + "@_spi(BridgeJS) import JavaScriptKit", + "", + "", + ].join("\n"); + + /** @type {string[]} */ + const bodies = []; + const globalFileSet = new Set(globalFiles); + for (const inputPath of [...filePaths, ...globalFiles]) { + const processor = new TypeProcessor(program.getTypeChecker(), engine, { + defaultImportFromGlobal: globalFileSet.has(inputPath), + }); + const result = processor.processTypeDeclarations(program, inputPath); + const body = result.content.trim(); + if (body.length > 0) bodies.push(body); + } + + const hasAny = bodies.length > 0; + return hasAny ? prelude + bodies.join("\n\n") + "\n" : ""; } /** @@ -82,7 +182,6 @@ function printUsage() { * @returns {void} */ export function main(args) { - // Parse command line arguments const options = parseArgs({ args, options: { @@ -102,80 +201,75 @@ export function main(args) { type: 'string', default: 'info', }, + help: { + type: 'boolean', + short: 'h', + }, }, allowPositionals: true }) - if (options.positionals.length !== 1) { + if (options.values.help) { printUsage(); - process.exit(1); + process.exit(0); } - const tsconfigPath = options.values.project; - if (!tsconfigPath) { + if (options.positionals.length !== 1) { printUsage(); process.exit(1); } - const filePath = options.positionals[0]; - const diagnosticEngine = new DiagnosticEngine(options.values["log-level"] || "info"); - - diagnosticEngine.print("verbose", `Processing ${filePath}...`); - - // Create TypeScript program and process declarations - const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile); - const configParseResult = ts.parseJsonConfigFileContent( - configFile.config, - ts.sys, - path.dirname(path.resolve(tsconfigPath)) - ); + /** @type {string[]} */ + let filePaths = options.positionals; + /** @type {(() => void)[]} cleanup functions to run after completion */ + const cleanups = []; - if (configParseResult.errors.length > 0) { - diagnosticEngine.tsDiagnose(configParseResult.errors); - process.exit(1); + if (filePaths[0] === '-') { + const content = fs.readFileSync(0, 'utf-8'); + const stdinTempPath = path.join(os.tmpdir(), `ts2swift-stdin-${process.pid}-${Date.now()}.d.ts`); + fs.writeFileSync(stdinTempPath, content); + cleanups.push(() => fs.unlinkSync(stdinTempPath)); + filePaths = [stdinTempPath]; } + const logLevel = /** @type {keyof typeof DiagnosticEngine.LEVELS} */ ((() => { + const logLevel = options.values["log-level"] || "info"; + if (!Object.keys(DiagnosticEngine.LEVELS).includes(logLevel)) { + console.error(`Invalid log level: ${logLevel}. Valid levels are: ${Object.keys(DiagnosticEngine.LEVELS).join(", ")}`); + process.exit(1); + } + return logLevel; + })()); + const globalFiles = options.values.global || []; + const tsconfigPath = options.values.project || "tsconfig.json"; - /** @type {string[]} */ - const globalFiles = Array.isArray(options.values.global) - ? options.values.global - : (options.values.global ? [options.values.global] : []); - - const program = TypeProcessor.createProgram([filePath, ...globalFiles], configParseResult.options); - const diagnostics = program.getSemanticDiagnostics(); - if (diagnostics.length > 0) { - diagnosticEngine.tsDiagnose(diagnostics); + const diagnosticEngine = new DiagnosticEngine(logLevel); + diagnosticEngine.print("verbose", `Processing ${filePaths.join(", ")}`); + + let swiftOutput; + try { + swiftOutput = run(filePaths, { tsconfigPath, logLevel, globalFiles, diagnosticEngine }); + } catch (/** @type {unknown} */ err) { + if (err instanceof Error) { + diagnosticEngine.print("error", err.message); + } else { + diagnosticEngine.print("error", String(err)); + } process.exit(1); + } finally { + for (const cleanup of cleanups) { + cleanup(); + } } - const prelude = [ - "// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit,", - "// DO NOT EDIT.", - "//", - "// To update this file, just rebuild your project or run", - "// `swift package bridge-js`.", - "", - "@_spi(Experimental) import JavaScriptKit", - "", - "", - ].join("\n"); - - /** @type {string[]} */ - const bodies = []; - const globalFileSet = new Set(globalFiles); - for (const inputPath of [filePath, ...globalFiles]) { - const processor = new TypeProcessor(program.getTypeChecker(), diagnosticEngine, { - defaultImportFromGlobal: globalFileSet.has(inputPath), - }); - const result = processor.processTypeDeclarations(program, inputPath); - const body = result.content.trim(); - if (body.length > 0) bodies.push(body); + if (swiftOutput.length === 0) { + diagnosticEngine.print( + "warning", + "No Swift declarations were generated. This usually means the .d.ts contained constructs that BridgeJS cannot import." + ); } - - const hasAny = bodies.length > 0; - const swiftOutput = hasAny ? prelude + bodies.join("\n\n") + "\n" : ""; - - if (options.values.output) { - if (hasAny) { + // Write to file or stdout + if (options.values.output && options.values.output !== "-") { + if (swiftOutput.length > 0) { fs.mkdirSync(path.dirname(options.values.output), { recursive: true }); fs.writeFileSync(options.values.output, swiftOutput); } diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js index e48510466..9617a5261 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/src/processor.js @@ -20,14 +20,17 @@ import ts from 'typescript'; export class TypeProcessor { /** * Create a TypeScript program from a d.ts file - * @param {string} filePath - Path to the d.ts file + * @param {string[]} filePaths - Paths to the d.ts file * @param {ts.CompilerOptions} options - Compiler options * @returns {ts.Program} TypeScript program object */ static createProgram(filePaths, options) { const host = ts.createCompilerHost(options); - const roots = Array.isArray(filePaths) ? filePaths : [filePaths]; - return ts.createProgram(roots, options, host); + return ts.createProgram(filePaths, { + ...options, + noCheck: true, + skipLibCheck: true, + }, host); } /** @@ -35,14 +38,7 @@ export class TypeProcessor { * @param {DiagnosticEngine} diagnosticEngine - Diagnostic engine */ constructor(checker, diagnosticEngine, options = { - inheritIterable: true, - inheritArraylike: true, - inheritPromiselike: true, - addAllParentMembersToClass: true, - replaceAliasToFunction: true, - replaceRankNFunction: true, - replaceNewableFunction: true, - noExtendsInTyprm: false, + defaultImportFromGlobal: false, }) { this.checker = checker; this.diagnosticEngine = diagnosticEngine; @@ -58,6 +54,11 @@ export class TypeProcessor { this.emittedEnumNames = new Set(); /** @type {Set} */ this.emittedStructuredTypeNames = new Set(); + /** @type {Set} */ + this.emittedStringLiteralUnionNames = new Set(); + + /** @type {Set} */ + this.warnedExportNodes = new Set(); /** @type {Set} */ this.visitedDeclarationKeys = new Set(); @@ -149,19 +150,27 @@ export class TypeProcessor { for (const [type, node] of this.seenTypes) { this.seenTypes.delete(type); + const stringLiteralUnion = this.getStringLiteralUnionLiterals(type); + if (stringLiteralUnion && stringLiteralUnion.length > 0) { + this.emitStringLiteralUnion(type, node); + continue; + } if (this.isEnumType(type)) { this.visitEnumType(type, node); continue; } - const typeString = this.checker.typeToString(type); const members = type.getProperties(); if (members) { - this.visitStructuredType(typeString, members); + this.visitStructuredType(type, node, members); } } }); - } catch (error) { - this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${error.message}`); + } catch (/** @type {unknown} */ error) { + if (error instanceof Error) { + this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${error.message}`); + } else { + this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${String(error)}`); + } } } @@ -186,6 +195,8 @@ export class TypeProcessor { this.visitEnumDeclaration(node); } else if (ts.isExportDeclaration(node)) { this.visitExportDeclaration(node); + } else if (ts.isExportAssignment(node)) { + this.visitExportAssignment(node); } } @@ -233,6 +244,7 @@ export class TypeProcessor { } } else { // export * as ns from "..." is not currently supported by BridgeJS imports. + this.warnExportSkip(node, "Skipping namespace re-export (export * as ns) which is not supported"); return; } @@ -248,6 +260,19 @@ export class TypeProcessor { this.visitNode(declaration); } } + + if (targetSymbols.length === 0) { + this.warnExportSkip(node, "Export declaration resolved to no symbols; nothing was generated"); + } + } + + /** + * Handle `export default foo;` style assignments. + * @param {ts.ExportAssignment} node + */ + visitExportAssignment(node) { + // BridgeJS does not currently model default export assignments (they may point to expressions). + this.warnExportSkip(node, "Skipping export assignment (export default ...) which is not supported"); } /** @@ -262,24 +287,46 @@ export class TypeProcessor { if (!isExported) return; const fromArg = this.renderDefaultJSImportFromArgument(); + const isConst = (node.declarationList.flags & ts.NodeFlags.Const) !== 0; for (const decl of node.declarationList.declarations) { - if (!ts.isIdentifier(decl.name)) continue; + if (!ts.isIdentifier(decl.name)) { + this.warnExportSkip(decl, "Skipping exported variable with a non-identifier name"); + continue; + } const jsName = decl.name.text; const swiftName = this.swiftTypeName(jsName); const swiftVarName = this.renderIdentifier(swiftName); const type = this.checker.getTypeAtLocation(decl); - const swiftType = this.visitType(type, decl); /** @type {string[]} */ const args = []; const jsNameArg = this.renderOptionalJSNameArg(jsName, swiftName); if (jsNameArg) args.push(jsNameArg); if (fromArg) args.push(fromArg); + const callSignatures = type.getCallSignatures(); + + if (isConst && callSignatures.length > 0) { + const signature = callSignatures[0]; + const parameters = signature.getParameters(); + const parameterNameMap = this.buildParameterNameMap(parameters); + const params = this.renderParameters(parameters, decl); + const returnType = this.visitType(signature.getReturnType(), decl); + const effects = this.renderEffects({ isAsync: false }); + const annotation = this.renderMacroAnnotation("JSFunction", args); + + this.emitDocComment(decl, { indent: "", parameterNameMap }); + this.swiftLines.push(`${annotation} func ${swiftVarName}(${params}) ${effects} -> ${returnType}`); + this.swiftLines.push(""); + continue; + } + + const swiftType = this.visitType(type, decl); const annotation = this.renderMacroAnnotation("JSGetter", args); + this.emitDocComment(decl, { indent: "" }); this.swiftLines.push(`${annotation} var ${swiftVarName}: ${swiftType}`); this.swiftLines.push(""); } @@ -296,13 +343,90 @@ export class TypeProcessor { return (symbol.flags & ts.SymbolFlags.Enum) !== 0; } + dedupeSwiftEnumCaseNames(items) { + const seen = new Map(); + return items.map(item => { + const count = seen.get(item.name) ?? 0; + seen.set(item.name, count + 1); + if (count === 0) return item; + return { ...item, name: `${item.name}_${count + 1}` }; + }); + } + + /** + * Extract string literal values if the type is a union containing only string literals. + * Returns null when any member is not a string literal. + * @param {ts.Type} type + * @returns {string[] | null} + * @private + */ + getStringLiteralUnionLiterals(type) { + if ((type.flags & ts.TypeFlags.Union) === 0) return null; + const symbol = type.getSymbol() ?? type.aliasSymbol; + // Skip enums so we don't double-generate real enum declarations. + if (symbol && (symbol.flags & ts.SymbolFlags.Enum) !== 0) { + return null; + } + /** @type {ts.UnionType} */ + // @ts-ignore + const unionType = type; + /** @type {string[]} */ + const literals = []; + const seen = new Set(); + for (const member of unionType.types) { + if ((member.flags & ts.TypeFlags.StringLiteral) === 0) { + return null; + } + // @ts-ignore value exists for string literal types + const value = String(member.value); + if (seen.has(value)) continue; + seen.add(value); + literals.push(value); + } + return literals; + } + + /** + * @param {ts.Type} type + * @param {ts.Node} diagnosticNode + * @private + */ + emitStringLiteralUnion(type, diagnosticNode) { + const typeName = this.deriveTypeName(type); + if (!typeName) return; + if (this.emittedStringLiteralUnionNames.has(typeName)) return; + this.emittedStringLiteralUnionNames.add(typeName); + + const literals = this.getStringLiteralUnionLiterals(type); + if (!literals || literals.length === 0) return; + + const swiftEnumName = this.renderTypeIdentifier(typeName); + /** @type {{ name: string, raw: string }[]} */ + const members = literals.map(raw => ({ name: makeValidSwiftIdentifier(String(raw), { emptyFallback: "_case" }), raw: String(raw) })); + const deduped = this.dedupeSwiftEnumCaseNames(members); + + this.emitDocComment(diagnosticNode, { indent: "" }); + this.swiftLines.push(`enum ${swiftEnumName}: String {`); + for (const { name, raw } of deduped) { + this.swiftLines.push(` case ${this.renderIdentifier(name)} = "${raw.replaceAll("\"", "\\\"")}"`); + } + this.swiftLines.push("}"); + this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {}`); + this.swiftLines.push(""); + } + /** * @param {ts.EnumDeclaration} node * @private */ visitEnumDeclaration(node) { const name = node.name?.text; - if (!name) return; + if (!name) { + if (this.isExported(node)) { + this.warnExportSkip(node, "Skipping exported enum without a name"); + } + return; + } this.emitEnumFromDeclaration(name, node, node); } @@ -334,6 +458,7 @@ export class TypeProcessor { this.emittedEnumNames.add(enumName); const members = decl.members ?? []; + this.emitDocComment(decl, { indent: "" }); if (members.length === 0) { this.diagnosticEngine.print("warning", `Empty enum is not supported: ${enumName}`, diagnosticNode); this.swiftLines.push(`typealias ${this.renderIdentifier(enumName)} = String`); @@ -383,7 +508,7 @@ export class TypeProcessor { canBeIntEnum = false; } const swiftEnumName = this.renderTypeIdentifier(enumName); - const dedupeNames = (items) => { + const dedupeNames = (/** @type {{ name: string, raw: string | number }[]} */ items) => { const seen = new Map(); return items.map(item => { const count = seen.get(item.name) ?? 0; @@ -396,10 +521,14 @@ export class TypeProcessor { if (canBeStringEnum && stringMembers.length > 0) { this.swiftLines.push(`enum ${swiftEnumName}: String {`); for (const { name, raw } of dedupeNames(stringMembers)) { + if (typeof raw !== "string") { + this.diagnosticEngine.print("warning", `Invalid string literal: ${raw}`, diagnosticNode); + continue; + } this.swiftLines.push(` case ${this.renderIdentifier(name)} = "${raw.replaceAll("\"", "\\\\\"")}"`); } this.swiftLines.push("}"); - this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload {}`); + this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {}`); this.swiftLines.push(""); return; } @@ -410,7 +539,7 @@ export class TypeProcessor { this.swiftLines.push(` case ${this.renderIdentifier(name)} = ${raw}`); } this.swiftLines.push("}"); - this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload {}`); + this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {}`); this.swiftLines.push(""); return; } @@ -430,7 +559,12 @@ export class TypeProcessor { * @private */ visitFunctionDeclaration(node) { - if (!node.name) return; + if (!node.name) { + if (this.isExported(node)) { + this.warnExportSkip(node, "Skipping exported function without a name"); + } + return; + } const jsName = node.name.text; const swiftName = this.swiftTypeName(jsName); const fromArg = this.renderDefaultJSImportFromArgument(); @@ -444,54 +578,194 @@ export class TypeProcessor { const signature = this.checker.getSignatureFromDeclaration(node); if (!signature) return; - const params = this.renderParameters(signature.getParameters(), node); + const parameters = signature.getParameters(); + const parameterNameMap = this.buildParameterNameMap(parameters); + const params = this.renderParameters(parameters, node); const returnType = this.visitType(signature.getReturnType(), node); const effects = this.renderEffects({ isAsync: false }); const swiftFuncName = this.renderIdentifier(swiftName); + this.emitDocComment(node, { parameterNameMap }); this.swiftLines.push(`${annotation} func ${swiftFuncName}(${params}) ${effects} -> ${returnType}`); this.swiftLines.push(""); } /** - * Get the full JSDoc text from a node - * @param {ts.Node} node - The node to get the JSDoc text from - * @returns {string | undefined} The full JSDoc text + * Convert a JSDoc comment node content to plain text. + * @param {string | ts.NodeArray | undefined} comment + * @returns {string} + * @private */ - getFullJSDocText(node) { - const docs = ts.getJSDocCommentsAndTags(node); - const parts = []; - for (const doc of docs) { - if (ts.isJSDoc(doc)) { - parts.push(doc.comment ?? ""); + renderJSDocText(comment) { + if (!comment) return ""; + if (typeof comment === "string") return comment; + let result = ""; + for (const part of comment) { + if (typeof part === "string") { + result += part; + continue; + } + // JSDocText/JSDocLink both have a `text` field + // https://github.com/microsoft/TypeScript/blob/main/src/compiler/types.ts + // @ts-ignore + if (typeof part.text === "string") { + // @ts-ignore + result += part.text; + continue; + } + if (typeof part.getText === "function") { + result += part.getText(); } } - if (parts.length === 0) return undefined; - return parts.join("\n"); + return result; } - /** @returns {string} */ - renderDefaultJSImportFromArgument() { - if (this.defaultImportFromGlobal) return "from: .global"; - return ""; + /** + * Split documentation text into lines suitable for DocC rendering. + * @param {string} text + * @returns {string[]} + * @private + */ + splitDocumentationText(text) { + if (!text) return []; + return text.split(/\r?\n/).map(line => line.trimEnd()); } /** - * Render constructor parameters - * @param {ts.ConstructorDeclaration} node - * @returns {string} Rendered parameters + * @param {string[]} lines + * @returns {boolean} * @private */ - renderConstructorParameters(node) { - const signature = this.checker.getSignatureFromDeclaration(node); - if (!signature) return ""; + hasMeaningfulLine(lines) { + return lines.some(line => line.trim().length > 0); + } + + /** + * Render Swift doc comments from a node's JSDoc, including parameter/return tags. + * @param {ts.Node} node + * @param {{ indent?: string, parameterNameMap?: Map }} options + * @private + */ + emitDocComment(node, options = {}) { + const indent = options.indent ?? ""; + const parameterNameMap = options.parameterNameMap ?? new Map(); + + /** @type {string[]} */ + const descriptionLines = []; + for (const doc of ts.getJSDocCommentsAndTags(node)) { + if (!ts.isJSDoc(doc)) continue; + const text = this.renderJSDocText(doc.comment); + if (text) { + descriptionLines.push(...this.splitDocumentationText(text)); + } + } + + /** @type {Array<{ name: string, lines: string[] }>} */ + const parameterDocs = []; + const supportsParameters = ( + ts.isFunctionLike(node) || + ts.isMethodSignature(node) || + ts.isCallSignatureDeclaration(node) || + ts.isConstructSignatureDeclaration(node) + ); + /** @type {ts.JSDocReturnTag | undefined} */ + let returnTag = undefined; + if (supportsParameters) { + for (const tag of ts.getJSDocTags(node)) { + if (ts.isJSDocParameterTag(tag)) { + const tsName = tag.name.getText(); + const name = parameterNameMap.get(tsName) ?? this.renderIdentifier(tsName); + const text = this.renderJSDocText(tag.comment); + const lines = this.splitDocumentationText(text); + parameterDocs.push({ name, lines }); + } else if (!returnTag && ts.isJSDocReturnTag(tag)) { + returnTag = tag; + } + } + } + + const returnLines = returnTag ? this.splitDocumentationText(this.renderJSDocText(returnTag.comment)) : []; + const hasDescription = this.hasMeaningfulLine(descriptionLines); + const hasParameters = parameterDocs.length > 0; + const hasReturns = returnTag !== undefined; + + if (!hasDescription && !hasParameters && !hasReturns) { + return; + } + + /** @type {string[]} */ + const docLines = []; + if (hasDescription) { + docLines.push(...descriptionLines); + } + + if (hasDescription && (hasParameters || hasReturns)) { + docLines.push(""); + } + + if (hasParameters) { + docLines.push("- Parameters:"); + for (const param of parameterDocs) { + const hasParamDescription = this.hasMeaningfulLine(param.lines); + const [firstParamLine, ...restParamLines] = param.lines; + if (hasParamDescription) { + docLines.push(` - ${param.name}: ${firstParamLine}`); + for (const line of restParamLines) { + docLines.push(` ${line}`); + } + } else { + docLines.push(` - ${param.name}:`); + } + } + } - return this.renderParameters(signature.getParameters(), node); + if (hasReturns) { + const hasReturnDescription = this.hasMeaningfulLine(returnLines); + const [firstReturnLine, ...restReturnLines] = returnLines; + if (hasReturnDescription) { + docLines.push(`- Returns: ${firstReturnLine}`); + for (const line of restReturnLines) { + docLines.push(` ${line}`); + } + } else { + docLines.push("- Returns:"); + } + } + + const prefix = `${indent}///`; + for (const line of docLines) { + if (line.length === 0) { + this.swiftLines.push(prefix); + } else { + this.swiftLines.push(`${prefix} ${line}`); + } + } } /** + * Build a map from TypeScript parameter names to rendered Swift identifiers. + * @param {ts.Symbol[]} parameters + * @returns {Map} + * @private + */ + buildParameterNameMap(parameters) { + const map = new Map(); + for (const parameter of parameters) { + map.set(parameter.name, this.renderIdentifier(parameter.name)); + } + return map; + } + + /** @returns {string} */ + renderDefaultJSImportFromArgument() { + if (this.defaultImportFromGlobal) return "from: .global"; + return ""; + } + + /** + * Visit a property declaration and extract metadata * @param {ts.PropertyDeclaration | ts.PropertySignature} node - * @returns {{ jsName: string, swiftName: string, type: string, isReadonly: boolean, documentation: string | undefined } | null} + * @returns {{ jsName: string, swiftName: string, type: string, isReadonly: boolean, isStatic: boolean } | null} */ visitPropertyDecl(node) { if (!node.name) return null; @@ -511,8 +785,8 @@ export class TypeProcessor { const type = this.checker.getTypeAtLocation(node) const swiftType = this.visitType(type, node); const isReadonly = node.modifiers?.some(m => m.kind === ts.SyntaxKind.ReadonlyKeyword) ?? false; - const documentation = this.getFullJSDocText(node); - return { jsName, swiftName, type: swiftType, isReadonly, documentation }; + const isStatic = node.modifiers?.some(m => m.kind === ts.SyntaxKind.StaticKeyword) ?? false; + return { jsName, swiftName, type: swiftType, isReadonly, isStatic }; } /** @@ -532,7 +806,12 @@ export class TypeProcessor { * @private */ visitClassDecl(node) { - if (!node.name) return; + if (!node.name) { + if (this.isExported(node)) { + this.warnExportSkip(node, "Skipping exported class without a name"); + } + return; + } const jsName = node.name.text; if (this.emittedStructuredTypeNames.has(jsName)) return; @@ -547,6 +826,7 @@ export class TypeProcessor { if (fromArg) args.push(fromArg); const annotation = this.renderMacroAnnotation("JSClass", args); const className = this.renderIdentifier(swiftName); + this.emitDocComment(node, { indent: "" }); this.swiftLines.push(`${annotation} struct ${className} {`); // Process members in declaration order @@ -596,11 +876,15 @@ export class TypeProcessor { /** * Visit a structured type (interface) and render Swift code - * @param {string} name + * @param {ts.Type} type + * @param {ts.Node} diagnosticNode * @param {ts.Symbol[]} members * @private */ - visitStructuredType(name, members) { + visitStructuredType(type, diagnosticNode, members) { + const symbol = type.aliasSymbol ?? type.getSymbol(); + const name = type.aliasSymbol?.name ?? symbol?.name ?? this.checker.typeToString(type); + if (!name) return; if (this.emittedStructuredTypeNames.has(name)) return; this.emittedStructuredTypeNames.add(name); @@ -611,17 +895,22 @@ export class TypeProcessor { if (jsNameArg) args.push(jsNameArg); const annotation = this.renderMacroAnnotation("JSClass", args); const typeName = this.renderIdentifier(swiftName); + const docNode = type.aliasSymbol?.getDeclarations()?.[0] ?? symbol?.getDeclarations()?.[0] ?? diagnosticNode; + if (docNode) { + this.emitDocComment(docNode, { indent: "" }); + } this.swiftLines.push(`${annotation} struct ${typeName} {`); // Collect all declarations with their positions to preserve order /** @type {Array<{ decl: ts.Node, symbol: ts.Symbol, position: number }>} */ const allDecls = []; - for (const symbol of members) { - for (const decl of symbol.getDeclarations() ?? []) { + const typeMembers = members ?? type.getProperties() ?? []; + for (const memberSymbol of typeMembers) { + for (const decl of memberSymbol.getDeclarations() ?? []) { const sourceFile = decl.getSourceFile(); const pos = sourceFile ? decl.getStart() : 0; - allDecls.push({ decl, symbol, position: pos }); + allDecls.push({ decl, symbol: memberSymbol, position: pos }); } } @@ -659,6 +948,21 @@ export class TypeProcessor { * @private */ visitType(type, node) { + const typeArguments = this.getTypeArguments(type); + if (this.checker.isArrayType(type)) { + const typeArgs = this.checker.getTypeArguments(/** @type {ts.TypeReference} */ (type)); + if (typeArgs && typeArgs.length > 0) { + const elementType = this.visitType(typeArgs[0], node); + return `[${elementType}]`; + } + return "[JSObject]"; + } + + const recordType = this.convertRecordType(type, typeArguments, node); + if (recordType) { + return recordType; + } + // Treat A and A as the same type if (isTypeReference(type)) { type = type.target; @@ -672,14 +976,48 @@ export class TypeProcessor { * @returns {string} */ const convert = (type) => { + const originalType = type; + // Handle nullable/undefined unions (e.g. T | null, T | undefined) + const isUnionType = (type.flags & ts.TypeFlags.Union) !== 0; + if (isUnionType) { + /** @type {ts.UnionType} */ + // @ts-ignore + const unionType = type; + const unionTypes = unionType.types; + const hasNull = unionTypes.some(t => (t.flags & ts.TypeFlags.Null) !== 0); + const hasUndefined = unionTypes.some(t => (t.flags & ts.TypeFlags.Undefined) !== 0); + const nonNullableTypes = unionTypes.filter( + t => (t.flags & ts.TypeFlags.Null) === 0 && (t.flags & ts.TypeFlags.Undefined) === 0 + ); + if (nonNullableTypes.length === 1 && (hasNull || hasUndefined)) { + const wrapped = this.visitType(nonNullableTypes[0], node); + if (hasNull && hasUndefined) { + return "JSObject"; + } + if (hasNull) { + return `Optional<${wrapped}>`; + } + return `JSUndefinedOr<${wrapped}>`; + } + + const stringLiteralUnion = this.getStringLiteralUnionLiterals(type); + if (stringLiteralUnion && stringLiteralUnion.length > 0) { + const typeName = this.deriveTypeName(originalType) ?? this.deriveTypeName(type); + if (typeName) { + this.seenTypes.set(originalType, node); + return this.renderTypeIdentifier(typeName); + } + } + } + /** @type {Record} */ const typeMap = { "number": "Double", "string": "String", "boolean": "Bool", "void": "Void", - "any": "JSObject", - "unknown": "JSObject", + "any": "JSValue", + "unknown": "JSValue", "null": "Void", "undefined": "Void", "bigint": "Int", @@ -688,19 +1026,24 @@ export class TypeProcessor { "never": "Void", "Promise": "JSPromise", }; - const typeString = type.getSymbol()?.name ?? this.checker.typeToString(type); + const symbol = type.getSymbol() ?? type.aliasSymbol; + const typeString = symbol?.name ?? this.checker.typeToString(type); if (typeMap[typeString]) { return typeMap[typeString]; } - - const symbol = type.getSymbol() ?? type.aliasSymbol; if (symbol && (symbol.flags & ts.SymbolFlags.Enum) !== 0) { const typeName = symbol.name; this.seenTypes.set(type, node); return this.renderTypeIdentifier(typeName); } - if (this.checker.isArrayType(type) || this.checker.isTupleType(type) || type.getCallSignatures().length > 0) { + const stringLiteralUnion = this.getStringLiteralUnionLiterals(type); + if (stringLiteralUnion && stringLiteralUnion.length > 0) { + this.seenTypes.set(type, node); + return this.renderTypeIdentifier(this.deriveTypeName(type) ?? this.checker.typeToString(type)); + } + + if (this.checker.isTupleType(type) || type.getCallSignatures().length > 0) { return "JSObject"; } // "a" | "b" -> string @@ -724,6 +1067,54 @@ export class TypeProcessor { return swiftType; } + /** + * Convert a `Record` TypeScript type into a Swift dictionary type. + * Falls back to `JSObject` when keys are not string-compatible or type arguments are missing. + * @param {ts.Type} type + * @param {readonly ts.Type[]} typeArguments + * @param {ts.Node} node + * @returns {string | null} + * @private + */ + convertRecordType(type, typeArguments, node) { + const symbol = type.aliasSymbol ?? type.getSymbol(); + if (!symbol || symbol.name !== "Record") { + return null; + } + if (typeArguments.length !== 2) { + this.diagnosticEngine.print("warning", "Record expects two type arguments", node); + return "JSObject"; + } + const [keyType, valueType] = typeArguments; + const stringType = this.checker.getStringType(); + if (!this.checker.isTypeAssignableTo(keyType, stringType)) { + this.diagnosticEngine.print( + "warning", + `Record key type must be assignable to string: ${this.checker.typeToString(keyType)}`, + node + ); + return "JSObject"; + } + + const valueSwiftType = this.visitType(valueType, node); + return `[String: ${valueSwiftType}]`; + } + + /** + * Retrieve type arguments for a given type, including type alias instantiations. + * @param {ts.Type} type + * @returns {readonly ts.Type[]} + * @private + */ + getTypeArguments(type) { + if (isTypeReference(type)) { + return this.checker.getTypeArguments(type); + } + // Non-TypeReference alias instantiations store type arguments separately. + // @ts-ignore: `aliasTypeArguments` is intentionally accessed for alias instantiations. + return type.aliasTypeArguments ?? []; + } + /** * Derive the type name from a type * @param {ts.Type} type - TypeScript type @@ -753,6 +1144,7 @@ export class TypeProcessor { const type = property.type; const swiftName = this.renderIdentifier(property.swiftName); + const isStatic = property.isStatic; const needsJSGetterName = property.jsName !== property.swiftName; // Note: `from: .global` is only meaningful for top-level imports and constructors. // Instance member access always comes from the JS object itself. @@ -762,9 +1154,11 @@ export class TypeProcessor { if (needsJSGetterName) getterArgs.push(`jsName: "${this.escapeForSwiftStringLiteral(property.jsName)}"`); if (fromArg) getterArgs.push(fromArg); const getterAnnotation = this.renderMacroAnnotation("JSGetter", getterArgs); + const staticKeyword = isStatic ? "static " : ""; // Always render getter - this.swiftLines.push(` ${getterAnnotation} var ${swiftName}: ${type}`); + this.emitDocComment(node, { indent: " " }); + this.swiftLines.push(` ${getterAnnotation} ${staticKeyword}var ${swiftName}: ${type}`); // Render setter if not readonly if (!property.isReadonly) { @@ -777,7 +1171,7 @@ export class TypeProcessor { if (needsJSNameField) setterArgs.push(`jsName: "${this.escapeForSwiftStringLiteral(property.jsName)}"`); if (fromArg) setterArgs.push(fromArg); const annotation = this.renderMacroAnnotation("JSSetter", setterArgs); - this.swiftLines.push(` ${annotation} func ${this.renderIdentifier(setterName)}(_ value: ${type}) ${this.renderEffects({ isAsync: false })}`); + this.swiftLines.push(` ${annotation} ${staticKeyword}func ${this.renderIdentifier(setterName)}(_ value: ${type}) ${this.renderEffects({ isAsync: false })}`); } } @@ -813,12 +1207,19 @@ export class TypeProcessor { const signature = this.checker.getSignatureFromDeclaration(node); if (!signature) return; - const params = this.renderParameters(signature.getParameters(), node); + const parameters = signature.getParameters(); + const parameterNameMap = this.buildParameterNameMap(parameters); + const params = this.renderParameters(parameters, node); const returnType = this.visitType(signature.getReturnType(), node); const effects = this.renderEffects({ isAsync: false }); const swiftMethodName = this.renderIdentifier(swiftName); + const isStatic = node.modifiers?.some( + (modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword + ) ?? false; + const staticKeyword = isStatic ? "static " : ""; - this.swiftLines.push(` ${annotation} func ${swiftMethodName}(${params}) ${effects} -> ${returnType}`); + this.emitDocComment(node, { indent: " ", parameterNameMap }); + this.swiftLines.push(` ${annotation} ${staticKeyword}func ${swiftMethodName}(${params}) ${effects} -> ${returnType}`); } /** @@ -836,8 +1237,14 @@ export class TypeProcessor { * @private */ renderConstructor(node) { - const params = this.renderConstructorParameters(node); + const signature = this.checker.getSignatureFromDeclaration(node); + if (!signature) return; + + const parameters = signature.getParameters(); + const parameterNameMap = this.buildParameterNameMap(parameters); + const params = this.renderParameters(parameters, node); const effects = this.renderEffects({ isAsync: false }); + this.emitDocComment(node, { indent: " ", parameterNameMap }); this.swiftLines.push(` @JSFunction init(${params}) ${effects}`); } @@ -870,10 +1277,32 @@ export class TypeProcessor { if (effects?.isAsync) { parts.push("async"); } - parts.push("throws (JSException)"); + parts.push("throws(JSException)"); return parts.join(" "); } + /** + * @param {ts.Node} node + * @returns {boolean} + */ + isExported(node) { + const hasExportModifier = /** @type {ts.ModifierLike[] | undefined} */ (node.modifiers)?.some( + (m) => m.kind === ts.SyntaxKind.ExportKeyword + ) ?? false; + return hasExportModifier || ts.isExportAssignment(node); + } + + /** + * Emit a single warning per node when an exported declaration cannot be generated. + * @param {ts.Node} node + * @param {string} reason + */ + warnExportSkip(node, reason) { + if (this.warnedExportNodes.has(node)) return; + this.warnedExportNodes.add(node); + this.diagnosticEngine.print("warning", `${reason}. Swift binding not generated`, node); + } + /** * Render identifier with backticks if needed * @param {string} name diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap new file mode 100644 index 000000000..4122f4148 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/__snapshots__/ts2swift.test.js.snap @@ -0,0 +1,633 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`ts2swift > snapshots Swift output for ArrayParameter.d.ts > ArrayParameter 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func processNumbers(_ values: [Double]) throws(JSException) -> Void + +@JSFunction func getNumbers() throws(JSException) -> [Double] + +@JSFunction func transformNumbers(_ values: [Double]) throws(JSException) -> [Double] + +@JSFunction func processStrings(_ values: [String]) throws(JSException) -> [String] + +@JSFunction func processBooleans(_ values: [Bool]) throws(JSException) -> [Bool] + +@JSFunction func processArraySyntax(_ values: [Double]) throws(JSException) -> [Double] +" +`; + +exports[`ts2swift > snapshots Swift output for Async.d.ts > Async 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func asyncReturnVoid() throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripInt(_ v: Double) throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripString(_ v: String) throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripBool(_ v: Bool) throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripFloat(_ v: Double) throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripDouble(_ v: Double) throws(JSException) -> JSPromise + +@JSFunction func asyncRoundTripJSObject(_ v: JSValue) throws(JSException) -> JSPromise +" +`; + +exports[`ts2swift > snapshots Swift output for CallableConst.d.ts > CallableConst 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func fetch(_ url: String) throws(JSException) -> Response + +@JSClass struct Response { +} +" +`; + +exports[`ts2swift > snapshots Swift output for Documentation.d.ts > Documentation 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +/// Return a greeting for a user. +/// +/// - Parameters: +/// - name: The user's name. +/// - Returns: The greeting message. +@JSFunction func greet(_ name: String) throws(JSException) -> String + +@JSFunction func origin() throws(JSException) -> Point + +/// Represents a 2D point. +@JSClass struct Point { + /// The horizontal position. + @JSGetter var x: Double + @JSSetter func setX(_ value: Double) throws(JSException) + /// Translate the point. + /// + /// - Parameters: + /// - dx: Delta to apply on x. + /// - dy: Delta to apply on y. + /// - Returns: The moved point. + @JSFunction func translate(_ dx: Double, _ dy: Double) throws(JSException) -> Point +} + +/// Move a point by the given delta. +/// +/// - Parameters: +/// - point: The point to move. +/// - dx: Delta to apply on x. +/// - dy: Delta to apply on y. +@JSFunction func translatePoint(_ point: Point, _ dx: Double, _ dy: Double) throws(JSException) -> Point + +/// A greeter that keeps the target name. +@JSClass struct Greeter { + /// Create a greeter. + /// + /// - Parameters: + /// - name: Name to greet. + @JSFunction init(_ name: String) throws(JSException) + /// The configured name. + @JSGetter var targetName: String + /// Say hello. + /// + /// - Returns: Greeting message. + @JSFunction func greet() throws(JSException) -> String +} +" +`; + +exports[`ts2swift > snapshots Swift output for ExportAssignment.d.ts > ExportAssignment 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSGetter var foo: Double +" +`; + +exports[`ts2swift > snapshots Swift output for Interface.d.ts > Interface 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func returnAnimatable() throws(JSException) -> Animatable + +@JSClass struct Animatable { + @JSFunction func animate(_ keyframes: JSValue, _ options: JSValue) throws(JSException) -> JSValue + @JSFunction func getAnimations(_ options: JSValue) throws(JSException) -> JSValue +} +" +`; + +exports[`ts2swift > snapshots Swift output for InvalidPropertyNames.d.ts > InvalidPropertyNames 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func createArrayBuffer() throws(JSException) -> ArrayBufferLike + +@JSClass struct ArrayBufferLike { + @JSGetter var byteLength: Double + @JSFunction func slice(_ begin: Double, _ end: Double) throws(JSException) -> ArrayBufferLike +} + +@JSFunction func createWeirdObject() throws(JSException) -> WeirdNaming + +@JSClass struct WeirdNaming { + @JSGetter var normalProperty: String + @JSSetter func setNormalProperty(_ value: String) throws(JSException) + @JSGetter(jsName: "property-with-dashes") var property_with_dashes: Double + @JSSetter(jsName: "property-with-dashes") func setProperty_with_dashes(_ value: Double) throws(JSException) + @JSGetter(jsName: "123invalidStart") var _123invalidStart: Bool + @JSSetter(jsName: "123invalidStart") func set_123invalidStart(_ value: Bool) throws(JSException) + @JSGetter(jsName: "property with spaces") var property_with_spaces: String + @JSSetter(jsName: "property with spaces") func setProperty_with_spaces(_ value: String) throws(JSException) + @JSGetter(jsName: "@specialChar") var _specialChar: Double + @JSSetter(jsName: "@specialChar") func set_specialChar(_ value: Double) throws(JSException) + @JSGetter var constructor: String + @JSSetter func setConstructor(_ value: String) throws(JSException) + @JSGetter var \`for\`: String + @JSSetter func setFor(_ value: String) throws(JSException) + @JSGetter var \`Any\`: String + @JSSetter(jsName: "Any") func setAny(_ value: String) throws(JSException) + @JSFunction func \`as\`() throws(JSException) -> Void + @JSFunction func \`try\`() throws(JSException) -> Void +} + +@JSClass(jsName: "$Weird") struct _Weird { + @JSFunction init() throws(JSException) + @JSFunction(jsName: "method-with-dashes") func method_with_dashes() throws(JSException) -> Void +} + +@JSFunction func createWeirdClass() throws(JSException) -> _Weird +" +`; + +exports[`ts2swift > snapshots Swift output for MultipleImportedTypes.d.ts > MultipleImportedTypes 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func createDatabaseConnection(_ config: JSValue) throws(JSException) -> DatabaseConnection + +@JSClass struct DatabaseConnection { + @JSFunction func connect(_ url: String) throws(JSException) -> Void + @JSFunction func execute(_ query: String) throws(JSException) -> JSValue + @JSGetter var isConnected: Bool + @JSGetter var connectionTimeout: Double + @JSSetter func setConnectionTimeout(_ value: Double) throws(JSException) +} + +@JSFunction func createLogger(_ level: String) throws(JSException) -> Logger + +@JSClass struct Logger { + @JSFunction func log(_ message: String) throws(JSException) -> Void + @JSFunction func error(_ message: String, _ error: JSValue) throws(JSException) -> Void + @JSGetter var level: String +} + +@JSFunction func getConfigManager() throws(JSException) -> ConfigManager + +@JSClass struct ConfigManager { + @JSFunction func get(_ key: String) throws(JSException) -> JSValue + @JSFunction func set(_ key: String, _ value: JSValue) throws(JSException) -> Void + @JSGetter var configPath: String +} +" +`; + +exports[`ts2swift > snapshots Swift output for ObjectLikeTypes.d.ts > ObjectLikeTypes 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func acceptObject(_ v: JSObject) throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for OptionalNullUndefined.d.ts > OptionalNullUndefined 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func roundTripNumberNull(_ value: Optional) throws(JSException) -> Optional + +@JSFunction func roundTripNumberUndefined(_ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + +@JSFunction func roundTripStringNull(_ value: Optional) throws(JSException) -> Optional + +@JSFunction func roundTripStringUndefined(_ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + +@JSFunction func roundTripBooleanNull(_ value: JSObject) throws(JSException) -> JSObject + +@JSFunction func roundTripBooleanUndefined(_ value: JSObject) throws(JSException) -> JSObject + +@JSFunction func optionalNumberParamNull(_ x: Double, _ maybe: Optional) throws(JSException) -> Double + +@JSFunction func optionalNumberParamUndefined(_ x: Double, _ maybe: JSUndefinedOr) throws(JSException) -> Double + +@JSFunction func roundTripMyInterfaceNull(_ value: Optional) throws(JSException) -> Optional + +@JSClass struct MyInterface { +} + +@JSFunction func roundTripMyInterfaceUndefined(_ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + +@JSClass struct WithOptionalFields { + @JSGetter var valueOrNull: Optional + @JSSetter func setValueOrNull(_ value: Optional) throws(JSException) + @JSGetter var valueOrUndefined: JSUndefinedOr + @JSSetter func setValueOrUndefined(_ value: JSUndefinedOr) throws(JSException) +} +" +`; + +exports[`ts2swift > snapshots Swift output for PrimitiveParameters.d.ts > PrimitiveParameters 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func check(_ a: Double, _ b: Bool) throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for PrimitiveReturn.d.ts > PrimitiveReturn 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func checkNumber() throws(JSException) -> Double + +@JSFunction func checkBoolean() throws(JSException) -> Bool +" +`; + +exports[`ts2swift > snapshots Swift output for ReExportFrom.d.ts > ReExportFrom 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func jsRoundTripNumber(_ v: Double) throws(JSException) -> Double + +@JSClass struct JsGreeter { + @JSFunction init(_ name: String) throws(JSException) + @JSFunction func greet() throws(JSException) -> String +} +" +`; + +exports[`ts2swift > snapshots Swift output for RecordDictionary.d.ts > RecordDictionary 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func takeRecord(_ value: [String: Double]) throws(JSException) -> Void + +@JSFunction func returnRecord() throws(JSException) -> [String: String] + +@JSFunction func optionalRecord(_ value: Optional<[String: Bool]>) throws(JSException) -> Optional<[String: Bool]> + +@JSFunction func nestedRecord(_ value: [String: [String: Double]]) throws(JSException) -> [String: [String: Double]] + +@JSFunction func recordWithArrayValues(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] + +@JSFunction func recordWithObjects(_ values: [String: Optional]) throws(JSException) -> [String: Optional] + +@JSClass struct Box { + @JSGetter var value: Double + @JSSetter func setValue(_ value: Double) throws(JSException) +} + +@JSFunction func unsupportedKeyRecord(_ values: JSObject) throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for StaticProperty.d.ts > StaticProperty 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSClass struct Library { + @JSGetter static var version: String + @JSSetter static func setVersion(_ value: String) throws(JSException) +} +" +`; + +exports[`ts2swift > snapshots Swift output for StringEnum.d.ts > StringEnum 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +enum FeatureFlag: String { + case foo = "foo" + case bar = "bar" +} +extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} + +@JSFunction func takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void + +@JSFunction func returnsFeatureFlag() throws(JSException) -> FeatureFlag +" +`; + +exports[`ts2swift > snapshots Swift output for StringLiteralUnion.d.ts > StringLiteralUnion 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func move(_ direction: Direction) throws(JSException) -> Void + +enum Direction: String { + case up = "up" + case down = "down" + case left = "left" + case right = "right" +} +extension Direction: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} +" +`; + +exports[`ts2swift > snapshots Swift output for StringParameter.d.ts > StringParameter 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func checkString(_ a: String) throws(JSException) -> Void + +@JSFunction func checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for StringReturn.d.ts > StringReturn 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func checkString() throws(JSException) -> String +" +`; + +exports[`ts2swift > snapshots Swift output for TS2SkeletonLike.d.ts > TS2SkeletonLike 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func createTS2Skeleton() throws(JSException) -> TypeScriptProcessor + +@JSClass struct TypeScriptProcessor { + @JSFunction func convert(_ ts: String) throws(JSException) -> String + @JSFunction func validate(_ ts: String) throws(JSException) -> Bool + @JSGetter var version: String +} + +@JSFunction func createCodeGenerator(_ format: String) throws(JSException) -> CodeGenerator + +@JSClass struct CodeGenerator { + @JSFunction func generate(_ input: JSValue) throws(JSException) -> String + @JSGetter var outputFormat: String +} +" +`; + +exports[`ts2swift > snapshots Swift output for TypeAlias.d.ts > TypeAlias 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func checkSimple(_ a: Double) throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for TypeAliasObject.d.ts > TypeAliasObject 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func console() throws(JSException) -> Console + +/// Console from the environment. +@JSClass struct Console { + /// Log a message. + @JSFunction func log(_ message: String) throws(JSException) -> Void +} +" +`; + +exports[`ts2swift > snapshots Swift output for TypeScriptClass.d.ts > TypeScriptClass 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSClass struct Greeter { + @JSGetter var name: String + @JSSetter func setName(_ value: String) throws(JSException) + @JSGetter var age: Double + @JSFunction init(_ name: String) throws(JSException) + @JSFunction func greet() throws(JSException) -> String + @JSFunction func changeName(_ name: String) throws(JSException) -> Void + @JSFunction static func staticMethod(_ p1: Double, _ p2: String) throws(JSException) -> String +} +" +`; + +exports[`ts2swift > snapshots Swift output for VoidParameterVoidReturn.d.ts > VoidParameterVoidReturn 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func check() throws(JSException) -> Void +" +`; + +exports[`ts2swift > snapshots Swift output for WebIDLDOMDocs.d.ts > WebIDLDOMDocs 1`] = ` +"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// \`swift package bridge-js\`. + +@_spi(BridgeJS) import JavaScriptKit + +/// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document) +@JSGetter var document: Document + +/// A simple Document subset with WebIDL-derived comments. +@JSClass struct Document { + /// Creates an instance of the element for the specified tag. + /// + /// - Parameters: + /// - tagName: The name of an element. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) + @JSFunction func createElement(_ tagName: String, _ options: JSUndefinedOr) throws(JSException) -> Element + /// Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. + /// + /// If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. + /// + /// If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + /// + /// localName does not match the QName production. + /// Namespace prefix is not null and namespace is the empty string. + /// Namespace prefix is "xml" and namespace is not the XML namespace. + /// qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + /// namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". + /// + /// When supplied, options's is can be used to create a customized built-in element. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) + @JSFunction func createElementNS(_ namespaceURI: Optional, _ qualifiedName: String, _ options: JSObject) throws(JSException) -> Element + /// Creates a TreeWalker object. + /// + /// - Parameters: + /// - root: The root element or node to start traversing on. + /// - whatToShow: The type of nodes or elements to appear in the node list + /// - filter: A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + /// - Returns: The created TreeWalker. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTreeWalker) + @JSFunction func createTreeWalker(_ root: Node, _ whatToShow: JSUndefinedOr, _ filter: JSUndefinedOr) throws(JSException) -> TreeWalker +} + +@JSClass struct ElementCreationOptions { + @JSGetter var \`is\`: JSUndefinedOr + @JSSetter func setIs(_ value: JSUndefinedOr) throws(JSException) +} + +@JSClass struct Element { + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/textContent) + @JSGetter var textContent: Optional + @JSSetter func setTextContent(_ value: Optional) throws(JSException) + /// Returns a copy of node. If deep is true, the copy also includes the node's descendants. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) + @JSFunction func cloneNode(_ subtree: JSObject) throws(JSException) -> Node +} + +/// Minimal stubs to mirror lib.dom.d.ts documentation converted from WebIDL. +@JSClass struct Node { + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/textContent) + @JSGetter var textContent: Optional + @JSSetter func setTextContent(_ value: Optional) throws(JSException) + /// Returns a copy of node. If deep is true, the copy also includes the node's descendants. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) + @JSFunction func cloneNode(_ subtree: JSObject) throws(JSException) -> Node +} + +@JSClass struct TreeWalker { + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/TreeWalker/currentNode) + @JSGetter var currentNode: Node + @JSSetter func setCurrentNode(_ value: Node) throws(JSException) + /// Moves the currentNode to the next visible node in the document order. + /// + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/TreeWalker/nextNode) + @JSFunction func nextNode() throws(JSException) -> Optional +} +" +`; diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ArrayParameter.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ArrayParameter.d.ts new file mode 100644 index 000000000..b5a099388 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ArrayParameter.d.ts @@ -0,0 +1,17 @@ +// Array as parameter +export function processNumbers(values: number[]): void; + +// Array as return value +export function getNumbers(): number[]; + +// Array as both parameter and return value +export function transformNumbers(values: number[]): number[]; + +// String arrays +export function processStrings(values: string[]): string[]; + +// Boolean arrays +export function processBooleans(values: boolean[]): boolean[]; + +// Using Array syntax +export function processArraySyntax(values: Array): Array; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Async.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Async.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Async.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Async.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/CallableConst.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/CallableConst.d.ts new file mode 100644 index 000000000..3df79d597 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/CallableConst.d.ts @@ -0,0 +1,2 @@ +export interface Response {} +export const fetch: (url: string) => Response; diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Documentation.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Documentation.d.ts new file mode 100644 index 000000000..90ba064bb --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Documentation.d.ts @@ -0,0 +1,56 @@ +/** + * Return a greeting for a user. + * @param name The user's name. + * @returns The greeting message. + */ +export function greet(name: string): string; + +/** + * Represents a 2D point. + */ +export interface Point { + /** + * The horizontal position. + */ + x: number; + + /** + * Translate the point. + * @param dx Delta to apply on x. + * @param dy Delta to apply on y. + * @returns The moved point. + */ + translate(dx: number, dy: number): Point; +} + +export function origin(): Point; + +/** + * Move a point by the given delta. + * @param point The point to move. + * @param dx Delta to apply on x. + * @param dy Delta to apply on y. + */ +export function translatePoint(point: Point, dx: number, dy: number): Point; + +/** + * A greeter that keeps the target name. + */ +export class Greeter { + /** + * Create a greeter. + * @param name Name to greet. + */ + constructor(name: string); + + /** + * The configured name. + */ + readonly targetName: string; + + /** + * Say hello. + * @returns Greeting message. + */ + greet(): string; +} diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ExportAssignment.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ExportAssignment.d.ts new file mode 100644 index 000000000..5f9543ecb --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ExportAssignment.d.ts @@ -0,0 +1,2 @@ +export const foo: number; +export default foo; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Interface.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Interface.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Interface.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Interface.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/InvalidPropertyNames.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/InvalidPropertyNames.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/InvalidPropertyNames.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/InvalidPropertyNames.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MultipleImportedTypes.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/MultipleImportedTypes.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MultipleImportedTypes.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/MultipleImportedTypes.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ObjectLikeTypes.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ObjectLikeTypes.d.ts new file mode 100644 index 000000000..d605048cd --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ObjectLikeTypes.d.ts @@ -0,0 +1 @@ +export function acceptObject(v: object): void; diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/OptionalNullUndefined.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/OptionalNullUndefined.d.ts new file mode 100644 index 000000000..8b64528d9 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/OptionalNullUndefined.d.ts @@ -0,0 +1,20 @@ +export function roundTripNumberNull(value: number | null): number | null; +export function roundTripNumberUndefined(value: number | undefined): number | undefined; + +export function roundTripStringNull(value: string | null): string | null; +export function roundTripStringUndefined(value: string | undefined): string | undefined; + +export function roundTripBooleanNull(value: boolean | null): boolean | null; +export function roundTripBooleanUndefined(value: boolean | undefined): boolean | undefined; + +export function optionalNumberParamNull(x: number, maybe: number | null): number; +export function optionalNumberParamUndefined(x: number, maybe: number | undefined): number; + +export interface MyInterface {} +export function roundTripMyInterfaceNull(value: MyInterface | null): MyInterface | null; +export function roundTripMyInterfaceUndefined(value: MyInterface | undefined): MyInterface | undefined; + +export class WithOptionalFields { + valueOrNull: MyInterface | null; + valueOrUndefined: MyInterface | undefined; +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveParameters.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/PrimitiveParameters.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveParameters.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/PrimitiveParameters.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveReturn.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/PrimitiveReturn.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveReturn.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/PrimitiveReturn.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ReExportFrom.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ReExportFrom.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ReExportFrom.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/ReExportFrom.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/RecordDictionary.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/RecordDictionary.d.ts new file mode 100644 index 000000000..cfaf5f309 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/RecordDictionary.d.ts @@ -0,0 +1,17 @@ +export interface Box { + value: number; +} + +export function takeRecord(value: Record): void; + +export function returnRecord(): Record; + +export function optionalRecord(value: Record | null): Record | null; + +export function nestedRecord(value: Record>): Record>; + +export function recordWithArrayValues(values: Record): Record; + +export function recordWithObjects(values: Record): Record; + +export function unsupportedKeyRecord(values: Record): void; diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StaticProperty.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StaticProperty.d.ts new file mode 100644 index 000000000..afef26b5c --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StaticProperty.d.ts @@ -0,0 +1,3 @@ +export class Library { + static version: string; +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringEnum.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringEnum.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringEnum.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringEnum.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringLiteralUnion.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringLiteralUnion.d.ts new file mode 100644 index 000000000..2c01a23fa --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringLiteralUnion.d.ts @@ -0,0 +1,3 @@ +export type Direction = "up" | "down" | "left" | "right"; + +export function move(direction: Direction): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringParameter.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringParameter.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringParameter.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringParameter.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringReturn.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringReturn.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringReturn.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/StringReturn.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Support/ReExportTarget.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Support/ReExportTarget.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Support/ReExportTarget.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/Support/ReExportTarget.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TS2SkeletonLike.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TS2SkeletonLike.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TS2SkeletonLike.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TS2SkeletonLike.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TypeAlias.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeAlias.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TypeAlias.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeAlias.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeAliasObject.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeAliasObject.d.ts new file mode 100644 index 000000000..55ffdfa3a --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeAliasObject.d.ts @@ -0,0 +1,11 @@ +/** + * Console from the environment. + */ +export type Console = { + /** + * Log a message. + */ + log(message: string): void; +}; + +export function console(): Console; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TypeScriptClass.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeScriptClass.d.ts similarity index 73% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TypeScriptClass.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeScriptClass.d.ts index 074772f24..0745de1f9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/TypeScriptClass.d.ts +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/TypeScriptClass.d.ts @@ -4,4 +4,6 @@ export class Greeter { constructor(name: string); greet(): string; changeName(name: string): void; + + static staticMethod(p1: number, p2: string): string; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/VoidParameterVoidReturn.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/VoidParameterVoidReturn.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/VoidParameterVoidReturn.d.ts rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/VoidParameterVoidReturn.d.ts diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/WebIDLDOMDocs.d.ts b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/WebIDLDOMDocs.d.ts new file mode 100644 index 000000000..ace4011a4 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/WebIDLDOMDocs.d.ts @@ -0,0 +1,81 @@ +/** + * Minimal stubs to mirror lib.dom.d.ts documentation converted from WebIDL. + */ + +interface Node { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/textContent) */ + textContent: string | null; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/cloneNode) + */ + cloneNode(subtree?: boolean): Node; +} + +interface Element extends Node {} +type HTMLElement = Element; +type SVGElement = Element; +type MathMLElement = Element; +type DocumentFragment = Node; + +interface ElementCreationOptions { + is?: string; +} + +/** + * A simple Document subset with WebIDL-derived comments. + */ +interface Document { + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) + */ + createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; + + /** + * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. + * + * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. + * + * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + * + * localName does not match the QName production. + * Namespace prefix is not null and namespace is the empty string. + * Namespace prefix is "xml" and namespace is not the XML namespace. + * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". + * + * When supplied, options's is can be used to create a customized built-in element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) + */ + createElementNS(namespaceURI: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + + /** + * Creates a TreeWalker object. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @returns The created TreeWalker. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTreeWalker) + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: (node: Node) => number | null): TreeWalker; +} + +interface TreeWalker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TreeWalker/currentNode) */ + currentNode: Node; + /** + * Moves the currentNode to the next visible node in the document order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TreeWalker/nextNode) + */ + nextNode(): Node | null; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document) */ +export const document: Document; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/tsconfig.json b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/tsconfig.json similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/tsconfig.json rename to Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/fixtures/tsconfig.json diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/ts2swift.test.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/ts2swift.test.js new file mode 100644 index 000000000..4aefa19b5 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/test/ts2swift.test.js @@ -0,0 +1,67 @@ +// @ts-check +import { describe, it, expect } from 'vitest'; +import { readdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs'; +import { fileURLToPath } from 'url'; +import path from 'path'; +import os from 'os'; +import { run } from '../src/cli.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +/** Path to BridgeJSToolTests/Inputs/TypeScript (.d.ts fixtures and tsconfig). */ +const inputsDir = path.resolve(__dirname, 'fixtures'); +const tsconfigPath = path.join(inputsDir, 'tsconfig.json'); + +function runTs2Swift(dtsPath) { + return run([dtsPath], { tsconfigPath, logLevel: 'error' }); +} + +function collectDtsInputs() { + const entries = readdirSync(inputsDir, { withFileTypes: true }); + return entries + .filter((e) => e.isFile() && e.name.endsWith('.d.ts')) + .map((e) => e.name) + .sort(); +} + +describe('ts2swift', () => { + const dtsFiles = collectDtsInputs(); + if (dtsFiles.length === 0) { + it.skip('no .d.ts fixtures found in BridgeJSToolTests/Inputs', () => {}); + return; + } + + for (const dtsFile of dtsFiles) { + it(`snapshots Swift output for ${dtsFile}`, () => { + const dtsPath = path.join(inputsDir, dtsFile); + const swiftOutput = runTs2Swift(dtsPath); + const name = dtsFile.replace(/\.d\.ts$/, ''); + expect(swiftOutput).toMatchSnapshot(name); + }); + } + + it('reports TypeScript syntax errors via thrown message', () => { + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'ts2swift-invalid-')); + const invalidPath = path.join(tmpDir, 'invalid.d.ts'); + writeFileSync(invalidPath, 'function foo(x'); + try { + expect(() => runTs2Swift(invalidPath)).toThrowError(/TypeScript syntax errors/); + } finally { + rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it('emits a warning when export assignments cannot be generated', () => { + const dtsPath = path.join(inputsDir, 'ExportAssignment.d.ts'); + /** @type {{ level: string, message: string }[]} */ + const diagnostics = []; + const diagnosticEngine = { + print: (level, message) => diagnostics.push({ level, message }), + }; + run([dtsPath], { tsconfigPath, logLevel: 'warning', diagnosticEngine }); + const messages = diagnostics.map((d) => d.message).join('\n'); + expect(messages).toMatch(/Skipping export assignment/); + const occurrences = (messages.match(/Skipping export assignment/g) || []).length; + expect(occurrences).toBe(1); + }); +}); diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/tsconfig.json b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/tsconfig.json new file mode 100644 index 000000000..ed3dcf4bf --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "strict": true, + "allowJs": true, + "skipLibCheck": true, + "noEmit": true, + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "nodenext" + }, + "include": [ + "src/*.js" + ] +} diff --git a/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/vitest.config.js b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/vitest.config.js new file mode 100644 index 000000000..d5d33a7e1 --- /dev/null +++ b/Plugins/BridgeJS/Sources/TS2Swift/JavaScript/vitest.config.js @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + snapshotFormat: { + escapeString: false, + }, + }, +}); diff --git a/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift b/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift index 795b7b390..6337dcf27 100644 --- a/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift +++ b/Plugins/BridgeJS/Sources/TS2Swift/TS2Swift.swift @@ -20,6 +20,12 @@ import BridgeJSCore import BridgeJSSkeleton #endif +#if os(Windows) +let PATH_SEPARATOR: Character = ";" +#else +let PATH_SEPARATOR: Character = ":" +#endif + internal func which( _ executable: String, environment: [String: String] = ProcessInfo.processInfo.environment @@ -39,13 +45,8 @@ internal func which( } } } - let pathSeparator: Character - #if os(Windows) - pathSeparator = ";" - #else - pathSeparator = ":" - #endif - let paths = environment["PATH"]?.split(separator: pathSeparator) ?? [] + + let paths = environment["PATH"]?.split(separator: PATH_SEPARATOR) ?? [] for path in paths { let url = URL(fileURLWithPath: String(path)).appendingPathComponent(executable) if checkCandidate(url) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift index b27b93941..77dc814eb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSClassMacroTests.swift @@ -1,8 +1,7 @@ import SwiftDiagnostics import SwiftSyntax import SwiftSyntaxMacroExpansion -import SwiftSyntaxMacros -import SwiftSyntaxMacrosTestSupport +import SwiftSyntaxMacrosGenericTestSupport import Testing import BridgeJSMacros @@ -13,7 +12,7 @@ import BridgeJSMacros ] @Test func emptyStruct() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -21,6 +20,7 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { + let jsObject: JSObject init(unsafelyWrapping jsObject: JSObject) { @@ -32,12 +32,12 @@ import BridgeJSMacros } """, macroSpecs: macroSpecs, - indentationWidth: indentationWidth + indentationWidth: indentationWidth, ) } @Test func structWithExistingJSObject() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -62,7 +62,7 @@ import BridgeJSMacros } @Test func structWithExistingInit() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -73,11 +73,11 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { - let jsObject: JSObject - init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } + + let jsObject: JSObject } extension MyClass: _JSBridgedClass { @@ -89,7 +89,7 @@ import BridgeJSMacros } @Test func structWithBothExisting() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -118,7 +118,7 @@ import BridgeJSMacros } @Test func structWithMembers() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -127,10 +127,10 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { - let jsObject: JSObject - var name: String + let jsObject: JSObject + init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } @@ -145,7 +145,7 @@ import BridgeJSMacros } @Test func _class() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass class MyClass { @@ -159,7 +159,17 @@ import BridgeJSMacros DiagnosticSpec( message: "@JSClass can only be applied to structs.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Use @JSClass on a struct wrapper to synthesize jsObject and JS bridging members.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Change 'class' to 'struct'") + ] ) ], macroSpecs: macroSpecs, @@ -168,7 +178,7 @@ import BridgeJSMacros } @Test func _enum() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass enum MyEnum { @@ -182,7 +192,14 @@ import BridgeJSMacros DiagnosticSpec( message: "@JSClass can only be applied to structs.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Use @JSClass on a struct wrapper to synthesize jsObject and JS bridging members.", + line: 1, + column: 1 + ) + ] ) ], macroSpecs: macroSpecs, @@ -191,7 +208,7 @@ import BridgeJSMacros } @Test func _actor() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass actor MyActor { @@ -205,7 +222,14 @@ import BridgeJSMacros DiagnosticSpec( message: "@JSClass can only be applied to structs.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Use @JSClass on a struct wrapper to synthesize jsObject and JS bridging members.", + line: 1, + column: 1 + ) + ] ) ], macroSpecs: macroSpecs, @@ -214,7 +238,7 @@ import BridgeJSMacros } @Test func structWithDifferentJSObjectName() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -223,10 +247,10 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { - let jsObject: JSObject - var otherProperty: String + let jsObject: JSObject + init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } @@ -241,7 +265,7 @@ import BridgeJSMacros } @Test func structWithDifferentInit() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -251,11 +275,11 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { - let jsObject: JSObject - init(name: String) { } + let jsObject: JSObject + init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } @@ -270,7 +294,7 @@ import BridgeJSMacros } @Test func structWithMultipleMembers() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass { @@ -280,11 +304,11 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass { - let jsObject: JSObject - var name: String var age: Int + let jsObject: JSObject + init(unsafelyWrapping jsObject: JSObject) { self.jsObject = jsObject } @@ -299,7 +323,7 @@ import BridgeJSMacros } @Test func structWithComment() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ /// Documentation comment @JSClass @@ -309,6 +333,7 @@ import BridgeJSMacros expandedSource: """ /// Documentation comment struct MyClass { + let jsObject: JSObject init(unsafelyWrapping jsObject: JSObject) { @@ -325,7 +350,7 @@ import BridgeJSMacros } @Test func structAlreadyConforms() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSClass struct MyClass: _JSBridgedClass { @@ -333,6 +358,7 @@ import BridgeJSMacros """, expandedSource: """ struct MyClass: _JSBridgedClass { + let jsObject: JSObject init(unsafelyWrapping jsObject: JSObject) { @@ -344,4 +370,102 @@ import BridgeJSMacros indentationWidth: indentationWidth ) } + + @Test func publicStructSynthesizesPublicMembers() { + TestSupport.assertMacroExpansion( + """ + @JSClass + public struct MyClass { + } + """, + expandedSource: """ + public struct MyClass { + + public let jsObject: JSObject + + public init(unsafelyWrapping jsObject: JSObject) { + self.jsObject = jsObject + } + } + + extension MyClass: _JSBridgedClass { + } + """, + macroSpecs: macroSpecs, + indentationWidth: indentationWidth + ) + } + + @Test func packageStructSynthesizesPackageMembers() { + TestSupport.assertMacroExpansion( + """ + @JSClass + package struct MyClass { + } + """, + expandedSource: """ + package struct MyClass { + + package let jsObject: JSObject + + package init(unsafelyWrapping jsObject: JSObject) { + self.jsObject = jsObject + } + } + + extension MyClass: _JSBridgedClass { + } + """, + macroSpecs: macroSpecs, + indentationWidth: indentationWidth + ) + } + + @Test func privateStructIsRejected() { + TestSupport.assertMacroExpansion( + """ + @JSClass + private struct MyClass { + } + """, + expandedSource: """ + private struct MyClass { + } + """, + diagnostics: [ + DiagnosticSpec( + message: + "@JSClass does not support private/fileprivate access level. Use internal, package, or public.", + line: 1, + column: 1 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth + ) + } + + @Test func fileprivateStructIsRejected() { + TestSupport.assertMacroExpansion( + """ + @JSClass + fileprivate struct MyClass { + } + """, + expandedSource: """ + fileprivate struct MyClass { + } + """, + diagnostics: [ + DiagnosticSpec( + message: + "@JSClass does not support private/fileprivate access level. Use internal, package, or public.", + line: 1, + column: 1 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth + ) + } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSFunctionMacroTests.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSFunctionMacroTests.swift index 8cfdd66e0..28eade958 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSFunctionMacroTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSFunctionMacroTests.swift @@ -1,79 +1,125 @@ import SwiftDiagnostics import SwiftSyntax -import SwiftSyntaxMacros -import SwiftSyntaxMacrosTestSupport +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport import Testing import BridgeJSMacros @Suite struct JSFunctionMacroTests { private let indentationWidth: Trivia = .spaces(4) + private let macroSpecs: [String: MacroSpec] = [ + "JSFunction": MacroSpec(type: JSFunctionMacro.self) + ] @Test func topLevelFunction() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func greet(name: String) -> String + func greet(name: String) throws(JSException) -> String """, expandedSource: """ - func greet(name: String) -> String { - return _$greet(name) + func greet(name: String) throws(JSException) -> String { + return try _$greet(name) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, + ) + } + + @Test func instanceMethodRequiresJSClass() { + TestSupport.assertMacroExpansion( + """ + struct MyClass { + @JSFunction + func getName() throws(JSException) -> String + } + """, + expandedSource: """ + struct MyClass { + func getName() throws(JSException) -> String { + return try _$MyClass_getName(self.jsObject) + } + } + """, + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionVoidReturn() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func log(message: String) + func log(message: String) throws(JSException) """, expandedSource: """ - func log(message: String) { - _$log(message) + func log(message: String) throws(JSException) { + try _$log(message) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionWithExplicitVoidReturn() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func log(message: String) -> Void + func log(message: String) throws(JSException) -> Void """, expandedSource: """ - func log(message: String) -> Void { - _$log(message) + func log(message: String) throws(JSException) -> Void { + try _$log(message) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionWithEmptyTupleReturn() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func log(message: String) -> () + func log(message: String) throws(JSException) -> () """, expandedSource: """ - func log(message: String) -> () { - _$log(message) + func log(message: String) throws(JSException) -> () { + try _$log(message) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionThrows() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( + """ + @JSFunction + func parse(json: String) throws(JSException) -> [String: Any] + """, + expandedSource: """ + func parse(json: String) throws(JSException) -> [String: Any] { + return try _$parse(json) + } + """, + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, + ) + } + + @Test func topLevelFunctionThrowsMissingType() { + TestSupport.assertMacroExpansion( """ @JSFunction func parse(json: String) throws -> [String: Any] @@ -83,221 +129,329 @@ import BridgeJSMacros return try _$parse(json) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, + ) + } + + @Test func topLevelFunctionThrowsWrongType() { + TestSupport.assertMacroExpansion( + """ + @JSFunction + func parse(json: String) throws(CustomError) -> [String: Any] + """, + expandedSource: """ + func parse(json: String) throws(CustomError) -> [String: Any] { + return try _$parse(json) + } + """, + diagnostics: [ + DiagnosticSpec( + message: "@JSFunction throws must be declared as throws(JSException).", + line: 1, + column: 1, + severity: .error, + notes: [ + NoteSpec( + message: "@JSFunction must propagate JavaScript errors as JSException.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Declare throws(JSException)") + ] + ) + ], + macroSpecs: macroSpecs, + applyFixIts: ["Declare throws(JSException)"], + fixedSource: """ + @JSFunction + func parse(json: String) throws(JSException) -> [String: Any] + """, + indentationWidth: indentationWidth, + ) + } + + @Test func topLevelFunctionMissingThrowsClause() { + TestSupport.assertMacroExpansion( + """ + @JSFunction + func greet(name: String) -> String + """, + expandedSource: """ + func greet(name: String) -> String { + return try _$greet(name) + } + """, + diagnostics: [ + DiagnosticSpec( + message: "@JSFunction throws must be declared as throws(JSException).", + line: 1, + column: 1, + notes: [ + NoteSpec( + message: "@JSFunction must propagate JavaScript errors as JSException.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Declare throws(JSException)") + ] + ) + ], + macroSpecs: macroSpecs, + applyFixIts: ["Declare throws(JSException)"], + fixedSource: """ + @JSFunction + func greet(name: String) throws(JSException) -> String + """, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionAsync() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func fetch(url: String) async -> String + func fetch(url: String) async throws(JSException) -> String """, expandedSource: """ - func fetch(url: String) async -> String { - return await _$fetch(url) + func fetch(url: String) async throws(JSException) -> String { + return try await _$fetch(url) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionAsyncThrows() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func fetch(url: String) async throws -> String + func fetch(url: String) async throws(JSException) -> String """, expandedSource: """ - func fetch(url: String) async throws -> String { + func fetch(url: String) async throws(JSException) -> String { return try await _$fetch(url) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionWithUnderscoreParameter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func process(_ value: Int) -> Int + func process(_ value: Int) throws(JSException) -> Int """, expandedSource: """ - func process(_ value: Int) -> Int { - return _$process(value) + func process(_ value: Int) throws(JSException) -> Int { + return try _$process(value) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelFunctionWithMultipleParameters() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func add(a: Int, b: Int) -> Int + func add(a: Int, b: Int) throws(JSException) -> Int """, expandedSource: """ - func add(a: Int, b: Int) -> Int { - return _$add(a, b) + func add(a: Int, b: Int) throws(JSException) -> Int { + return try _$add(a, b) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func instanceMethod() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSFunction - func getName() -> String + func getName() throws(JSException) -> String } """, expandedSource: """ + @JSClass struct MyClass { - func getName() -> String { - return _$MyClass_getName(self.jsObject) + func getName() throws(JSException) -> String { + return try _$MyClass_getName(self.jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func staticMethod() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ struct MyClass { @JSFunction - static func create() -> MyClass + static func create() throws(JSException) -> MyClass } """, expandedSource: """ struct MyClass { - static func create() -> MyClass { - return _$create() + static func create() throws(JSException) -> MyClass { + return try _$MyClass_create() } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func classMethod() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ class MyClass { @JSFunction - class func create() -> MyClass + class func create() throws(JSException) -> MyClass } """, expandedSource: """ class MyClass { - class func create() -> MyClass { - return _$create() + class func create() throws(JSException) -> MyClass { + return try _$MyClass_create() } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func initializer() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSFunction - init(name: String) + init(name: String) throws(JSException) } """, expandedSource: """ + @JSClass struct MyClass { - init(name: String) { - let jsObject = _$MyClass_init(name) + init(name: String) throws(JSException) { + let jsObject = try _$MyClass_init(name) self.init(unsafelyWrapping: jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func initializerThrows() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSFunction - init(name: String) throws + init(name: String) throws(JSException) } """, expandedSource: """ + @JSClass struct MyClass { - init(name: String) throws { + init(name: String) throws(JSException) { let jsObject = try _$MyClass_init(name) self.init(unsafelyWrapping: jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func initializerAsyncThrows() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSFunction - init(name: String) async throws + init(name: String) async throws(JSException) } """, expandedSource: """ + @JSClass struct MyClass { - init(name: String) async throws { + init(name: String) async throws(JSException) { let jsObject = try await _$MyClass_init(name) self.init(unsafelyWrapping: jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func initializerWithoutEnclosingType() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction init() """, expandedSource: """ - init() + init() { + fatalError("@JSFunction init must be inside a type") + } """, diagnostics: [ DiagnosticSpec( message: "@JSFunction can only be applied to functions or initializers.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Move this initializer inside a JS wrapper type annotated with @JSClass.", + line: 1, + column: 1 + ) + ] ) ], - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func unsupportedDeclaration() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction var property: String @@ -309,69 +463,81 @@ import BridgeJSMacros DiagnosticSpec( message: "@JSFunction can only be applied to functions or initializers.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: + "Place @JSFunction on a function or initializer; use @JSGetter/@JSSetter for properties.", + line: 1, + column: 1 + ) + ] ) ], - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func enumInstanceMethod() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass enum MyEnum { @JSFunction - func getValue() -> Int + func getValue() throws(JSException) -> Int } """, expandedSource: """ + @JSClass enum MyEnum { - func getValue() -> Int { - return _$MyEnum_getValue(self.jsObject) + func getValue() throws(JSException) -> Int { + return try _$MyEnum_getValue(self.jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func actorInstanceMethod() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass actor MyActor { @JSFunction - func getValue() -> Int + func getValue() throws(JSException) -> Int } """, expandedSource: """ + @JSClass actor MyActor { - func getValue() -> Int { - return _$MyActor_getValue(self.jsObject) + func getValue() throws(JSException) -> Int { + return try _$MyActor_getValue(self.jsObject) } } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func functionWithExistingBody() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSFunction - func greet(name: String) -> String { + func greet(name: String) throws(JSException) -> String { return "Hello, \\(name)" } """, expandedSource: """ - func greet(name: String) -> String { - return _$greet(name) + func greet(name: String) throws(JSException) -> String { + return try _$greet(name) } """, - macros: ["JSFunction": JSFunctionMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSGetterMacroTests.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSGetterMacroTests.swift index 8c7f3c119..0e4cea844 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSGetterMacroTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSGetterMacroTests.swift @@ -1,15 +1,18 @@ import SwiftDiagnostics import SwiftSyntax -import SwiftSyntaxMacros -import SwiftSyntaxMacrosTestSupport +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport import Testing import BridgeJSMacros @Suite struct JSGetterMacroTests { private let indentationWidth: Trivia = .spaces(4) + private let macroSpecs: [String: MacroSpec] = [ + "JSGetter": MacroSpec(type: JSGetterMacro.self) + ] @Test func topLevelVariable() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var count: Int @@ -21,13 +24,13 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelLet() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter let constant: String @@ -39,20 +42,22 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func instanceProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSGetter var name: String } """, expandedSource: """ + @JSClass struct MyClass { var name: String { get throws(JSException) { @@ -61,20 +66,51 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, + ) + } + + @Test func instancePropertyRequiresJSClass() { + TestSupport.assertMacroExpansion( + """ + struct MyClass { + @JSGetter + var name: String + } + """, + expandedSource: """ + struct MyClass { + var name: String { + get throws(JSException) { + return try _$MyClass_name_get(self.jsObject) + } + } + } + """, + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func instanceLetProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSGetter let id: Int } """, expandedSource: """ + @JSClass struct MyClass { let id: Int { get throws(JSException) { @@ -83,13 +119,13 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func staticProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ struct MyClass { @JSGetter @@ -100,18 +136,25 @@ import BridgeJSMacros struct MyClass { static var version: String { get throws(JSException) { - return try _$version_get() + return try _$MyClass_version_get() } } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func classProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ class MyClass { @JSGetter @@ -122,25 +165,34 @@ import BridgeJSMacros class MyClass { class var version: String { get throws(JSException) { - return try _$version_get() + return try _$MyClass_version_get() } } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func enumProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass enum MyEnum { @JSGetter var value: Int } """, expandedSource: """ + @JSClass enum MyEnum { var value: Int { get throws(JSException) { @@ -149,20 +201,22 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func actorProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass actor MyActor { @JSGetter var state: String } """, expandedSource: """ + @JSClass actor MyActor { var state: String { get throws(JSException) { @@ -171,13 +225,13 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func variableWithExistingAccessor() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var count: Int { @@ -194,13 +248,13 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func variableWithInitializer() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var count: Int = 0 @@ -212,13 +266,13 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func multipleBindings() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var x: Int, y: Int @@ -228,19 +282,25 @@ import BridgeJSMacros """, diagnostics: [ DiagnosticSpec( - message: "@JSGetter can only be applied to single-variable declarations.", + message: "accessor macro can only be applied to a single variable", line: 1, column: 1, severity: .error - ) + ), + DiagnosticSpec( + message: "peer macro can only be applied to a single variable", + line: 1, + column: 1, + severity: .error + ), ], - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func unsupportedDeclaration() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter func test() {} @@ -253,16 +313,25 @@ import BridgeJSMacros message: "@JSGetter can only be applied to single-variable declarations.", line: 1, column: 1, - severity: .error + severity: .error, + notes: [ + NoteSpec( + message: "@JSGetter must be attached to a single stored or computed property.", + line: 1, + column: 1 + ) + ] ) ], - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } + #if canImport(SwiftSyntax602) + // https://github.com/swiftlang/swift-syntax/pull/2722 @Test func variableWithTrailingComment() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var count: Int // comment @@ -274,13 +343,14 @@ import BridgeJSMacros } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } + #endif @Test func variableWithUnderscoreName() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSGetter var _internal: String @@ -288,12 +358,12 @@ import BridgeJSMacros expandedSource: """ var _internal: String { get throws(JSException) { - return try _$internal_get() + return try _$_internal_get() } } """, - macros: ["JSGetter": JSGetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSSetterMacroTests.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSSetterMacroTests.swift index 83289e092..00d959921 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSSetterMacroTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/JSSetterMacroTests.swift @@ -1,15 +1,18 @@ import SwiftDiagnostics import SwiftSyntax -import SwiftSyntaxMacros -import SwiftSyntaxMacrosTestSupport +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport import Testing import BridgeJSMacros @Suite struct JSSetterMacroTests { private let indentationWidth: Trivia = .spaces(4) + private let macroSpecs: [String: MacroSpec] = [ + "JSSetter": MacroSpec(type: JSSetterMacro.self) + ] @Test func topLevelSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setFoo(_ value: Foo) throws(JSException) @@ -19,13 +22,13 @@ import BridgeJSMacros try _$foo_set(value) } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func topLevelSetterWithNamedParameter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setCount(count: Int) throws(JSException) @@ -35,33 +38,62 @@ import BridgeJSMacros try _$count_set(count) } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func instanceSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass struct MyClass { @JSSetter func setName(_ name: String) throws(JSException) } """, expandedSource: """ + @JSClass struct MyClass { func setName(_ name: String) throws(JSException) { try _$MyClass_name_set(self.jsObject, name) } } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, + ) + } + + @Test func instanceSetterRequiresJSClass() { + TestSupport.assertMacroExpansion( + """ + struct MyClass { + @JSSetter + func setName(_ name: String) throws(JSException) + } + """, + expandedSource: """ + struct MyClass { + func setName(_ name: String) throws(JSException) { + try _$MyClass_name_set(self.jsObject, name) + } + } + """, + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func staticSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ struct MyClass { @JSSetter @@ -71,17 +103,24 @@ import BridgeJSMacros expandedSource: """ struct MyClass { static func setVersion(_ version: String) throws(JSException) { - try _$version_set(version) + try _$MyClass_version_set(version) } } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func classSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ class MyClass { @JSSetter @@ -91,57 +130,68 @@ import BridgeJSMacros expandedSource: """ class MyClass { class func setConfig(_ config: Config) throws(JSException) { - try _$config_set(config) + try _$MyClass_config_set(config) } } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + diagnostics: [ + DiagnosticSpec( + message: "JavaScript members must be declared inside a @JSClass struct.", + line: 2, + column: 5 + ) + ], + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func enumSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass enum MyEnum { @JSSetter func setValue(_ value: Int) throws(JSException) } """, expandedSource: """ + @JSClass enum MyEnum { func setValue(_ value: Int) throws(JSException) { try _$MyEnum_value_set(self.jsObject, value) } } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func actorSetter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ + @JSClass actor MyActor { @JSSetter func setState(_ state: String) throws(JSException) } """, expandedSource: """ + @JSClass actor MyActor { func setState(_ state: String) throws(JSException) { try _$MyActor_state_set(self.jsObject, state) } } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func setterWithExistingBody() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setFoo(_ value: Foo) throws(JSException) { @@ -153,78 +203,211 @@ import BridgeJSMacros try _$foo_set(value) } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func invalidSetterName() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func updateFoo(_ value: Foo) throws(JSException) """, expandedSource: """ - func updateFoo(_ value: Foo) throws(JSException) + func updateFoo(_ value: Foo) throws(JSException) { + fatalError("@JSSetter function name must start with 'set' followed by a property name") + } """, diagnostics: [ DiagnosticSpec( message: "@JSSetter function name must start with 'set' followed by a property name (e.g., 'setFoo').", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Setter names must start with 'set' followed by the property name.", + line: 2, + column: 6 + ) + ], + fixIts: [ + FixItSpec(message: "Rename setter to 'setFoo'") + ] ) ], - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func setterNameTooShort() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func set(_ value: Foo) throws(JSException) """, expandedSource: """ - func set(_ value: Foo) throws(JSException) + func set(_ value: Foo) throws(JSException) { + fatalError("@JSSetter function name must start with 'set' followed by a property name") + } """, diagnostics: [ DiagnosticSpec( message: "@JSSetter function name must start with 'set' followed by a property name (e.g., 'setFoo').", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "Setter names must start with 'set' followed by the property name.", + line: 2, + column: 6 + ) + ], + fixIts: [ + FixItSpec(message: "Rename setter to 'setFoo'") + ] ) ], - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func setterWithoutParameter() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setFoo() throws(JSException) """, expandedSource: """ - func setFoo() throws(JSException) + func setFoo() throws(JSException) { + fatalError("@JSSetter function must have at least one parameter") + } """, diagnostics: [ DiagnosticSpec( message: "@JSSetter function must have at least one parameter.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "@JSSetter needs a parameter for the value being assigned.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Add a value parameter to the setter") + ] ) ], - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + applyFixIts: ["Add a value parameter to the setter"], + fixedSource: """ + @JSSetter + func setFoo(_ value: <#Type#>) throws(JSException) + """, + indentationWidth: indentationWidth, + ) + } + + @Test func setterMissingThrows() { + TestSupport.assertMacroExpansion( + """ + @JSSetter + func setFoo(_ value: Foo) + """, + expandedSource: """ + func setFoo(_ value: Foo) { + try _$foo_set(value) + } + """, + diagnostics: [ + DiagnosticSpec( + message: "@JSSetter function must declare throws(JSException).", + line: 1, + column: 1, + notes: [ + NoteSpec( + message: "@JSSetter must propagate JavaScript errors as JSException.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Declare throws(JSException)") + ] + ) + ], + macroSpecs: macroSpecs, + applyFixIts: ["Declare throws(JSException)"], + fixedSource: """ + @JSSetter + func setFoo(_ value: Foo) throws(JSException) + """, + indentationWidth: indentationWidth, + ) + } + + @Test func setterThrowsWrongType() { + TestSupport.assertMacroExpansion( + """ + @JSSetter + func setFoo(_ value: Foo) throws(CustomError) + """, + expandedSource: """ + func setFoo(_ value: Foo) throws(CustomError) { + try _$foo_set(value) + } + """, + diagnostics: [ + DiagnosticSpec( + message: "@JSSetter function must declare throws(JSException).", + line: 1, + column: 1, + notes: [ + NoteSpec( + message: "@JSSetter must propagate JavaScript errors as JSException.", + line: 1, + column: 1 + ) + ], + fixIts: [ + FixItSpec(message: "Declare throws(JSException)") + ] + ) + ], + macroSpecs: macroSpecs, + applyFixIts: ["Declare throws(JSException)"], + fixedSource: """ + @JSSetter + func setFoo(_ value: Foo) throws(JSException) + """, + indentationWidth: indentationWidth, + ) + } + + @Test func setterThrowsErrorAccepted() { + TestSupport.assertMacroExpansion( + """ + @JSSetter + func setFoo(_ value: Foo) throws(Error) + """, + expandedSource: """ + func setFoo(_ value: Foo) throws(Error) { + try _$foo_set(value) + } + """, + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func unsupportedDeclaration() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter var property: String @@ -236,16 +419,23 @@ import BridgeJSMacros DiagnosticSpec( message: "@JSSetter can only be applied to functions.", line: 1, - column: 1 + column: 1, + notes: [ + NoteSpec( + message: "@JSSetter should be attached to a method that writes a JavaScript property.", + line: 1, + column: 1 + ) + ] ) ], - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func setterWithMultipleWords() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setConnectionTimeout(_ timeout: Int) throws(JSException) @@ -255,13 +445,13 @@ import BridgeJSMacros try _$connectionTimeout_set(timeout) } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } @Test func setterWithSingleLetterProperty() { - assertMacroExpansion( + TestSupport.assertMacroExpansion( """ @JSSetter func setX(_ x: Int) throws(JSException) @@ -271,8 +461,8 @@ import BridgeJSMacros try _$x_set(x) } """, - macros: ["JSSetter": JSSetterMacro.self], - indentationWidth: indentationWidth + macroSpecs: macroSpecs, + indentationWidth: indentationWidth, ) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/TestSupport.swift b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/TestSupport.swift new file mode 100644 index 000000000..84e343281 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSMacrosTests/TestSupport.swift @@ -0,0 +1,52 @@ +import SwiftSyntaxMacrosGenericTestSupport +import Testing +import SwiftSyntax +import SwiftDiagnostics +import SwiftSyntaxMacroExpansion + +enum TestSupport { + static func failureHandler(spec: TestFailureSpec) { + Issue.record( + Comment(rawValue: spec.message), + sourceLocation: .init( + fileID: spec.location.fileID, + filePath: spec.location.filePath, + line: spec.location.line, + column: spec.location.column + ) + ) + } + + static func assertMacroExpansion( + _ originalSource: String, + expandedSource expectedExpandedSource: String, + diagnostics: [DiagnosticSpec] = [], + macroSpecs: [String: MacroSpec], + applyFixIts: [String]? = nil, + fixedSource expectedFixedSource: String? = nil, + testModuleName: String = "TestModule", + testFileName: String = "test.swift", + indentationWidth: Trivia = .spaces(4), + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + SwiftSyntaxMacrosGenericTestSupport.assertMacroExpansion( + originalSource, + expandedSource: expectedExpandedSource, + diagnostics: diagnostics, + macroSpecs: macroSpecs, + applyFixIts: applyFixIts, + fixedSource: expectedFixedSource, + testModuleName: testModuleName, + testFileName: testFileName, + indentationWidth: indentationWidth, + failureHandler: TestSupport.failureHandler, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift new file mode 100644 index 000000000..9754fbced --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -0,0 +1,187 @@ +import Foundation +import SwiftSyntax +import SwiftParser +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct BridgeJSCodegenTests { + static let inputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( + "Inputs" + ).appendingPathComponent("MacroSwift") + static let multifileInputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .appendingPathComponent("Inputs").appendingPathComponent("MacroSwift").appendingPathComponent("Multifile") + + private func snapshotCodegen( + skeleton: BridgeJSSkeleton, + name: String, + filePath: String = #filePath, + function: String = #function, + sourceLocation: Testing.SourceLocation = #_sourceLocation + ) throws { + var swiftParts: [String] = [] + if let closureSupport = try ClosureCodegen().renderSupport(for: skeleton) { + swiftParts.append(closureSupport) + } + if let exported = skeleton.exported { + let exportSwift = ExportSwift( + progress: .silent, + moduleName: skeleton.moduleName, + skeleton: exported + ) + if let s = try exportSwift.finalize() { + swiftParts.append(s) + } + } + if let imported = skeleton.imported { + let importTS = ImportTS(progress: .silent, moduleName: skeleton.moduleName, skeleton: imported) + if let s = try importTS.finalize() { + swiftParts.append(s) + } + } + let combinedSwift = + swiftParts + .map { $0.trimmingCharacters(in: .newlines) } + .filter { !$0.isEmpty } + .joined(separator: "\n\n") + try assertSnapshot( + name: name, + filePath: filePath, + function: function, + sourceLocation: sourceLocation, + input: combinedSwift.data(using: String.Encoding.utf8)!, + fileExtension: "swift" + ) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let skeletonData = try encoder.encode(skeleton) + try assertSnapshot( + name: name, + filePath: filePath, + function: function, + sourceLocation: sourceLocation, + input: skeletonData, + fileExtension: "json" + ) + } + + static func collectInputs() -> [String] { + let fileManager = FileManager.default + let inputs = try! fileManager.contentsOfDirectory(atPath: Self.inputsDirectory.path) + return inputs.filter { $0.hasSuffix(".swift") }.sorted() + } + + @Test(arguments: collectInputs()) + func codegenSnapshot(input: String) throws { + let url = Self.inputsDirectory.appendingPathComponent(input) + let name = url.deletingPathExtension().lastPathComponent + let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + swiftAPI.addSourceFile(sourceFile, inputFilePath: input) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: name) + } + + @Test(arguments: [ + "Namespaces.swift", + "StaticFunctions.swift", + "StaticProperties.swift", + "EnumNamespace.swift", + ]) + func codegenSnapshotWithGlobal(input: String) throws { + let url = Self.inputsDirectory.appendingPathComponent(input) + let name = url.deletingPathExtension().lastPathComponent + let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: true) + swiftAPI.addSourceFile(sourceFile, inputFilePath: input) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: name + ".Global") + } + + @Test + func codegenCrossFileTypeResolution() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let classBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassB.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classBURL, encoding: .utf8)), + inputFilePath: "CrossFileClassB.swift" + ) + let classAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassA.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classAURL, encoding: .utf8)), + inputFilePath: "CrossFileClassA.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileTypeResolution") + } + + @Test + func codegenCrossFileTypeResolutionReverseOrder() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let classAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassA.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classAURL, encoding: .utf8)), + inputFilePath: "CrossFileClassA.swift" + ) + let classBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassB.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classBURL, encoding: .utf8)), + inputFilePath: "CrossFileClassB.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileTypeResolution.ReverseOrder") + } + + @Test + func codegenCrossFileFunctionTypes() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let functionBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionB.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: functionBURL, encoding: .utf8)), + inputFilePath: "CrossFileFunctionB.swift" + ) + let functionAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionA.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: functionAURL, encoding: .utf8)), + inputFilePath: "CrossFileFunctionA.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileFunctionTypes") + } + + @Test + func codegenCrossFileFunctionTypesReverseOrder() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let functionAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionA.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: functionAURL, encoding: .utf8)), + inputFilePath: "CrossFileFunctionA.swift" + ) + let functionBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionB.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: functionBURL, encoding: .utf8)), + inputFilePath: "CrossFileFunctionB.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileFunctionTypes.ReverseOrder") + } + + @Test + func codegenSkipsEmptySkeletons() throws { + let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) + let importedURL = Self.multifileInputsDirectory.appendingPathComponent("ImportedFunctions.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: importedURL, encoding: .utf8)), + inputFilePath: "ImportedFunctions.swift" + ) + let exportedOnlyURL = Self.multifileInputsDirectory.appendingPathComponent("ExportedOnly.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: exportedOnlyURL, encoding: .utf8)), + inputFilePath: "ExportedOnly.swift" + ) + let skeleton = try swiftAPI.finalize() + #expect(skeleton.exported == nil, "Empty exported skeleton should be omitted") + try snapshotCodegen(skeleton: skeleton, name: "CrossFileSkipsEmptySkeletons") + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 16de8617e..711b04512 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -4,7 +4,6 @@ import SwiftParser import Testing @testable import BridgeJSLink @testable import BridgeJSCore -@testable import TS2Swift @testable import BridgeJSSkeleton @Suite struct BridgeJSLinkTests { @@ -36,10 +35,7 @@ import Testing static let inputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( "Inputs" - ) - - static let importMacroInputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .appendingPathComponent("ImportMacroInputs") + ).appendingPathComponent("MacroSwift") static func collectInputs(extension: String) -> [String] { let fileManager = FileManager.default @@ -47,56 +43,9 @@ import Testing return inputs.filter { $0.hasSuffix(`extension`) } } - static func collectImportMacroInputs() -> [String] { - let fileManager = FileManager.default - let inputs = try! fileManager.contentsOfDirectory(atPath: Self.importMacroInputsDirectory.path) - return inputs.filter { $0.hasSuffix(".swift") } - } - @Test(arguments: collectInputs(extension: ".swift")) - func snapshotExport(input: String) throws { + func snapshot(input: String) throws { let url = Self.inputsDirectory.appendingPathComponent(input) - let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - swiftAPI.addSourceFile(sourceFile, inputFilePath: input) - let name = url.deletingPathExtension().lastPathComponent - - let outputSkeleton = try swiftAPI.finalize() - let bridgeJSLink: BridgeJSLink = BridgeJSLink( - skeletons: [outputSkeleton], - sharedMemory: false - ) - try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".Export") - } - - @Test(arguments: collectInputs(extension: ".d.ts")) - func snapshotImport(input: String) throws { - let url = Self.inputsDirectory.appendingPathComponent(input) - let name = url.deletingPathExtension().deletingPathExtension().lastPathComponent - let tsconfigPath = url.deletingLastPathComponent().appendingPathComponent("tsconfig.json") - - let nodePath = try #require(which("node")) - let swiftSource = try invokeTS2Swift( - dtsFile: url.path, - tsconfigPath: tsconfigPath.path, - nodePath: nodePath, - progress: .silent - ) - - let sourceFile = Parser.parse(source: swiftSource) - let importSwift = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).Macros.swift") - let skeleton = try importSwift.finalize() - let bridgeJSLink = BridgeJSLink( - skeletons: [skeleton], - sharedMemory: false - ) - try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".Import") - } - - @Test(arguments: collectImportMacroInputs()) - func snapshotImportMacroInput(input: String) throws { - let url = Self.importMacroInputsDirectory.appendingPathComponent(input) let name = url.deletingPathExtension().lastPathComponent let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) @@ -108,7 +57,7 @@ import Testing encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let unifiedData = try encoder.encode(importResult) try bridgeJSLink.addSkeletonFile(data: unifiedData) - try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".ImportMacros") + try snapshot(bridgeJSLink: bridgeJSLink, name: name) } @Test(arguments: [ @@ -130,7 +79,7 @@ import Testing ], sharedMemory: false ) - try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".Global.Export") + try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".Global") } @Test @@ -154,6 +103,6 @@ import Testing ], sharedMemory: false ) - try snapshot(bridgeJSLink: bridgeJSLink, name: "MixedModules.Export") + try snapshot(bridgeJSLink: bridgeJSLink, name: "MixedModules") } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift new file mode 100644 index 000000000..500a5db95 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -0,0 +1,182 @@ +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSCore + +@Suite struct DiagnosticsTests { + /// Returns the first parameter's type node from a function in the source (the first `@JS func`-like decl), for pinpointing diagnostics. + private func firstParameterTypeNode(source: String) -> TypeSyntax? { + let tree = Parser.parse(source: source) + for stmt in tree.statements { + if let funcDecl = stmt.item.as(FunctionDeclSyntax.self), + let firstParam = funcDecl.signature.parameterClause.parameters.first + { + return firstParam.type + } + } + return nil + } + + @Test + func diagnosticIncludesLocationSourceAndHint() throws { + let source = "@JS func foo(_ bar: A) {}\n" + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError( + node: typeNode, + message: "Unsupported type 'A'.", + hint: "Only primitive types and types defined in the same module are allowed" + ) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + let expectedPrefix = """ + :1:21: error: Unsupported type 'A'. + 1 | @JS func foo(_ bar: A) {} + | `- error: Unsupported type 'A'. + 2 | + """.trimmingCharacters(in: .whitespacesAndNewlines) + #expect(description.hasPrefix(expectedPrefix)) + #expect(description.contains("Hint: Only primitive types and types defined in the same module are allowed")) + } + + @Test + func diagnosticOmitsHintWhenNotProvided() throws { + let source = "@JS static func foo() {}\n" + let tree = Parser.parse(source: source) + let diagnostic = DiagnosticError( + node: tree, + message: "Top-level functions cannot be static", + hint: nil + ) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + let expectedPrefix = """ + :1:1: error: Top-level functions cannot be static + 1 | @JS static func foo() {} + | `- error: Top-level functions cannot be static + 2 | + """.trimmingCharacters(in: .whitespacesAndNewlines) + #expect(description.hasPrefix(expectedPrefix)) + #expect(!description.contains("Hint:")) + } + + @Test + func diagnosticUsesGivenFileNameNotStdin() throws { + let source = "@JS func foo(_ bar: A) {}\n" + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError( + node: typeNode, + message: "Unsupported type 'A'.", + hint: nil + ) + let description = diagnostic.formattedDescription(fileName: "Sources/Foo.swift", colorize: false) + #expect(description.hasPrefix("Sources/Foo.swift:1:21: error: Unsupported type 'A'.")) + } + + @Test + func diagnosticWithColorizeTrueIncludesANSISequences() throws { + let source = "@JS func foo(_ bar: A) {}\n" + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError( + node: typeNode, + message: "Unsupported type 'A'.", + hint: nil + ) + let description = diagnostic.formattedDescription(fileName: "-", colorize: true) + let esc = "\u{001B}" + let boldRed = "\(esc)[1;31m" + let boldDefault = "\(esc)[1;39m" + let reset = "\(esc)[0;0m" + let cyan = "\(esc)[0;36m" + let underline = "\(esc)[4;39m" + let expected = + ":1:21: \(boldRed)error: \(boldDefault)Unsupported type 'A'.\(reset)\n" + + "\(cyan) 1\(reset) | @JS func foo(_ bar: \(underline)A\(reset)) {}\n" + + " | `- \(boldRed)error: \(boldDefault)Unsupported type 'A'.\(reset)\n" + + "\(cyan) 2\(reset) | " + #expect(description == expected) + } + + // MARK: - Context source lines + + @Test + func showsOnePreviousLineWhenErrorNotOnFirstLine() throws { + let source = """ + preamble + @JS func foo(_ bar: A) {} + """ + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError(node: typeNode, message: "Unsupported type 'A'.", hint: nil) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + #expect(description.contains(" 1 | preamble")) + #expect(description.contains(" 2 | @JS func foo(_ bar: A) {}")) + #expect(description.contains(":2:")) + } + + @Test + func showsThreePreviousLinesWhenAvailable() throws { + let source = """ + first + second + third + @JS func foo(_ bar: A) {} + """ + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError(node: typeNode, message: "Unsupported type 'A'.", hint: nil) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + #expect(description.contains(" 1 | first")) + #expect(description.contains(" 2 | second")) + #expect(description.contains(" 3 | third")) + #expect(description.contains(" 4 | @JS func foo(_ bar: A) {}")) + #expect(description.contains(":4:")) + } + + @Test + func capsContextAtThreePreviousLines() throws { + let source = """ + line0 + line1 + line2 + line3 + @JS func foo(_ bar: A) {} + """ + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError(node: typeNode, message: "Unsupported type 'A'.", hint: nil) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + #expect(!description.contains(" 1 | line0")) + #expect(description.contains(" 2 | line1")) + #expect(description.contains(" 3 | line2")) + #expect(description.contains(" 4 | line3")) + #expect(description.contains(" 5 | @JS func foo(_ bar: A) {}")) + #expect(description.contains(":5:")) + } + + @Test + func includesNextLineAfterErrorLine() throws { + let source = """ + @JS func foo( + _ bar: A + ) {} + """ + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError(node: typeNode, message: "Unsupported type 'A'.", hint: nil) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + #expect(description.contains(" 1 | @JS func foo(")) + #expect(description.contains(" 2 | _ bar: A")) + #expect(description.contains(" 3 | ) {}")) + #expect(description.contains(":2:")) + } + + @Test + func omitsNextLineWhenErrorIsOnLastLine() throws { + let source = """ + preamble + @JS func foo(_ bar: A) + """ + let typeNode = try #require(firstParameterTypeNode(source: source)) + let diagnostic = DiagnosticError(node: typeNode, message: "Unsupported type 'A'.", hint: nil) + let description = diagnostic.formattedDescription(fileName: "-", colorize: false) + #expect(description.contains(" 2 | @JS func foo(_ bar: A)")) + #expect(description.contains(":2:")) + // No line 3 in source, so output must not show a " 3 |" context line after the pointer + #expect(!description.contains(" 3 |")) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportSwiftTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportSwiftTests.swift deleted file mode 100644 index fb31ac837..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ExportSwiftTests.swift +++ /dev/null @@ -1,158 +0,0 @@ -import Foundation -import SwiftSyntax -import SwiftParser -import Testing - -@testable import BridgeJSCore -@testable import BridgeJSSkeleton - -@Suite struct ExportSwiftTests { - private func snapshot( - skeleton: BridgeJSSkeleton, - name: String? = nil, - filePath: String = #filePath, - function: String = #function, - sourceLocation: Testing.SourceLocation = #_sourceLocation - ) throws { - guard let exported = skeleton.exported else { return } - let exportSwift = ExportSwift( - progress: .silent, - moduleName: skeleton.moduleName, - skeleton: exported - ) - let closureSupport = try ClosureCodegen().renderSupport(for: skeleton) - let exportResult = try #require(try exportSwift.finalize()) - let outputSwift = ([closureSupport, exportResult] as [String?]) - .compactMap { $0?.trimmingCharacters(in: .newlines) } - .filter { !$0.isEmpty } - .joined(separator: "\n\n") - try assertSnapshot( - name: name, - filePath: filePath, - function: function, - sourceLocation: sourceLocation, - input: outputSwift.data(using: .utf8)!, - fileExtension: "swift" - ) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let outputSkeletonData = try encoder.encode(exported) - try assertSnapshot( - name: name, - filePath: filePath, - function: function, - sourceLocation: sourceLocation, - input: outputSkeletonData, - fileExtension: "json" - ) - } - - static let inputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( - "Inputs" - ) - - static let multifileInputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .appendingPathComponent( - "MultifileInputs" - ) - - static func collectInputs() -> [String] { - let fileManager = FileManager.default - let inputs = try! fileManager.contentsOfDirectory(atPath: Self.inputsDirectory.path) - return inputs.filter { $0.hasSuffix(".swift") } - } - - @Test(arguments: collectInputs()) - func snapshot(input: String) throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - let url = Self.inputsDirectory.appendingPathComponent(input) - let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - swiftAPI.addSourceFile(sourceFile, inputFilePath: input) - let name = url.deletingPathExtension().lastPathComponent - try snapshot(skeleton: swiftAPI.finalize(), name: name) - } - - @Test(arguments: [ - "Namespaces.swift", - "StaticFunctions.swift", - "StaticProperties.swift", - "EnumNamespace.swift", - ]) - func snapshotWithGlobal(input: String) throws { - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: true) - let url = Self.inputsDirectory.appendingPathComponent(input) - let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - swiftAPI.addSourceFile(sourceFile, inputFilePath: input) - let name = url.deletingPathExtension().lastPathComponent - try snapshot(skeleton: swiftAPI.finalize(), name: name + ".Global") - } - - @Test - func snapshotCrossFileTypeResolution() throws { - // Test that types defined in one file can be referenced from another file - // This tests the fix for cross-file type resolution in BridgeJS - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - - // Add ClassB first, then ClassA (which references ClassB) - let classBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassB.swift") - let classBSourceFile = Parser.parse(source: try String(contentsOf: classBURL, encoding: .utf8)) - swiftAPI.addSourceFile(classBSourceFile, inputFilePath: "CrossFileClassB.swift") - - let classAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassA.swift") - let classASourceFile = Parser.parse(source: try String(contentsOf: classAURL, encoding: .utf8)) - swiftAPI.addSourceFile(classASourceFile, inputFilePath: "CrossFileClassA.swift") - - try snapshot(skeleton: swiftAPI.finalize(), name: "CrossFileTypeResolution") - } - - @Test - func snapshotCrossFileTypeResolutionReverseOrder() throws { - // Test that types can be resolved regardless of the order files are added - // Add ClassA first (which references ClassB), then ClassB - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - - let classAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassA.swift") - let classASourceFile = Parser.parse(source: try String(contentsOf: classAURL, encoding: .utf8)) - swiftAPI.addSourceFile(classASourceFile, inputFilePath: "CrossFileClassA.swift") - - let classBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileClassB.swift") - let classBSourceFile = Parser.parse(source: try String(contentsOf: classBURL, encoding: .utf8)) - swiftAPI.addSourceFile(classBSourceFile, inputFilePath: "CrossFileClassB.swift") - - try snapshot(skeleton: swiftAPI.finalize(), name: "CrossFileTypeResolution.ReverseOrder") - } - - @Test - func snapshotCrossFileFunctionTypes() throws { - // Test that functions and methods can use cross-file types as parameters and return types - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - - // Add FunctionB first, then FunctionA (which references FunctionB in methods and functions) - let functionBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionB.swift") - let functionBSourceFile = Parser.parse(source: try String(contentsOf: functionBURL, encoding: .utf8)) - swiftAPI.addSourceFile(functionBSourceFile, inputFilePath: "CrossFileFunctionB.swift") - - let functionAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionA.swift") - let functionASourceFile = Parser.parse(source: try String(contentsOf: functionAURL, encoding: .utf8)) - swiftAPI.addSourceFile(functionASourceFile, inputFilePath: "CrossFileFunctionA.swift") - - try snapshot(skeleton: swiftAPI.finalize(), name: "CrossFileFunctionTypes") - } - - @Test - func snapshotCrossFileFunctionTypesReverseOrder() throws { - // Test that function types can be resolved regardless of the order files are added - let swiftAPI = SwiftToSkeleton(progress: .silent, moduleName: "TestModule", exposeToGlobal: false) - - // Add FunctionA first (which references FunctionB), then FunctionB - let functionAURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionA.swift") - let functionASourceFile = Parser.parse(source: try String(contentsOf: functionAURL, encoding: .utf8)) - swiftAPI.addSourceFile(functionASourceFile, inputFilePath: "CrossFileFunctionA.swift") - - let functionBURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileFunctionB.swift") - let functionBSourceFile = Parser.parse(source: try String(contentsOf: functionBURL, encoding: .utf8)) - swiftAPI.addSourceFile(functionBSourceFile, inputFilePath: "CrossFileFunctionB.swift") - - try snapshot(skeleton: swiftAPI.finalize(), name: "CrossFileFunctionTypes.ReverseOrder") - } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportTSTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportTSTests.swift deleted file mode 100644 index 89c7dd11d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportTSTests.swift +++ /dev/null @@ -1,101 +0,0 @@ -import Testing -import Foundation -import SwiftParser -@testable import BridgeJSCore -@testable import TS2Swift -@testable import BridgeJSSkeleton - -@Suite struct ImportTSTests { - static let inputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( - "Inputs" - ) - static let importMacroInputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .appendingPathComponent("ImportMacroInputs") - - static func collectInputs() -> [String] { - let fileManager = FileManager.default - let inputs = try! fileManager.contentsOfDirectory(atPath: Self.inputsDirectory.path) - return inputs.filter { $0.hasSuffix(".d.ts") } - } - - static func collectImportMacroInputs() -> [String] { - let fileManager = FileManager.default - let inputs = try! fileManager.contentsOfDirectory(atPath: Self.importMacroInputsDirectory.path) - return inputs.filter { $0.hasSuffix(".swift") } - } - - @Test(arguments: collectInputs()) - func snapshot(input: String) throws { - let url = Self.inputsDirectory.appendingPathComponent(input) - let name = url.deletingPathExtension().deletingPathExtension().deletingPathExtension().lastPathComponent - let nodePath = try #require(which("node")) - let tsconfigPath = url.deletingLastPathComponent().appendingPathComponent("tsconfig.json") - - let swiftSource = try invokeTS2Swift( - dtsFile: url.path, - tsconfigPath: tsconfigPath.path, - nodePath: nodePath, - progress: .silent - ) - try assertSnapshot( - name: name + ".Macros", - filePath: #filePath, - function: #function, - input: swiftSource.data(using: .utf8)!, - fileExtension: "swift" - ) - - let sourceFile = Parser.parse(source: swiftSource) - let importSwift = SwiftToSkeleton(progress: .silent, moduleName: "Check", exposeToGlobal: false) - importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).Macros.swift") - let skeleton = try importSwift.finalize() - - guard let imported = skeleton.imported else { return } - - let importTS = ImportTS(progress: .silent, moduleName: "Check", skeleton: imported) - let importResult = try #require(try importTS.finalize()) - let closureSupport = try ClosureCodegen().renderSupport( - for: BridgeJSSkeleton(moduleName: "Check", imported: imported) - ) - let outputSwift = ([closureSupport, importResult] as [String?]) - .compactMap { $0?.trimmingCharacters(in: .newlines) } - .filter { !$0.isEmpty } - .joined(separator: "\n\n") - try assertSnapshot( - name: name, - filePath: #filePath, - function: #function, - input: outputSwift.data(using: .utf8)!, - fileExtension: "swift" - ) - } - - @Test(arguments: collectImportMacroInputs()) - func snapshotImportMacroInput(input: String) throws { - let url = Self.importMacroInputsDirectory.appendingPathComponent(input) - let name = url.deletingPathExtension().lastPathComponent - - let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - let importSwift = SwiftToSkeleton(progress: .silent, moduleName: "Check", exposeToGlobal: false) - importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).swift") - let skeleton = try importSwift.finalize() - - guard let imported = skeleton.imported else { return } - let importTS = ImportTS(progress: .silent, moduleName: "Check", skeleton: imported) - let importResult = try #require(try importTS.finalize()) - let closureSupport = try ClosureCodegen().renderSupport( - for: BridgeJSSkeleton(moduleName: "Check", imported: imported) - ) - let outputSwift = ([closureSupport, importResult] as [String?]) - .compactMap { $0?.trimmingCharacters(in: .newlines) } - .filter { !$0.isEmpty } - .joined(separator: "\n\n") - try assertSnapshot( - name: name + ".ImportMacros", - filePath: #filePath, - function: #function, - input: outputSwift.data(using: .utf8)!, - fileExtension: "swift" - ) - } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayParameter.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayParameter.d.ts deleted file mode 100644 index 59674e071..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayParameter.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function checkArray(a: number[]): void; -export function checkArrayWithLength(a: number[], b: number): void; -export function checkArray(a: Array): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ImportedTypeInExportedInterface.swift deleted file mode 100644 index 9e3524284..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ImportedTypeInExportedInterface.swift +++ /dev/null @@ -1,7 +0,0 @@ -@JSClass class Foo { - @JSFunction init() throws(JSException) -} - -@JS func makeFoo() throws(JSException) -> Foo { - return try Foo() -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ArrayTypes.swift similarity index 69% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayTypes.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ArrayTypes.swift index 8454b7520..0cea90512 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ArrayTypes.swift @@ -54,3 +54,16 @@ @JS func processItemArray(_ items: [Item]) -> [Item] @JS func processNestedItemArray(_ items: [[Item]]) -> [[Item]] + +@JS func processJSObjectArray(_ objects: [JSObject]) -> [JSObject] +@JS func processOptionalJSObjectArray(_ objects: [JSObject?]) -> [JSObject?] +@JS func processNestedJSObjectArray(_ objects: [[JSObject]]) -> [[JSObject]] + +@JSFunction func checkArray(_ a: JSObject) throws(JSException) -> Void +@JSFunction func checkArrayWithLength(_ a: JSObject, _ b: Double) throws(JSException) -> Void + +@JSFunction func importProcessNumbers(_ values: [Double]) throws(JSException) -> Void +@JSFunction func importGetNumbers() throws(JSException) -> [Double] +@JSFunction func importTransformNumbers(_ values: [Double]) throws(JSException) -> [Double] +@JSFunction func importProcessStrings(_ values: [String]) throws(JSException) -> [String] +@JSFunction func importProcessBooleans(_ values: [Bool]) throws(JSException) -> [Bool] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Async.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DefaultParameters.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/DefaultParameters.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DefaultParameters.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift new file mode 100644 index 000000000..c699ea79b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DictionaryTypes.swift @@ -0,0 +1,15 @@ +@JS class Box { + var value: Int + + init(value: Int) { + self.value = value + } +} + +@JS func mirrorDictionary(_ values: [String: Int]) -> [String: Int] +@JS func optionalDictionary(_ values: [String: String]?) -> [String: String]? +@JS func nestedDictionary(_ values: [String: [Int]]) -> [String: [Int]] +@JS func boxDictionary(_ boxes: [String: Box]) -> [String: Box] +@JS func optionalBoxDictionary(_ boxes: [String: Box?]) -> [String: Box?] + +@JSFunction func importMirrorDictionary(_ values: [String: Double]) throws(JSException) -> [String: Double] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValue.swift similarity index 52% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumAssociatedValue.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValue.swift index efb6cd1b1..a0e6cbfeb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValue.swift @@ -55,3 +55,66 @@ enum APIOptionalResult { } @JS func roundTripOptionalAPIOptionalResult(result: APIOptionalResult?) -> APIOptionalResult? @JS func compareAPIResults(result1: APIOptionalResult?, result2: APIOptionalResult?) -> APIOptionalResult? + +@JS enum Precision: Float { + case rough = 0.1 + case fine = 0.001 +} + +@JS enum CardinalDirection { + case north + case south + case east + case west +} + +@JS +enum TypedPayloadResult { + case precision(Precision) + case direction(CardinalDirection) + case optPrecision(Precision?) + case optDirection(CardinalDirection?) + case empty +} + +@JS func roundTripTypedPayloadResult(_ result: TypedPayloadResult) -> TypedPayloadResult +@JS func roundTripOptionalTypedPayloadResult(_ result: TypedPayloadResult?) -> TypedPayloadResult? + +@JS struct Point { + var x: Double + var y: Double +} + +@JS class User { + var name: String + + init(name: String) { + self.name = name + } +} + +@JS +enum AllTypesResult { + case structPayload(Point) + case classPayload(User) + case jsObjectPayload(JSObject) + case nestedEnum(APIResult) + case arrayPayload([Int]) + case empty +} + +@JS func roundTripAllTypesResult(_ result: AllTypesResult) -> AllTypesResult +@JS func roundTripOptionalAllTypesResult(_ result: AllTypesResult?) -> AllTypesResult? + +@JS +enum OptionalAllTypesResult { + case optStruct(Point?) + case optClass(User?) + case optJSObject(JSObject?) + case optNestedEnum(APIResult?) + case optArray([Int]?) + case empty +} + +@JS func roundTripOptionalPayloadResult(_ result: OptionalAllTypesResult) -> OptionalAllTypesResult +@JS func roundTripOptionalPayloadResultOpt(_ result: OptionalAllTypesResult?) -> OptionalAllTypesResult? diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCase.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumCase.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCase.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift similarity index 77% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumNamespace.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift index 26a4e9c3a..dbf044834 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumNamespace.swift @@ -53,4 +53,17 @@ enum Internal { } } -// TODO: Add namespace enum with static functions when supported +@JS(namespace: "Services.Graph") +enum GraphOperations { + @JS static func createGraph(rootId: Int) -> Int { + return rootId * 10 + } + + @JS static func nodeCount(graphId: Int) -> Int { + return graphId + } + + @JS static func validate(graphId: Int) throws(JSException) -> Bool { + return graphId > 0 + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumRawType.swift similarity index 91% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumRawType.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumRawType.swift index 13b502eac..6e18c913c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumRawType.swift @@ -124,3 +124,13 @@ @JS func processTheme(_ theme: Theme) -> HttpStatus @JS func convertPriority(_ status: HttpStatus) -> Priority @JS func validateSession(_ session: SessionId) -> Theme + +enum FeatureFlag: String { + case foo = "foo" + case bar = "bar" +} +extension FeatureFlag: _BridgedSwiftEnumNoPayload {} + +@JSFunction func takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void + +@JSFunction func returnsFeatureFlag() throws(JSException) -> FeatureFlag diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/GlobalGetter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GlobalGetter.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/GlobalGetter.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GlobalGetter.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/GlobalThisImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GlobalThisImports.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/GlobalThisImports.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GlobalThisImports.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift new file mode 100644 index 000000000..cd9142a26 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift @@ -0,0 +1,2 @@ +@JSFunction func roundtrip(_ items: [Int]) throws(JSException) -> [Int] +@JSFunction func logStrings(_ items: [String]) throws(JSException) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportedTypeInExportedInterface.swift new file mode 100644 index 000000000..db167c5a9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportedTypeInExportedInterface.swift @@ -0,0 +1,17 @@ +@JSClass class Foo { + @JSFunction init() throws(JSException) +} + +@JS func makeFoo() throws(JSException) -> Foo { + return try Foo() +} + +@JS func processFooArray(_ foos: [Foo]) -> [Foo] +@JS func processOptionalFooArray(_ foos: [Foo?]) -> [Foo?] + +@JS struct FooContainer { + var foo: Foo + var optionalFoo: Foo? +} + +@JS func roundtripFooContainer(_ container: FooContainer) -> FooContainer diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/InvalidPropertyNames.swift new file mode 100644 index 000000000..ea5755dec --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/InvalidPropertyNames.swift @@ -0,0 +1,29 @@ +@JSFunction func createWeirdObject() throws(JSException) -> WeirdNaming + +@JSClass struct WeirdNaming { + @JSGetter var normalProperty: String + @JSSetter func setNormalProperty(_ value: String) throws(JSException) + @JSGetter(jsName: "property-with-dashes") var property_with_dashes: Double + @JSSetter(jsName: "property-with-dashes") func setProperty_with_dashes(_ value: Double) throws(JSException) + @JSGetter(jsName: "123invalidStart") var _123invalidStart: Bool + @JSSetter(jsName: "123invalidStart") func set_123invalidStart(_ value: Bool) throws(JSException) + @JSGetter(jsName: "property with spaces") var property_with_spaces: String + @JSSetter(jsName: "property with spaces") func setProperty_with_spaces(_ value: String) throws(JSException) + @JSGetter(jsName: "@specialChar") var _specialChar: Double + @JSSetter(jsName: "@specialChar") func set_specialChar(_ value: Double) throws(JSException) + @JSGetter var constructor: String + @JSSetter func setConstructor(_ value: String) throws(JSException) + @JSGetter var `for`: String + @JSSetter func setFor(_ value: String) throws(JSException) + @JSGetter var `Any`: String + @JSSetter(jsName: "Any") func setAny(_ value: String) throws(JSException) + @JSFunction func `as`() throws(JSException) -> Void + @JSFunction func `try`() throws(JSException) -> Void +} + +@JSClass(jsName: "$Weird") struct _Weird { + @JSFunction init() throws(JSException) + @JSFunction(jsName: "method-with-dashes") func method_with_dashes() throws(JSException) -> Void +} + +@JSFunction func createWeirdClass() throws(JSException) -> _Weird diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClass.swift new file mode 100644 index 000000000..6459f5354 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClass.swift @@ -0,0 +1,15 @@ +@JSClass struct Greeter { + @JSGetter var name: String + @JSSetter func setName(_ value: String) throws(JSException) + @JSGetter var age: Double + @JSFunction init(_ name: String) throws(JSException) + @JSFunction func greet() throws(JSException) -> String + @JSFunction func changeName(_ name: String) throws(JSException) -> Void +} + +@JSFunction func returnAnimatable() throws(JSException) -> Animatable + +@JSClass struct Animatable { + @JSFunction func animate(_ keyframes: JSObject, _ options: JSObject) throws(JSException) -> JSObject + @JSFunction func getAnimations(_ options: JSObject) throws(JSException) -> JSObject +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClassStaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClassStaticFunctions.swift new file mode 100644 index 000000000..c64952565 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSClassStaticFunctions.swift @@ -0,0 +1,12 @@ +@JSClass struct StaticBox { + @JSFunction static func create(_ value: Double) throws(JSException) -> StaticBox + @JSFunction func value() throws(JSException) -> Double + @JSFunction static func value() throws(JSException) -> Double + @JSFunction static func makeDefault() throws(JSException) -> StaticBox + @JSFunction(jsName: "with-dashes") static func dashed() throws(JSException) -> StaticBox +} + +@JSClass struct WithCtor { + @JSFunction init(_ value: Double) throws(JSException) + @JSFunction static func create(_ value: Double) throws(JSException) -> WithCtor +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSValue.swift new file mode 100644 index 000000000..2a34f5f2b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSValue.swift @@ -0,0 +1,41 @@ +@JS func roundTripJSValue(_ value: JSValue) -> JSValue { + return value +} + +@JS func roundTripOptionalJSValue(_ value: JSValue?) -> JSValue? { + return value +} + +@JS func roundTripJSValueArray(_ values: [JSValue]) -> [JSValue] { + return values +} + +@JS func roundTripOptionalJSValueArray(_ values: [JSValue]?) -> [JSValue]? { + return values +} + +@JS class JSValueHolder { + @JS var value: JSValue + @JS var optionalValue: JSValue? + + @JS init(value: JSValue, optionalValue: JSValue?) { + self.value = value + self.optionalValue = optionalValue + } + + @JS func update(value: JSValue, optionalValue: JSValue?) { + self.value = value + self.optionalValue = optionalValue + } + + @JS func echo(value: JSValue) -> JSValue { + return value + } + + @JS func echoOptional(_ value: JSValue?) -> JSValue? { + return value + } +} + +@JSFunction func jsEchoJSValue(_ value: JSValue) throws(JSException) -> JSValue +@JSFunction func jsEchoJSValueArray(_ values: [JSValue]) throws(JSException) -> [JSValue] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MixedGlobal.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/MixedGlobal.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MixedGlobal.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/MixedGlobal.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MixedPrivate.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/MixedPrivate.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MixedPrivate.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/MixedPrivate.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileClassA.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileClassA.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileClassA.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileClassA.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileClassB.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileClassB.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileClassB.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileClassB.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileFunctionA.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileFunctionA.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileFunctionA.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileFunctionA.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileFunctionB.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileFunctionB.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/MultifileInputs/CrossFileFunctionB.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileFunctionB.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ExportedOnly.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ExportedOnly.swift new file mode 100644 index 000000000..d7887d2bd --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ExportedOnly.swift @@ -0,0 +1,3 @@ +struct ExportedOnly { + let value: Int = 0 +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ImportedFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ImportedFunctions.swift new file mode 100644 index 000000000..451424777 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/ImportedFunctions.swift @@ -0,0 +1 @@ +@JSFunction func fetchNumber() throws(JSException) -> Int diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Namespaces.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift new file mode 100644 index 000000000..57d994519 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift @@ -0,0 +1,128 @@ +@JS class Greeter { + @JS var name: String? + + @JS init(name: String?) { + self.name = name + } + + @JS func greet() -> String { + return "Hello, " + (self.name ?? "stranger") + "!" + } + + @JS func changeName(name: String?) { + self.name = name + } +} + +@JS +func roundTripOptionalClass(value: Greeter?) -> Greeter? { + return value +} + +@JS +class OptionalPropertyHolder { + @JS var optionalName: String? = nil + @JS var optionalAge: Int? = nil + @JS var optionalGreeter: Greeter? = nil + + @JS init() {} +} + +@JS func testOptionalPropertyRoundtrip(_ holder: OptionalPropertyHolder?) -> OptionalPropertyHolder? + +@JS +func roundTripString(name: String?) -> String? { + return name +} + +@JS +func roundTripInt(value: Int?) -> Int? { + return value +} + +@JS +func roundTripBool(flag: Bool?) -> Bool? { + return flag +} + +@JS +func roundTripFloat(number: Float?) -> Float? { + return number +} + +@JS +func roundTripDouble(precision: Double?) -> Double? { + return precision +} + +@JS func roundTripSyntax(name: Optional) -> Optional { + return name +} + +@JS func roundTripMixSyntax(name: String?) -> Optional { + return name +} + +@JS func roundTripSwiftSyntax(name: Swift.Optional) -> Swift.Optional { + return name +} + +@JS func roundTripMixedSwiftSyntax(name: String?) -> Swift.Optional { + return name +} + +@JS func roundTripWithSpaces(value: Optional) -> Optional { + return value +} + +typealias OptionalAge = Int? + +@JS func roundTripAlias(age: OptionalAge) -> OptionalAge { + return age +} + +typealias OptionalNameAlias = Optional +@JS func roundTripOptionalAlias(name: OptionalNameAlias) -> OptionalNameAlias { + return name +} + +@JS +func testMixedOptionals(firstName: String?, lastName: String?, age: Int?, active: Bool) -> String? { + return nil +} + +@JSClass struct WithOptionalJSClass { + @JSFunction init(valueOrNull: String?, valueOrUndefined: JSUndefinedOr) throws(JSException) + + @JSGetter var stringOrNull: String? + @JSSetter func setStringOrNull(_ value: String?) throws(JSException) + @JSGetter var stringOrUndefined: JSUndefinedOr + @JSSetter func setStringOrUndefined(_ value: JSUndefinedOr) throws(JSException) + @JSFunction func roundTripStringOrNull(value: String?) throws(JSException) -> String? + @JSFunction func roundTripStringOrUndefined( + value: JSUndefinedOr + ) throws(JSException) -> JSUndefinedOr + + @JSGetter var doubleOrNull: Double? + @JSSetter func setDoubleOrNull(_ value: Double?) throws(JSException) + @JSGetter var doubleOrUndefined: JSUndefinedOr + @JSSetter func setDoubleOrUndefined(_ value: JSUndefinedOr) throws(JSException) + @JSFunction func roundTripDoubleOrNull(value: Double?) throws(JSException) -> Double? + @JSFunction func roundTripDoubleOrUndefined( + value: JSUndefinedOr + ) throws(JSException) -> JSUndefinedOr + + @JSGetter var boolOrNull: Bool? + @JSSetter func setBoolOrNull(_ value: Bool?) throws(JSException) + @JSGetter var boolOrUndefined: JSUndefinedOr + @JSSetter func setBoolOrUndefined(_ value: JSUndefinedOr) throws(JSException) + @JSFunction func roundTripBoolOrNull(value: Bool?) throws(JSException) -> Bool? + @JSFunction func roundTripBoolOrUndefined(value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + + @JSGetter var intOrNull: Int? + @JSSetter func setIntOrNull(_ value: Int?) throws(JSException) + @JSGetter var intOrUndefined: JSUndefinedOr + @JSSetter func setIntOrUndefined(_ value: JSUndefinedOr) throws(JSException) + @JSFunction func roundTripIntOrNull(value: Int?) throws(JSException) -> Int? + @JSFunction func roundTripIntOrUndefined(value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveParameters.swift new file mode 100644 index 000000000..97495d947 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveParameters.swift @@ -0,0 +1,2 @@ +@JS func check(a: Int, b: UInt, c: Float, d: Double, e: Bool) {} +@JSFunction func check(_ a: Double, _ b: Bool) throws(JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveReturn.swift similarity index 65% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveReturn.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveReturn.swift index 144a759ec..d2a65faef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveReturn.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PrimitiveReturn.swift @@ -3,3 +3,6 @@ @JS func checkFloat() -> Float { fatalError() } @JS func checkDouble() -> Double { fatalError() } @JS func checkBool() -> Bool { fatalError() } + +@JSFunction func checkNumber() throws(JSException) -> Double +@JSFunction func checkBoolean() throws(JSException) -> Bool diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PropertyTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PropertyTypes.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PropertyTypes.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/PropertyTypes.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Protocol.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Protocol.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StaticFunctions.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticFunctions.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticProperties.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StaticProperties.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StaticProperties.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringParameter.swift new file mode 100644 index 000000000..32fc62f32 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringParameter.swift @@ -0,0 +1,5 @@ +@JS func checkString(a: String) {} +@JS func roundtripString(a: String) -> String { return a } + +@JSFunction func checkString(_ a: String) throws(JSException) -> Void +@JSFunction func checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringReturn.swift new file mode 100644 index 000000000..4b5bc088a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StringReturn.swift @@ -0,0 +1,2 @@ +@JS func checkString() -> String { fatalError() } +@JSFunction func checkString() throws(JSException) -> String diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift similarity index 69% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClass.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift index 116b00878..d7b5a5b8e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClass.swift @@ -18,3 +18,6 @@ @JS public class PublicGreeter {} @JS package class PackageGreeter {} + +@JSFunction func jsRoundTripGreeter(greeter: Greeter) throws(JSException) -> Greeter +@JSFunction func jsRoundTripOptionalGreeter(greeter: Greeter?) throws(JSException) -> Greeter? diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift new file mode 100644 index 000000000..791b1b7a9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift @@ -0,0 +1,68 @@ +import JavaScriptKit + +@JS public class Person { + public let name: String + + @JS public init(name: String) { + self.name = name + } +} + +@JS class TestProcessor { + @JS init(transform: @escaping (String) -> String) {} +} + +@JS func roundtripString(_ stringClosure: (String) -> String) -> (String) -> String +@JS func roundtripInt(_ intClosure: (Int) -> Int) -> (Int) -> Int +@JS func roundtripBool(_ boolClosure: (Bool) -> Bool) -> (Bool) -> Bool +@JS func roundtripFloat(_ floatClosure: (Float) -> Float) -> (Float) -> Float +@JS func roundtripDouble(_ doubleClosure: (Double) -> Double) -> (Double) -> Double + +@JS func roundtripOptionalString(_ stringClosure: (String?) -> String?) -> (String?) -> String? +@JS func roundtripOptionalInt(_ intClosure: (Int?) -> Int?) -> (Int?) -> Int? +@JS func roundtripOptionalBool(_ boolClosure: (Bool?) -> Bool?) -> (Bool?) -> Bool? +@JS func roundtripOptionalFloat(_ floatClosure: (Float?) -> Float?) -> (Float?) -> Float? +@JS func roundtripOptionalDouble(_ doubleClosure: (Double?) -> Double?) -> (Double?) -> Double? + +@JS func roundtripPerson(_ personClosure: (Person) -> Person) -> (Person) -> Person +@JS func roundtripOptionalPerson(_ personClosure: (Person?) -> Person?) -> (Person?) -> Person? + +@JS func roundtripDirection(_ callback: (Direction) -> Direction) -> (Direction) -> Direction +@JS func roundtripTheme(_ callback: (Theme) -> Theme) -> (Theme) -> Theme +@JS func roundtripHttpStatus(_ callback: (HttpStatus) -> HttpStatus) -> (HttpStatus) -> HttpStatus +@JS func roundtripAPIResult(_ callback: (APIResult) -> APIResult) -> (APIResult) -> APIResult + +@JS func roundtripOptionalDirection(_ callback: (Direction?) -> Direction?) -> (Direction?) -> Direction? +@JS func roundtripOptionalTheme(_ callback: (Theme?) -> Theme?) -> (Theme?) -> Theme? +@JS func roundtripOptionalHttpStatus(_ callback: (HttpStatus?) -> HttpStatus?) -> (HttpStatus?) -> HttpStatus? +@JS func roundtripOptionalAPIResult(_ callback: (APIResult?) -> APIResult?) -> (APIResult?) -> APIResult? +@JS func roundtripOptionalDirection(_ callback: (Direction?) -> Direction?) -> (Direction?) -> Direction? + +@JS enum Direction { + case north + case south + case east + case west +} + +@JS enum Theme: String { + case light = "light" + case dark = "dark" + case auto = "auto" +} + +@JS enum HttpStatus: Int { + case ok = 200 + case notFound = 404 + case serverError = 500 + case unknown = -1 +} + +@JS enum APIResult { + case success(String) + case failure(Int) + case flag(Bool) + case rate(Float) + case precise(Double) + case info +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/SwiftClosureImports.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift similarity index 88% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftStruct.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index ac316a05a..0d84f4736 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -53,3 +53,10 @@ @JS static var computedSetting: String { "Config: \(defaultConfig)" } @JS static func update(_ timeout: Double) -> Double } + +@JS struct Container { + var object: JSObject + var optionalObject: JSObject? +} + +@JS func roundtripContainer(_ container: Container) -> Container diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportMacroInputs/SwiftStructImports.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Throws.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Throws.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Throws.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Throws.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/UnsafePointer.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/UnsafePointer.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/UnsafePointer.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/VoidParameterVoidReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/VoidParameterVoidReturn.swift new file mode 100644 index 000000000..4b9cd0d02 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/VoidParameterVoidReturn.swift @@ -0,0 +1,2 @@ +@JS func check() {} +@JSFunction func check() throws(JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Optionals.swift deleted file mode 100644 index d256a8753..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/Optionals.swift +++ /dev/null @@ -1,92 +0,0 @@ -@JS class Greeter { - @JS var name: String? - - @JS init(name: String?) { - self.name = name - } - - @JS func greet() -> String { - return "Hello, " + (self.name ?? "stranger") + "!" - } - - @JS func changeName(name: String?) { - self.name = name - } -} - -@JS -func roundTripOptionalClass(value: Greeter?) -> Greeter? { - return value -} - -@JS -class OptionalPropertyHolder { - @JS var optionalName: String? = nil - @JS var optionalAge: Int? = nil - @JS var optionalGreeter: Greeter? = nil - - @JS init() {} -} - -@JS func testOptionalPropertyRoundtrip(_ holder: OptionalPropertyHolder?) -> OptionalPropertyHolder? - -@JS -func roundTripString(name: String?) -> String? { - return name -} - -@JS -func roundTripInt(value: Int?) -> Int? { - return value -} - -@JS -func roundTripBool(flag: Bool?) -> Bool? { - return flag -} - -@JS -func roundTripFloat(number: Float?) -> Float? { - return number -} - -@JS -func roundTripDouble(precision: Double?) -> Double? { - return precision -} - -@JS func roundTripSyntax(name: Optional) -> Optional { - return name -} - -@JS func roundTripMixSyntax(name: String?) -> Optional { - return name -} - -@JS func roundTripSwiftSyntax(name: Swift.Optional) -> Swift.Optional { - return name -} - -@JS func roundTripMixedSwiftSyntax(name: String?) -> Swift.Optional { - return name -} - -@JS func roundTripWithSpaces(value: Optional) -> Optional { - return value -} - -typealias OptionalAge = Int? - -@JS func roundTripAlias(age: OptionalAge) -> OptionalAge { - return age -} - -typealias OptionalNameAlias = Optional -@JS func roundTripOptionalAlias(name: OptionalNameAlias) -> OptionalNameAlias { - return name -} - -@JS -func testMixedOptionals(firstName: String?, lastName: String?, age: Int?, active: Bool) -> String? { - return nil -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveParameters.swift deleted file mode 100644 index a0d4353eb..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/PrimitiveParameters.swift +++ /dev/null @@ -1 +0,0 @@ -@JS func check(a: Int, b: UInt, c: Float, d: Double, e: Bool) {} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringParameter.swift deleted file mode 100644 index c735c56f7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringParameter.swift +++ /dev/null @@ -1,2 +0,0 @@ -@JS func checkString(a: String) {} -@JS func roundtripString(a: String) -> String { return a } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringReturn.swift deleted file mode 100644 index fe070f0db..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/StringReturn.swift +++ /dev/null @@ -1 +0,0 @@ -@JS func checkString() -> String { fatalError() } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClosure.swift deleted file mode 100644 index 129f53b50..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/SwiftClosure.swift +++ /dev/null @@ -1,75 +0,0 @@ -import JavaScriptKit - -@JS public class Person { - public let name: String - - @JS public init(name: String) { - self.name = name - } -} - -@JS class TestProcessor { - private var transform: (String) -> String - - @JS init(transform: @escaping (String) -> String) { - self.transform = transform - } - - @JS func getTransform() -> (String) -> String - - @JS func processWithCustom(_ text: String, customTransform: (String) -> String) -> String - - @JS func printTogether( - person: Person, - name: String, - ratio: Double, - customTransform: (Person?, String?, Double?) -> String - ) -> String - - @JS func roundtrip(_ personClosure: (Person) -> String) -> (Person) -> String - @JS func roundtripOptional(_ personClosure: (Person?) -> String) -> (Person?) -> String - - @JS func processDirection(_ callback: (Direction) -> String) -> String - @JS func processTheme(_ callback: (Theme) -> String) -> String - @JS func processHttpStatus(_ callback: (HttpStatus) -> Int) -> Int - @JS func processAPIResult(_ callback: (APIResult) -> String) -> String - - @JS func makeDirectionChecker() -> (Direction) -> Bool - @JS func makeThemeValidator() -> (Theme) -> Bool - @JS func makeStatusCodeExtractor() -> (HttpStatus) -> Int - @JS func makeAPIResultHandler() -> (APIResult) -> String - - @JS func processOptionalDirection(_ callback: (Direction?) -> String) -> String - @JS func processOptionalTheme(_ callback: (Theme?) -> String) -> String - @JS func processOptionalAPIResult(_ callback: (APIResult?) -> String) -> String - @JS func makeOptionalDirectionFormatter() -> (Direction?) -> String -} - -@JS enum Direction { - case north - case south - case east - case west -} - -@JS enum Theme: String { - case light = "light" - case dark = "dark" - case auto = "auto" -} - -@JS enum HttpStatus: Int { - case ok = 200 - case notFound = 404 - case serverError = 500 - case unknown = -1 -} - -@JS enum APIResult { - case success(String) - case failure(Int) - case flag(Bool) - case rate(Float) - case precise(Double) - case info -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/VoidParameterVoidReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/VoidParameterVoidReturn.swift deleted file mode 100644 index ba0cf5d23..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/VoidParameterVoidReturn.swift +++ /dev/null @@ -1 +0,0 @@ -@JS func check() {} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/SnapshotTesting.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/SnapshotTesting.swift index ce7066a6d..de7ebd0c3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/SnapshotTesting.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/SnapshotTesting.swift @@ -22,17 +22,26 @@ func assertSnapshot( if FileManager.default.fileExists(atPath: snapshotPath.path) { let existingSnapshot = try String(contentsOf: snapshotPath, encoding: .utf8) - let ok = existingSnapshot == String(data: input, encoding: .utf8)! + let actual = String(data: input, encoding: .utf8)! + let ok = existingSnapshot == actual let actualFilePath = snapshotPath.path + ".actual" let updateSnapshots = ProcessInfo.processInfo.environment["UPDATE_SNAPSHOTS"] != nil - func buildComment() -> Comment { - "Snapshot mismatch: \(actualFilePath) \(snapshotPath.path)" - } + if !updateSnapshots { - #expect(ok, buildComment(), sourceLocation: sourceLocation) if !ok { - try input.write(to: URL(fileURLWithPath: actualFilePath)) + try actual.write(toFile: actualFilePath, atomically: true, encoding: .utf8) } + + let diff = ok ? nil : unifiedDiff(expectedPath: snapshotPath.path, actualPath: actualFilePath) + func buildComment() -> Comment { + var message = "Snapshot mismatch: \(actualFilePath) \(snapshotPath.path)" + if let diff { + message.append("\n\n" + diff) + } + return Comment(rawValue: message) + } + + #expect(ok, buildComment(), sourceLocation: sourceLocation) } else { try input.write(to: snapshotPath) } @@ -41,3 +50,23 @@ func assertSnapshot( #expect(Bool(false), "Snapshot created at \(snapshotPath.path)", sourceLocation: sourceLocation) } } + +private func unifiedDiff(expectedPath: String, actualPath: String) -> String? { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = ["diff", "-u", expectedPath, actualPath] + let output = Pipe() + process.standardOutput = output + process.standardError = Pipe() + + do { + try process.run() + } catch { + return nil + } + process.waitUntilExit() + + let data = output.fileHandleForReading.readDataToEndOfFile() + guard !data.isEmpty else { return nil } + return String(data: data, encoding: .utf8) +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/TS2SwiftVitestTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/TS2SwiftVitestTests.swift new file mode 100644 index 000000000..f658b001f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/TS2SwiftVitestTests.swift @@ -0,0 +1,43 @@ +import Foundation +import Testing +@testable import TS2Swift + +/// Runs the TS2Swift JavaScript test suite (Vitest) so that `swift test --package-path ./Plugins/BridgeJS` +/// validates both the TypeScript ts2swift output and the Swift codegen. For fast iteration on ts2swift, +/// run `npm test` directly in `Sources/TS2Swift/JavaScript`. +@Suite struct TS2SwiftVitestTests { + @Test + func ts2SwiftVitestSuitePasses() throws { + let testFileURL = URL(fileURLWithPath: #filePath) + let ts2SwiftJSDir = + testFileURL + .deletingLastPathComponent() // BridgeJSToolTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // BridgeJS package root + .appendingPathComponent("Sources") + .appendingPathComponent("TS2Swift") + .appendingPathComponent("JavaScript") + let process = Process() + guard let npmExecutable = which("npm"), let nodeExecutable = which("node") else { + Issue.record("No \"npm\" command found in your system") + return + } + process.executableURL = npmExecutable + var environment = ProcessInfo.processInfo.environment + environment["PATH"] = + "\(nodeExecutable.deletingLastPathComponent().path)\(PATH_SEPARATOR) \(environment["PATH"] ?? "")" + process.environment = environment + var arguments = ["run", "test"] + if ProcessInfo.processInfo.environment["UPDATE_SNAPSHOTS"] != nil { + arguments.append(contentsOf: ["--", "--update"]) + } + process.arguments = arguments + process.currentDirectoryURL = ts2SwiftJSDir + try process.run() + process.waitUntilExit() + #expect( + process.terminationStatus == 0, + "TS2Swift Vitest suite failed (exit code \(process.terminationStatus)). Run `cd Sources/TS2Swift/JavaScript && npm test` for details." + ) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json new file mode 100644 index 000000000..8eab0c059 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -0,0 +1,1285 @@ +{ + "exported" : { + "classes" : [ + { + "methods" : [ + + ], + "name" : "Item", + "properties" : [ + + ], + "swiftCallName" : "Item" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "Direction", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "pending", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "active", + "rawValue" : "1" + }, + { + "associatedValues" : [ + + ], + "name" : "completed", + "rawValue" : "2" + } + ], + "emitStyle" : "const", + "name" : "Status", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Status", + "tsFullPath" : "Status" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_processIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processIntArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "abiName" : "bjs_processStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processStringArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "abiName" : "bjs_processDoubleArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDoubleArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "abiName" : "bjs_processBoolArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processBoolArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + }, + { + "abiName" : "bjs_processPointArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processPointArray", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + } + }, + { + "abiName" : "bjs_processDirectionArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDirectionArray", + "parameters" : [ + { + "label" : "_", + "name" : "directions", + "type" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } + }, + { + "abiName" : "bjs_processStatusArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processStatusArray", + "parameters" : [ + { + "label" : "_", + "name" : "statuses", + "type" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Status", + "_1" : "Int" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Status", + "_1" : "Int" + } + } + } + } + }, + { + "abiName" : "bjs_sumIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sumIntArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_findFirstPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "findFirstPoint", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + } + }, + { + "label" : "matching", + "name" : "matching", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Point" + } + } + }, + { + "abiName" : "bjs_processUnsafeRawPointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processUnsafeRawPointerArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + } + }, + { + "abiName" : "bjs_processUnsafeMutableRawPointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processUnsafeMutableRawPointerArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + } + } + }, + { + "abiName" : "bjs_processOpaquePointerArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOpaquePointerArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalIntArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalStringArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_processOptionalPointArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalPointArray", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalDirectionArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalDirectionArray", + "parameters" : [ + { + "label" : "_", + "name" : "directions", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalStatusArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalStatusArray", + "parameters" : [ + { + "label" : "_", + "name" : "statuses", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Status", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Status", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processNestedIntArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processNestedIntArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + } + }, + { + "abiName" : "bjs_processNestedStringArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processNestedStringArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + } + }, + { + "abiName" : "bjs_processNestedPointArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processNestedPointArray", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + } + } + } + }, + { + "abiName" : "bjs_processItemArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processItemArray", + "parameters" : [ + { + "label" : "_", + "name" : "items", + "type" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Item" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Item" + } + } + } + } + }, + { + "abiName" : "bjs_processNestedItemArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processNestedItemArray", + "parameters" : [ + { + "label" : "_", + "name" : "items", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Item" + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Item" + } + } + } + } + } + } + }, + { + "abiName" : "bjs_processJSObjectArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processJSObjectArray", + "parameters" : [ + { + "label" : "_", + "name" : "objects", + "type" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalJSObjectArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalJSObjectArray", + "parameters" : [ + { + "label" : "_", + "name" : "objects", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_processNestedJSObjectArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processNestedJSObjectArray", + "parameters" : [ + { + "label" : "_", + "name" : "objects", + "type" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "array" : { + "_0" : { + "jsObject" : { + + } + } + } + } + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Point", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Point" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "checkArray", + "parameters" : [ + { + "name" : "a", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "checkArrayWithLength", + "parameters" : [ + { + "name" : "a", + "type" : { + "jsObject" : { + + } + } + }, + { + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "importProcessNumbers", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "importGetNumbers", + "parameters" : [ + + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "name" : "importTransformNumbers", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "name" : "importProcessStrings", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "name" : "importProcessBooleans", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift new file mode 100644 index 000000000..be884310b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -0,0 +1,643 @@ +extension Direction: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { + return Direction(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + case 2: + self = .east + case 3: + self = .west + default: + return nil + } + } + + private var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + case .east: + return 2 + case .west: + return 3 + } + } +} + +extension Status: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} + +@_expose(wasm, "bjs_processIntArray") +@_cdecl("bjs_processIntArray") +public func _bjs_processIntArray() -> Void { + #if arch(wasm32) + let ret = processIntArray(_: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processStringArray") +@_cdecl("bjs_processStringArray") +public func _bjs_processStringArray() -> Void { + #if arch(wasm32) + let ret = processStringArray(_: [String].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processDoubleArray") +@_cdecl("bjs_processDoubleArray") +public func _bjs_processDoubleArray() -> Void { + #if arch(wasm32) + let ret = processDoubleArray(_: [Double].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processBoolArray") +@_cdecl("bjs_processBoolArray") +public func _bjs_processBoolArray() -> Void { + #if arch(wasm32) + let ret = processBoolArray(_: [Bool].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processPointArray") +@_cdecl("bjs_processPointArray") +public func _bjs_processPointArray() -> Void { + #if arch(wasm32) + let ret = processPointArray(_: [Point].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processDirectionArray") +@_cdecl("bjs_processDirectionArray") +public func _bjs_processDirectionArray() -> Void { + #if arch(wasm32) + let ret = processDirectionArray(_: [Direction].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processStatusArray") +@_cdecl("bjs_processStatusArray") +public func _bjs_processStatusArray() -> Void { + #if arch(wasm32) + let ret = processStatusArray(_: [Status].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_sumIntArray") +@_cdecl("bjs_sumIntArray") +public func _bjs_sumIntArray() -> Int32 { + #if arch(wasm32) + let ret = sumIntArray(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_findFirstPoint") +@_cdecl("bjs_findFirstPoint") +public func _bjs_findFirstPoint(_ matchingBytes: Int32, _ matchingLength: Int32) -> Void { + #if arch(wasm32) + let ret = findFirstPoint(_: [Point].bridgeJSStackPop(), matching: String.bridgeJSLiftParameter(matchingBytes, matchingLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processUnsafeRawPointerArray") +@_cdecl("bjs_processUnsafeRawPointerArray") +public func _bjs_processUnsafeRawPointerArray() -> Void { + #if arch(wasm32) + let ret = processUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processUnsafeMutableRawPointerArray") +@_cdecl("bjs_processUnsafeMutableRawPointerArray") +public func _bjs_processUnsafeMutableRawPointerArray() -> Void { + #if arch(wasm32) + let ret = processUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOpaquePointerArray") +@_cdecl("bjs_processOpaquePointerArray") +public func _bjs_processOpaquePointerArray() -> Void { + #if arch(wasm32) + let ret = processOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalIntArray") +@_cdecl("bjs_processOptionalIntArray") +public func _bjs_processOptionalIntArray() -> Void { + #if arch(wasm32) + let ret = processOptionalIntArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalStringArray") +@_cdecl("bjs_processOptionalStringArray") +public func _bjs_processOptionalStringArray() -> Void { + #if arch(wasm32) + let ret = processOptionalStringArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalArray") +@_cdecl("bjs_processOptionalArray") +public func _bjs_processOptionalArray() -> Void { + #if arch(wasm32) + let ret = processOptionalArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalPointArray") +@_cdecl("bjs_processOptionalPointArray") +public func _bjs_processOptionalPointArray() -> Void { + #if arch(wasm32) + let ret = processOptionalPointArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + __bjs_elem_ret.bridgeJSStackPush() + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalDirectionArray") +@_cdecl("bjs_processOptionalDirectionArray") +public func _bjs_processOptionalDirectionArray() -> Void { + #if arch(wasm32) + let ret = processOptionalDirectionArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalStatusArray") +@_cdecl("bjs_processOptionalStatusArray") +public func _bjs_processOptionalStatusArray() -> Void { + #if arch(wasm32) + let ret = processOptionalStatusArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processNestedIntArray") +@_cdecl("bjs_processNestedIntArray") +public func _bjs_processNestedIntArray() -> Void { + #if arch(wasm32) + let ret = processNestedIntArray(_: [[Int]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processNestedStringArray") +@_cdecl("bjs_processNestedStringArray") +public func _bjs_processNestedStringArray() -> Void { + #if arch(wasm32) + let ret = processNestedStringArray(_: [[String]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processNestedPointArray") +@_cdecl("bjs_processNestedPointArray") +public func _bjs_processNestedPointArray() -> Void { + #if arch(wasm32) + let ret = processNestedPointArray(_: [[Point]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processItemArray") +@_cdecl("bjs_processItemArray") +public func _bjs_processItemArray() -> Void { + #if arch(wasm32) + let ret = processItemArray(_: [Item].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processNestedItemArray") +@_cdecl("bjs_processNestedItemArray") +public func _bjs_processNestedItemArray() -> Void { + #if arch(wasm32) + let ret = processNestedItemArray(_: [[Item]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processJSObjectArray") +@_cdecl("bjs_processJSObjectArray") +public func _bjs_processJSObjectArray() -> Void { + #if arch(wasm32) + let ret = processJSObjectArray(_: [JSObject].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalJSObjectArray") +@_cdecl("bjs_processOptionalJSObjectArray") +public func _bjs_processOptionalJSObjectArray() -> Void { + #if arch(wasm32) + let ret = processOptionalJSObjectArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processNestedJSObjectArray") +@_cdecl("bjs_processNestedJSObjectArray") +public func _bjs_processNestedJSObjectArray() -> Void { + #if arch(wasm32) + let ret = processNestedJSObjectArray(_: [[JSObject]].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Item_deinit") +@_cdecl("bjs_Item_deinit") +public func _bjs_Item_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Item: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Item_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Item_wrap") +fileprivate func _bjs_Item_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Item_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Item_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Item_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkArray") +fileprivate func bjs_checkArray_extern(_ a: Int32) -> Void +#else +fileprivate func bjs_checkArray_extern(_ a: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkArray(_ a: Int32) -> Void { + return bjs_checkArray_extern(a) +} + +func _$checkArray(_ a: JSObject) throws(JSException) -> Void { + let aValue = a.bridgeJSLowerParameter() + bjs_checkArray(aValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkArrayWithLength") +fileprivate func bjs_checkArrayWithLength_extern(_ a: Int32, _ b: Float64) -> Void +#else +fileprivate func bjs_checkArrayWithLength_extern(_ a: Int32, _ b: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkArrayWithLength(_ a: Int32, _ b: Float64) -> Void { + return bjs_checkArrayWithLength_extern(a, b) +} + +func _$checkArrayWithLength(_ a: JSObject, _ b: Double) throws(JSException) -> Void { + let aValue = a.bridgeJSLowerParameter() + let bValue = b.bridgeJSLowerParameter() + bjs_checkArrayWithLength(aValue, bValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importProcessNumbers") +fileprivate func bjs_importProcessNumbers_extern() -> Void +#else +fileprivate func bjs_importProcessNumbers_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importProcessNumbers() -> Void { + return bjs_importProcessNumbers_extern() +} + +func _$importProcessNumbers(_ values: [Double]) throws(JSException) -> Void { + let _ = values.bridgeJSLowerParameter() + bjs_importProcessNumbers() + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGetNumbers") +fileprivate func bjs_importGetNumbers_extern() -> Void +#else +fileprivate func bjs_importGetNumbers_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGetNumbers() -> Void { + return bjs_importGetNumbers_extern() +} + +func _$importGetNumbers() throws(JSException) -> [Double] { + bjs_importGetNumbers() + if let error = _swift_js_take_exception() { + throw error + } + return [Double].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importTransformNumbers") +fileprivate func bjs_importTransformNumbers_extern() -> Void +#else +fileprivate func bjs_importTransformNumbers_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importTransformNumbers() -> Void { + return bjs_importTransformNumbers_extern() +} + +func _$importTransformNumbers(_ values: [Double]) throws(JSException) -> [Double] { + let _ = values.bridgeJSLowerParameter() + bjs_importTransformNumbers() + if let error = _swift_js_take_exception() { + throw error + } + return [Double].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importProcessStrings") +fileprivate func bjs_importProcessStrings_extern() -> Void +#else +fileprivate func bjs_importProcessStrings_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importProcessStrings() -> Void { + return bjs_importProcessStrings_extern() +} + +func _$importProcessStrings(_ values: [String]) throws(JSException) -> [String] { + let _ = values.bridgeJSLowerParameter() + bjs_importProcessStrings() + if let error = _swift_js_take_exception() { + throw error + } + return [String].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importProcessBooleans") +fileprivate func bjs_importProcessBooleans_extern() -> Void +#else +fileprivate func bjs_importProcessBooleans_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importProcessBooleans() -> Void { + return bjs_importProcessBooleans_extern() +} + +func _$importProcessBooleans(_ values: [Bool]) throws(JSException) -> [Bool] { + let _ = values.bridgeJSLowerParameter() + bjs_importProcessBooleans() + if let error = _swift_js_take_exception() { + throw error + } + return [Bool].bridgeJSLiftReturn() +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json new file mode 100644 index 000000000..a780871ba --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -0,0 +1,187 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_asyncReturnVoid", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncReturnVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripInt", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripInt", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripString", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripString", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripBool", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripBool", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripFloat", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripFloat", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "float" : { + + } + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripDouble", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripDouble", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_asyncRoundTripJSObject", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripJSObject", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift similarity index 95% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 4c97553de..f5230f213 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -4,7 +4,7 @@ public func _bjs_asyncReturnVoid() -> Int32 { #if arch(wasm32) let ret = JSPromise.async { await asyncReturnVoid() - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -17,7 +17,7 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripInt(_: Int.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -30,7 +30,7 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripString(_: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -43,7 +43,7 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripBool(_: Bool.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -56,7 +56,7 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripFloat(_: Float.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -69,7 +69,7 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripDouble(_: Double.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -82,7 +82,7 @@ public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripJSObject(_: JSObject.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json new file mode 100644 index 000000000..9b056b650 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json @@ -0,0 +1,152 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_FunctionA_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_FunctionA_processB", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processB", + "parameters" : [ + { + "label" : "b", + "name" : "b", + "type" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_FunctionA_createB", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createB", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "name" : "FunctionA", + "properties" : [ + + ], + "swiftCallName" : "FunctionA" + }, + { + "constructor" : { + "abiName" : "bjs_FunctionB_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "FunctionB", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "FunctionB" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_standaloneFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "standaloneFunction", + "parameters" : [ + { + "label" : "b", + "name" : "b", + "type" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift index 05437f540..4dda325bf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.swift @@ -60,12 +60,15 @@ extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_FunctionA_wrap") -fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_FunctionA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_FunctionA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_FunctionA_wrap_extern(pointer) +} @_expose(wasm, "bjs_FunctionB_init") @_cdecl("bjs_FunctionB_init") @@ -117,9 +120,12 @@ extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_FunctionB_wrap") -fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_FunctionB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_FunctionB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_FunctionB_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json new file mode 100644 index 000000000..d76a1622d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json @@ -0,0 +1,152 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_FunctionB_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "FunctionB", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "FunctionB" + }, + { + "constructor" : { + "abiName" : "bjs_FunctionA_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_FunctionA_processB", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processB", + "parameters" : [ + { + "label" : "b", + "name" : "b", + "type" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_FunctionA_createB", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createB", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "name" : "FunctionA", + "properties" : [ + + ], + "swiftCallName" : "FunctionA" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_standaloneFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "standaloneFunction", + "parameters" : [ + { + "label" : "b", + "name" : "b", + "type" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "FunctionB" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift index fa8e80cd8..fcf84a88f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.swift @@ -59,12 +59,15 @@ extension FunctionB: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_FunctionB_wrap") -fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_FunctionB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_FunctionB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_FunctionB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_FunctionB_wrap_extern(pointer) +} @_expose(wasm, "bjs_FunctionA_init") @_cdecl("bjs_FunctionA_init") @@ -117,9 +120,12 @@ extension FunctionA: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_FunctionA_wrap") -fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_FunctionA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_FunctionA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_FunctionA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_FunctionA_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json new file mode 100644 index 000000000..10c079b27 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.json @@ -0,0 +1,25 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "fetchNumber", + "parameters" : [ + + ], + "returnType" : { + "int" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.swift new file mode 100644 index 000000000..48d06ee95 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileSkipsEmptySkeletons.swift @@ -0,0 +1,19 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_fetchNumber") +fileprivate func bjs_fetchNumber_extern() -> Int32 +#else +fileprivate func bjs_fetchNumber_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_fetchNumber() -> Int32 { + return bjs_fetchNumber_extern() +} + +func _$fetchNumber() throws(JSException) -> Int { + let ret = bjs_fetchNumber() + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json new file mode 100644 index 000000000..59fb8484a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json @@ -0,0 +1,65 @@ +{ + "exported" : { + "classes" : [ + { + "methods" : [ + + ], + "name" : "ClassA", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "linkedB", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "ClassB" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ClassA" + }, + { + "constructor" : { + "abiName" : "bjs_ClassB_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "ClassB", + "properties" : [ + + ], + "swiftCallName" : "ClassB" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift similarity index 78% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift index 8d697f8ba..2868156a4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.swift @@ -37,12 +37,15 @@ extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_ClassA_wrap") -fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ClassA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClassA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassA_wrap_extern(pointer) +} @_expose(wasm, "bjs_ClassB_init") @_cdecl("bjs_ClassB_init") @@ -73,9 +76,12 @@ extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_ClassB_wrap") -fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ClassB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClassB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassB_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json new file mode 100644 index 000000000..cc10331a4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json @@ -0,0 +1,65 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_ClassB_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "ClassB", + "properties" : [ + + ], + "swiftCallName" : "ClassB" + }, + { + "methods" : [ + + ], + "name" : "ClassA", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "linkedB", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "ClassB" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ClassA" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift similarity index 78% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift index 0a0396075..09070a16f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.swift @@ -27,12 +27,15 @@ extension ClassB: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_ClassB_wrap") -fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ClassB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClassB_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ClassB_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassB_wrap_extern(pointer) +} @_expose(wasm, "bjs_ClassA_linkedB_get") @_cdecl("bjs_ClassA_linkedB_get") @@ -73,9 +76,12 @@ extension ClassA: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_ClassA_wrap") -fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ClassA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClassA_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_ClassA_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClassA_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json new file mode 100644 index 000000000..8c088a35e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json @@ -0,0 +1,1283 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_DefaultGreeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "DefaultGreeter", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "DefaultGreeter" + }, + { + "constructor" : { + "abiName" : "bjs_EmptyGreeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "EmptyGreeter", + "properties" : [ + + ], + "swiftCallName" : "EmptyGreeter" + }, + { + "constructor" : { + "abiName" : "bjs_ConstructorDefaults_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Default" + } + }, + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + + } + } + }, + { + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "active" + } + }, + "label" : "status", + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "defaultValue" : { + "null" : { + + } + }, + "label" : "tag", + "name" : "tag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "ConstructorDefaults", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "enabled", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "tag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ConstructorDefaults" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "active" + }, + { + "associatedValues" : [ + + ], + "name" : "inactive" + }, + { + "associatedValues" : [ + + ], + "name" : "pending" + } + ], + "emitStyle" : "const", + "explicitAccessControl" : "public", + "name" : "Status", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Status", + "tsFullPath" : "Status" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_testStringDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testStringDefault", + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Hello World" + } + }, + "label" : "message", + "name" : "message", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_testNegativeIntDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testNegativeIntDefault", + "parameters" : [ + { + "defaultValue" : { + "int" : { + "_0" : -42 + } + }, + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_testBoolDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testBoolDefault", + "parameters" : [ + { + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "flag", + "name" : "flag", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_testNegativeFloatDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testNegativeFloatDefault", + "parameters" : [ + { + "defaultValue" : { + "float" : { + "_0" : -273.15 + } + }, + "label" : "temp", + "name" : "temp", + "type" : { + "float" : { + + } + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + { + "abiName" : "bjs_testDoubleDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testDoubleDefault", + "parameters" : [ + { + "defaultValue" : { + "double" : { + "_0" : 2.718 + } + }, + "label" : "precision", + "name" : "precision", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_testOptionalDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testOptionalDefault", + "parameters" : [ + { + "defaultValue" : { + "null" : { + + } + }, + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testOptionalStringDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testOptionalStringDefault", + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Hi" + } + }, + "label" : "greeting", + "name" : "greeting", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testMultipleDefaults", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testMultipleDefaults", + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "Default Title" + } + }, + "label" : "title", + "name" : "title", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : 10 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : false + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_testEnumDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testEnumDefault", + "parameters" : [ + { + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "active" + } + }, + "label" : "status", + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "abiName" : "bjs_testComplexInit", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testComplexInit", + "parameters" : [ + { + "defaultValue" : { + "objectWithArguments" : { + "_0" : "DefaultGreeter", + "_1" : [ + { + "string" : { + "_0" : "DefaultUser" + } + } + ] + } + }, + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "DefaultGreeter" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "DefaultGreeter" + } + } + }, + { + "abiName" : "bjs_testEmptyInit", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testEmptyInit", + "parameters" : [ + { + "defaultValue" : { + "object" : { + "_0" : "EmptyGreeter" + } + }, + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "EmptyGreeter" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "EmptyGreeter" + } + } + }, + { + "abiName" : "bjs_testOptionalStructDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testOptionalStructDefault", + "parameters" : [ + { + "defaultValue" : { + "null" : { + + } + }, + "label" : "point", + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testOptionalStructWithValueDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testOptionalStructWithValueDefault", + "parameters" : [ + { + "defaultValue" : { + "structLiteral" : { + "_0" : "Config", + "_1" : [ + { + "name" : "name", + "value" : { + "string" : { + "_0" : "default" + } + } + }, + { + "name" : "value", + "value" : { + "int" : { + "_0" : 42 + } + } + }, + { + "name" : "enabled", + "value" : { + "bool" : { + "_0" : true + } + } + } + ] + } + }, + "label" : "point", + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testIntArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testIntArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 1 + } + }, + { + "int" : { + "_0" : 2 + } + }, + { + "int" : { + "_0" : 3 + } + } + ] + } + }, + "label" : "values", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "abiName" : "bjs_testStringArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testStringArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "string" : { + "_0" : "a" + } + }, + { + "string" : { + "_0" : "b" + } + }, + { + "string" : { + "_0" : "c" + } + } + ] + } + }, + "label" : "names", + "name" : "names", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "abiName" : "bjs_testDoubleArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testDoubleArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "double" : { + "_0" : 1.5 + } + }, + { + "double" : { + "_0" : 2.5 + } + }, + { + "double" : { + "_0" : 3.5 + } + } + ] + } + }, + "label" : "values", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "abiName" : "bjs_testBoolArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testBoolArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "bool" : { + "_0" : true + } + }, + { + "bool" : { + "_0" : false + } + }, + { + "bool" : { + "_0" : true + } + } + ] + } + }, + "label" : "flags", + "name" : "flags", + "type" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "bool" : { + + } + } + } + } + }, + { + "abiName" : "bjs_testEmptyArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testEmptyArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "array" : { + "_0" : [ + + ] + } + }, + "label" : "items", + "name" : "items", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "abiName" : "bjs_testMixedWithArrayDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testMixedWithArrayDefault", + "parameters" : [ + { + "defaultValue" : { + "string" : { + "_0" : "test" + } + }, + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 10 + } + }, + { + "int" : { + "_0" : 20 + } + }, + { + "int" : { + "_0" : 30 + } + } + ] + } + }, + "label" : "values", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Config", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "enabled", + "type" : { + "bool" : { + + } + } + } + ], + "swiftCallName" : "Config" + }, + { + "constructor" : { + "abiName" : "bjs_MathOperations_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "defaultValue" : { + "double" : { + "_0" : 0 + } + }, + "label" : "baseValue", + "name" : "baseValue", + "type" : { + "double" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_MathOperations_add", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "add", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "defaultValue" : { + "double" : { + "_0" : 10 + } + }, + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_MathOperations_multiply", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "multiply", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_MathOperations_static_subtract", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "subtract", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "defaultValue" : { + "double" : { + "_0" : 5 + } + }, + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + }, + "staticContext" : { + "structName" : { + "_0" : "MathOperations" + } + } + } + ], + "name" : "MathOperations", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "baseValue", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "MathOperations" + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift similarity index 77% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index 5232bdd53..df4969fa6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -38,97 +38,100 @@ extension Status: _BridgedSwiftCaseEnum { } extension Config: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Config { - let enabled = Bool.bridgeJSLiftParameter(_swift_js_pop_i32()) - let value = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Config { + let enabled = Bool.bridgeJSStackPop() + let value = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return Config(name: name, value: value, enabled: enabled) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.value)) - _swift_js_push_i32(self.enabled ? 1 : 0) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.value.bridgeJSStackPush() + self.enabled.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Config())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Config") -fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Config_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Config") -fileprivate func _bjs_struct_lift_Config() -> Int32 +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Config() -> Int32 { +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Config() -> Int32 { + return _bjs_struct_lift_Config_extern() +} extension MathOperations: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> MathOperations { - let baseValue = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MathOperations { + let baseValue = Double.bridgeJSStackPop() return MathOperations(baseValue: baseValue) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.baseValue) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.baseValue.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MathOperations())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MathOperations") -fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Void { + return _bjs_struct_lower_MathOperations_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MathOperations") -fileprivate func _bjs_struct_lift_MathOperations() -> Int32 +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { + return _bjs_struct_lift_MathOperations_extern() +} @_expose(wasm, "bjs_MathOperations_init") @_cdecl("bjs_MathOperations_init") @@ -297,9 +300,9 @@ public func _bjs_testEmptyInit(_ greeter: UnsafeMutableRawPointer) -> UnsafeMuta @_expose(wasm, "bjs_testOptionalStructDefault") @_cdecl("bjs_testOptionalStructDefault") -public func _bjs_testOptionalStructDefault(_ point: Int32) -> Void { +public func _bjs_testOptionalStructDefault() -> Void { #if arch(wasm32) - let ret = testOptionalStructDefault(point: Optional.bridgeJSLiftParameter(point)) + let ret = testOptionalStructDefault(point: Optional.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -308,9 +311,9 @@ public func _bjs_testOptionalStructDefault(_ point: Int32) -> Void { @_expose(wasm, "bjs_testOptionalStructWithValueDefault") @_cdecl("bjs_testOptionalStructWithValueDefault") -public func _bjs_testOptionalStructWithValueDefault(_ point: Int32) -> Void { +public func _bjs_testOptionalStructWithValueDefault() -> Void { #if arch(wasm32) - let ret = testOptionalStructWithValueDefault(point: Optional.bridgeJSLiftParameter(point)) + let ret = testOptionalStructWithValueDefault(point: Optional.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -321,19 +324,8 @@ public func _bjs_testOptionalStructWithValueDefault(_ point: Int32) -> Void { @_cdecl("bjs_testIntArrayDefault") public func _bjs_testIntArrayDefault() -> Void { #if arch(wasm32) - let ret = testIntArrayDefault(values: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + let ret = testIntArrayDefault(values: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -343,22 +335,8 @@ public func _bjs_testIntArrayDefault() -> Void { @_cdecl("bjs_testStringArrayDefault") public func _bjs_testStringArrayDefault() -> Void { #if arch(wasm32) - let ret = testStringArrayDefault(names: { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) + let ret = testStringArrayDefault(names: [String].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -368,19 +346,8 @@ public func _bjs_testStringArrayDefault() -> Void { @_cdecl("bjs_testDoubleArrayDefault") public func _bjs_testDoubleArrayDefault() -> Void { #if arch(wasm32) - let ret = testDoubleArrayDefault(values: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_f64(__bjs_elem_ret)} - _swift_js_push_i32(Int32(ret.count)) + let ret = testDoubleArrayDefault(values: [Double].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -390,19 +357,8 @@ public func _bjs_testDoubleArrayDefault() -> Void { @_cdecl("bjs_testBoolArrayDefault") public func _bjs_testBoolArrayDefault() -> Void { #if arch(wasm32) - let ret = testBoolArrayDefault(flags: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Bool] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(__bjs_elem_ret ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) + let ret = testBoolArrayDefault(flags: [Bool].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -412,19 +368,8 @@ public func _bjs_testBoolArrayDefault() -> Void { @_cdecl("bjs_testEmptyArrayDefault") public func _bjs_testEmptyArrayDefault() -> Void { #if arch(wasm32) - let ret = testEmptyArrayDefault(items: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + let ret = testEmptyArrayDefault(items: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -434,16 +379,7 @@ public func _bjs_testEmptyArrayDefault() -> Void { @_cdecl("bjs_testMixedWithArrayDefault") public func _bjs_testMixedWithArrayDefault(_ nameBytes: Int32, _ nameLength: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = testMixedWithArrayDefault(name: String.bridgeJSLiftParameter(nameBytes, nameLength), values: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }(), enabled: Bool.bridgeJSLiftParameter(enabled)) + let ret = testMixedWithArrayDefault(name: String.bridgeJSLiftParameter(nameBytes, nameLength), values: [Int].bridgeJSStackPop(), enabled: Bool.bridgeJSLiftParameter(enabled)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -500,12 +436,15 @@ extension DefaultGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_DefaultGreeter_wrap") -fileprivate func _bjs_DefaultGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_DefaultGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_DefaultGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_DefaultGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_DefaultGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_DefaultGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_EmptyGreeter_init") @_cdecl("bjs_EmptyGreeter_init") @@ -536,12 +475,15 @@ extension EmptyGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_EmptyGreeter_wrap") -fileprivate func _bjs_EmptyGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_EmptyGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_EmptyGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_EmptyGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_EmptyGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_EmptyGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_ConstructorDefaults_init") @_cdecl("bjs_ConstructorDefaults_init") @@ -677,9 +619,12 @@ extension ConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_ConstructorDefaults_wrap") -fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ConstructorDefaults_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json new file mode 100644 index 000000000..af5b83dc7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -0,0 +1,259 @@ +{ + "exported" : { + "classes" : [ + { + "methods" : [ + + ], + "name" : "Box", + "properties" : [ + + ], + "swiftCallName" : "Box" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_mirrorDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "mirrorDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "abiName" : "bjs_optionalDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "optionalDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_nestedDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "nestedDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + } + }, + { + "abiName" : "bjs_boxDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "boxDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "boxes", + "type" : { + "dictionary" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Box" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Box" + } + } + } + } + }, + { + "abiName" : "bjs_optionalBoxDictionary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "optionalBoxDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "boxes", + "type" : { + "dictionary" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Box" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Box" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "importMirrorDictionary", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift new file mode 100644 index 000000000..742619f39 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -0,0 +1,103 @@ +@_expose(wasm, "bjs_mirrorDictionary") +@_cdecl("bjs_mirrorDictionary") +public func _bjs_mirrorDictionary() -> Void { + #if arch(wasm32) + let ret = mirrorDictionary(_: [String: Int].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_optionalDictionary") +@_cdecl("bjs_optionalDictionary") +public func _bjs_optionalDictionary() -> Void { + #if arch(wasm32) + let ret = optionalDictionary(_: Optional<[String: String]>.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_nestedDictionary") +@_cdecl("bjs_nestedDictionary") +public func _bjs_nestedDictionary() -> Void { + #if arch(wasm32) + let ret = nestedDictionary(_: [String: [Int]].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_boxDictionary") +@_cdecl("bjs_boxDictionary") +public func _bjs_boxDictionary() -> Void { + #if arch(wasm32) + let ret = boxDictionary(_: [String: Box].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_optionalBoxDictionary") +@_cdecl("bjs_optionalBoxDictionary") +public func _bjs_optionalBoxDictionary() -> Void { + #if arch(wasm32) + let ret = optionalBoxDictionary(_: [String: Optional].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Box_deinit") +@_cdecl("bjs_Box_deinit") +public func _bjs_Box_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Box: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Box_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Box_wrap") +fileprivate func _bjs_Box_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Box_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Box_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Box_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importMirrorDictionary") +fileprivate func bjs_importMirrorDictionary_extern() -> Void +#else +fileprivate func bjs_importMirrorDictionary_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importMirrorDictionary() -> Void { + return bjs_importMirrorDictionary_extern() +} + +func _$importMirrorDictionary(_ values: [String: Double]) throws(JSException) -> [String: Double] { + let _ = values.bridgeJSLowerParameter() + bjs_importMirrorDictionary() + if let error = _swift_js_take_exception() { + throw error + } + return [String: Double].bridgeJSLiftReturn() +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json new file mode 100644 index 000000000..3c624fa12 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json @@ -0,0 +1,1423 @@ +{ + "exported" : { + "classes" : [ + { + "methods" : [ + + ], + "name" : "User", + "properties" : [ + + ], + "swiftCallName" : "User" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + } + ], + "name" : "flag" + }, + { + "associatedValues" : [ + { + "type" : { + "float" : { + + } + } + } + ], + "name" : "rate" + }, + { + "associatedValues" : [ + { + "type" : { + "double" : { + + } + } + } + ], + "name" : "precise" + }, + { + "associatedValues" : [ + + ], + "name" : "info" + } + ], + "emitStyle" : "const", + "name" : "APIResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "error" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "status" + }, + { + "associatedValues" : [ + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + } + ], + "name" : "coordinates" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "double" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "comprehensive" + }, + { + "associatedValues" : [ + + ], + "name" : "info" + } + ], + "emitStyle" : "const", + "name" : "ComplexResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ComplexResult", + "tsFullPath" : "ComplexResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utilities", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utilities", + "tsFullPath" : "Utilities" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + }, + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "status" + } + ], + "emitStyle" : "const", + "name" : "Result", + "namespace" : [ + "Utilities" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utilities.Result", + "tsFullPath" : "Utilities.Result" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + }, + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + } + ], + "emitStyle" : "const", + "name" : "NetworkingResult", + "namespace" : [ + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "NetworkingResult", + "tsFullPath" : "API.NetworkingResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "status" + } + ], + "emitStyle" : "const", + "name" : "APIOptionalResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIOptionalResult", + "tsFullPath" : "APIOptionalResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "rough", + "rawValue" : "0.1" + }, + { + "associatedValues" : [ + + ], + "name" : "fine", + "rawValue" : "0.001" + } + ], + "emitStyle" : "const", + "name" : "Precision", + "rawType" : "Float", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Precision", + "tsFullPath" : "Precision" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "CardinalDirection", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "CardinalDirection", + "tsFullPath" : "CardinalDirection" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + } + ], + "name" : "precision" + }, + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "CardinalDirection" + } + } + } + ], + "name" : "direction" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optPrecision" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "CardinalDirection" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optDirection" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "TypedPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TypedPayloadResult", + "tsFullPath" : "TypedPayloadResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + ], + "name" : "structPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "swiftHeapObject" : { + "_0" : "User" + } + } + } + ], + "name" : "classPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "jsObject" : { + + } + } + } + ], + "name" : "jsObjectPayload" + }, + { + "associatedValues" : [ + { + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "name" : "nestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "name" : "arrayPayload" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "AllTypesResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AllTypesResult", + "tsFullPath" : "AllTypesResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optStruct" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "User" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optClass" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optJSObject" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optNestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optArray" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "OptionalAllTypesResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "OptionalAllTypesResult", + "tsFullPath" : "OptionalAllTypesResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_handle", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "handle", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getResult", + "parameters" : [ + + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "abiName" : "bjs_roundtripAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripAPIResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalAPIResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_handleComplex", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "handleComplex", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getComplexResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getComplexResult", + "parameters" : [ + + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + } + }, + { + "abiName" : "bjs_roundtripComplexResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripComplexResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalComplexResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalComplexResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalUtilitiesResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalUtilitiesResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "Utilities.Result" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "Utilities.Result" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalNetworkingResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalNetworkingResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "NetworkingResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "NetworkingResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalAPIOptionalResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalAPIOptionalResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_compareAPIResults", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "compareAPIResults", + "parameters" : [ + { + "label" : "result1", + "name" : "result1", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + }, + { + "label" : "result2", + "name" : "result2", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripTypedPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripTypedPayloadResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalTypedPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalTypedPayloadResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripAllTypesResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripAllTypesResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalAllTypesResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalAllTypesResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalPayloadResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalPayloadResultOpt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalPayloadResultOpt", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Point", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Point" + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift new file mode 100644 index 000000000..838c55122 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -0,0 +1,675 @@ +extension APIResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .flag(Bool.bridgeJSStackPop()) + case 3: + return .rate(Float.bridgeJSStackPop()) + case 4: + return .precise(Double.bridgeJSStackPop()) + case 5: + return .info + default: + fatalError("Unknown APIResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .flag(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .rate(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .precise(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .info: + return Int32(5) + } + } +} + +extension ComplexResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ComplexResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .error(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) + case 2: + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) + case 3: + return .coordinates(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop()) + case 4: + return .comprehensive(Bool.bridgeJSStackPop(), Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), Int.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop()) + case 5: + return .info + default: + fatalError("Unknown ComplexResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .error(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + case .status(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(2) + case .coordinates(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(3) + case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + param3.bridgeJSStackPush() + param4.bridgeJSStackPush() + param5.bridgeJSStackPush() + param6.bridgeJSStackPush() + param7.bridgeJSStackPush() + param8.bridgeJSStackPush() + return Int32(4) + case .info: + return Int32(5) + } + } +} + +extension Utilities.Result: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Utilities.Result { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) + case 2: + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) + default: + fatalError("Unknown Utilities.Result case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + case .status(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(2) + } + } +} + +extension NetworkingResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> NetworkingResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) + default: + fatalError("Unknown NetworkingResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + } + } +} + +extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIOptionalResult { + switch caseId { + case 0: + return .success(Optional.bridgeJSStackPop()) + case 1: + return .failure(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + case 2: + return .status(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + default: + fatalError("Unknown APIOptionalResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(0) + case .failure(let param0, let param1): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + let __bjs_isSome_param1 = param1 != nil + if let __bjs_unwrapped_param1 = param1 { + __bjs_unwrapped_param1.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + return Int32(1) + case .status(let param0, let param1, let param2): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + let __bjs_isSome_param1 = param1 != nil + if let __bjs_unwrapped_param1 = param1 { + __bjs_unwrapped_param1.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + let __bjs_isSome_param2 = param2 != nil + if let __bjs_unwrapped_param2 = param2 { + __bjs_unwrapped_param2.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + return Int32(2) + } + } +} + +extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension CardinalDirection: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> CardinalDirection { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> CardinalDirection { + return CardinalDirection(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + case 2: + self = .east + case 3: + self = .west + default: + return nil + } + } + + private var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + case .east: + return 2 + case .west: + return 3 + } + } +} + +extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> TypedPayloadResult { + switch caseId { + case 0: + return .precision(Precision.bridgeJSStackPop()) + case 1: + return .direction(CardinalDirection.bridgeJSStackPop()) + case 2: + return .optPrecision(Optional.bridgeJSStackPop()) + case 3: + return .optDirection(Optional.bridgeJSStackPop()) + case 4: + return .empty + default: + fatalError("Unknown TypedPayloadResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .precision(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .direction(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .optPrecision(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(2) + case .optDirection(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(3) + case .empty: + return Int32(4) + } + } +} + +extension AllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AllTypesResult { + switch caseId { + case 0: + return .structPayload(Point.bridgeJSStackPop()) + case 1: + return .classPayload(User.bridgeJSStackPop()) + case 2: + return .jsObjectPayload(JSObject.bridgeJSStackPop()) + case 3: + return .nestedEnum(APIResult.bridgeJSStackPop()) + case 4: + return .arrayPayload([Int].bridgeJSStackPop()) + case 5: + return .empty + default: + fatalError("Unknown AllTypesResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .structPayload(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .classPayload(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .jsObjectPayload(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .nestedEnum(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .arrayPayload(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .empty: + return Int32(5) + } + } +} + +extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> OptionalAllTypesResult { + switch caseId { + case 0: + return .optStruct(Optional.bridgeJSStackPop()) + case 1: + return .optClass(Optional.bridgeJSStackPop()) + case 2: + return .optJSObject(Optional.bridgeJSStackPop()) + case 3: + return .optNestedEnum(Optional.bridgeJSStackPop()) + case 4: + return .optArray(Optional<[Int]>.bridgeJSStackPop()) + case 5: + return .empty + default: + fatalError("Unknown OptionalAllTypesResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .optStruct(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .optClass(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(1) + case .optJSObject(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(2) + case .optNestedEnum(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(3) + case .optArray(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .empty: + return Int32(5) + } + } +} + +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} + +@_expose(wasm, "bjs_handle") +@_cdecl("bjs_handle") +public func _bjs_handle(_ result: Int32) -> Void { + #if arch(wasm32) + handle(result: APIResult.bridgeJSLiftParameter(result)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getResult") +@_cdecl("bjs_getResult") +public func _bjs_getResult() -> Void { + #if arch(wasm32) + let ret = getResult() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripAPIResult") +@_cdecl("bjs_roundtripAPIResult") +public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAPIResult") +@_cdecl("bjs_roundTripOptionalAPIResult") +public func _bjs_roundTripOptionalAPIResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAPIResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_handleComplex") +@_cdecl("bjs_handleComplex") +public func _bjs_handleComplex(_ result: Int32) -> Void { + #if arch(wasm32) + handleComplex(result: ComplexResult.bridgeJSLiftParameter(result)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getComplexResult") +@_cdecl("bjs_getComplexResult") +public func _bjs_getComplexResult() -> Void { + #if arch(wasm32) + let ret = getComplexResult() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripComplexResult") +@_cdecl("bjs_roundtripComplexResult") +public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalComplexResult") +@_cdecl("bjs_roundTripOptionalComplexResult") +public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalComplexResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalUtilitiesResult") +@_cdecl("bjs_roundTripOptionalUtilitiesResult") +public func _bjs_roundTripOptionalUtilitiesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalUtilitiesResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalNetworkingResult") +@_cdecl("bjs_roundTripOptionalNetworkingResult") +public func _bjs_roundTripOptionalNetworkingResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalNetworkingResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAPIOptionalResult") +@_cdecl("bjs_roundTripOptionalAPIOptionalResult") +public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_compareAPIResults") +@_cdecl("bjs_compareAPIResults") +public func _bjs_compareAPIResults(_ result1IsSome: Int32, _ result1CaseId: Int32, _ result2IsSome: Int32, _ result2CaseId: Int32) -> Void { + #if arch(wasm32) + let _tmp_result2 = Optional.bridgeJSLiftParameter(result2IsSome, result2CaseId) + let _tmp_result1 = Optional.bridgeJSLiftParameter(result1IsSome, result1CaseId) + let ret = compareAPIResults(result1: _tmp_result1, result2: _tmp_result2) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripTypedPayloadResult") +@_cdecl("bjs_roundTripTypedPayloadResult") +public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalTypedPayloadResult") +@_cdecl("bjs_roundTripOptionalTypedPayloadResult") +public func _bjs_roundTripOptionalTypedPayloadResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripAllTypesResult") +@_cdecl("bjs_roundTripAllTypesResult") +public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAllTypesResult") +@_cdecl("bjs_roundTripOptionalAllTypesResult") +public func _bjs_roundTripOptionalAllTypesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalPayloadResult") +@_cdecl("bjs_roundTripOptionalPayloadResult") +public func _bjs_roundTripOptionalPayloadResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalPayloadResultOpt") +@_cdecl("bjs_roundTripOptionalPayloadResultOpt") +public func _bjs_roundTripOptionalPayloadResultOpt(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_User_deinit") +@_cdecl("bjs_User_deinit") +public func _bjs_User_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension User: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_User_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_User_wrap") +fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_User_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_User_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json new file mode 100644 index 000000000..ea32ad739 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json @@ -0,0 +1,327 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "Direction", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "loading" + }, + { + "associatedValues" : [ + + ], + "name" : "success" + }, + { + "associatedValues" : [ + + ], + "name" : "error" + } + ], + "emitStyle" : "const", + "name" : "Status", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Status", + "tsFullPath" : "Status" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "tsEnum", + "name" : "TSDirection", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TSDirection", + "tsFullPath" : "TSDirection" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "success" + } + ], + "emitStyle" : "const", + "explicitAccessControl" : "public", + "name" : "PublicStatus", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "PublicStatus", + "tsFullPath" : "PublicStatus" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_setDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setDirection", + "parameters" : [ + { + "label" : "_", + "name" : "direction", + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getDirection", + "parameters" : [ + + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "abiName" : "bjs_processDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDirection", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalDirection", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setTSDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSDirection", + "parameters" : [ + { + "label" : "_", + "name" : "direction", + "type" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getTSDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTSDirection", + "parameters" : [ + + ], + "returnType" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalTSDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalTSDirection", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "TSDirection" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "TSDirection" + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumCase.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json new file mode 100644 index 000000000..65b8ba350 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -0,0 +1,541 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Converter_toString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "toString", + "namespace" : [ + "Utils" + ], + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Utils" + ], + "properties" : [ + + ], + "swiftCallName" : "Utils.Converter" + }, + { + "constructor" : { + "abiName" : "bjs_HTTPServer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_HTTPServer_call", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "call", + "namespace" : [ + "Networking", + "API" + ], + "parameters" : [ + { + "label" : "_", + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "HTTPServer", + "namespace" : [ + "Networking", + "API" + ], + "properties" : [ + + ], + "swiftCallName" : "Networking.API.HTTPServer" + }, + { + "constructor" : { + "abiName" : "bjs_TestServer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_TestServer_call", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "call", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "parameters" : [ + { + "label" : "_", + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Internal.SupportedMethod" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "TestServer", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "properties" : [ + + ], + "swiftCallName" : "Internal.TestServer" + } + ], + "enums" : [ + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utils", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Networking", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking", + "tsFullPath" : "Networking" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "API", + "namespace" : [ + "Networking" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API", + "tsFullPath" : "Networking.API" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "get" + }, + { + "associatedValues" : [ + + ], + "name" : "post" + }, + { + "associatedValues" : [ + + ], + "name" : "put" + }, + { + "associatedValues" : [ + + ], + "name" : "delete" + } + ], + "emitStyle" : "const", + "name" : "Method", + "namespace" : [ + "Networking", + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API.Method", + "tsFullPath" : "Networking.API.Method" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Configuration", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration", + "tsFullPath" : "Configuration" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "debug", + "rawValue" : "debug" + }, + { + "associatedValues" : [ + + ], + "name" : "info", + "rawValue" : "info" + }, + { + "associatedValues" : [ + + ], + "name" : "warning", + "rawValue" : "warning" + }, + { + "associatedValues" : [ + + ], + "name" : "error", + "rawValue" : "error" + } + ], + "emitStyle" : "const", + "name" : "LogLevel", + "namespace" : [ + "Configuration" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.LogLevel", + "tsFullPath" : "Configuration.LogLevel" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "http", + "rawValue" : "80" + }, + { + "associatedValues" : [ + + ], + "name" : "https", + "rawValue" : "443" + }, + { + "associatedValues" : [ + + ], + "name" : "development", + "rawValue" : "3000" + } + ], + "emitStyle" : "const", + "name" : "Port", + "namespace" : [ + "Configuration" + ], + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.Port", + "tsFullPath" : "Configuration.Port" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Internal", + "namespace" : [ + "Networking", + "APIV2" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal", + "tsFullPath" : "Networking.APIV2.Internal" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "get" + }, + { + "associatedValues" : [ + + ], + "name" : "post" + } + ], + "emitStyle" : "const", + "name" : "SupportedMethod", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal.SupportedMethod", + "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "GraphOperations", + "namespace" : [ + "Services", + "Graph" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createGraph", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "rootId", + "name" : "rootId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "nodeCount", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_validate", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : true + }, + "name" : "validate", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GraphOperations", + "tsFullPath" : "Services.Graph.GraphOperations" + } + ], + "exposeToGlobal" : true, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift similarity index 68% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 9683b5307..47d1ff60a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -41,10 +41,10 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } -extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload { +extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Configuration.Port: _BridgedSwiftEnumNoPayload { +extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @@ -82,6 +82,53 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } } +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_createGraph") +@_cdecl("bjs_Services_Graph_GraphOperations_static_createGraph") +public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.createGraph(rootId: Int.bridgeJSLiftParameter(rootId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_nodeCount") +@_cdecl("bjs_Services_Graph_GraphOperations_static_nodeCount") +public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.nodeCount(graphId: Int.bridgeJSLiftParameter(graphId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_validate") +@_cdecl("bjs_Services_Graph_GraphOperations_static_validate") +public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + do { + let ret = try GraphOperations.validate(graphId: Int.bridgeJSLiftParameter(graphId)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Converter_init") @_cdecl("bjs_Converter_init") public func _bjs_Converter_init() -> UnsafeMutableRawPointer { @@ -122,12 +169,15 @@ extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Converter_wrap_extern(pointer) +} @_expose(wasm, "bjs_HTTPServer_init") @_cdecl("bjs_HTTPServer_init") @@ -168,12 +218,15 @@ extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObje #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_HTTPServer_wrap_extern(pointer) +} @_expose(wasm, "bjs_TestServer_init") @_cdecl("bjs_TestServer_init") @@ -214,9 +267,12 @@ extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestServer_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json new file mode 100644 index 000000000..9b800c743 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -0,0 +1,541 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Converter_toString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "toString", + "namespace" : [ + "Utils" + ], + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Utils" + ], + "properties" : [ + + ], + "swiftCallName" : "Utils.Converter" + }, + { + "constructor" : { + "abiName" : "bjs_HTTPServer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_HTTPServer_call", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "call", + "namespace" : [ + "Networking", + "API" + ], + "parameters" : [ + { + "label" : "_", + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "HTTPServer", + "namespace" : [ + "Networking", + "API" + ], + "properties" : [ + + ], + "swiftCallName" : "Networking.API.HTTPServer" + }, + { + "constructor" : { + "abiName" : "bjs_TestServer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_TestServer_call", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "call", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "parameters" : [ + { + "label" : "_", + "name" : "method", + "type" : { + "caseEnum" : { + "_0" : "Internal.SupportedMethod" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "TestServer", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "properties" : [ + + ], + "swiftCallName" : "Internal.TestServer" + } + ], + "enums" : [ + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utils", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Networking", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking", + "tsFullPath" : "Networking" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "API", + "namespace" : [ + "Networking" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API", + "tsFullPath" : "Networking.API" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "get" + }, + { + "associatedValues" : [ + + ], + "name" : "post" + }, + { + "associatedValues" : [ + + ], + "name" : "put" + }, + { + "associatedValues" : [ + + ], + "name" : "delete" + } + ], + "emitStyle" : "const", + "name" : "Method", + "namespace" : [ + "Networking", + "API" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Networking.API.Method", + "tsFullPath" : "Networking.API.Method" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Configuration", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration", + "tsFullPath" : "Configuration" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "debug", + "rawValue" : "debug" + }, + { + "associatedValues" : [ + + ], + "name" : "info", + "rawValue" : "info" + }, + { + "associatedValues" : [ + + ], + "name" : "warning", + "rawValue" : "warning" + }, + { + "associatedValues" : [ + + ], + "name" : "error", + "rawValue" : "error" + } + ], + "emitStyle" : "const", + "name" : "LogLevel", + "namespace" : [ + "Configuration" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.LogLevel", + "tsFullPath" : "Configuration.LogLevel" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "http", + "rawValue" : "80" + }, + { + "associatedValues" : [ + + ], + "name" : "https", + "rawValue" : "443" + }, + { + "associatedValues" : [ + + ], + "name" : "development", + "rawValue" : "3000" + } + ], + "emitStyle" : "const", + "name" : "Port", + "namespace" : [ + "Configuration" + ], + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Configuration.Port", + "tsFullPath" : "Configuration.Port" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Internal", + "namespace" : [ + "Networking", + "APIV2" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal", + "tsFullPath" : "Networking.APIV2.Internal" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "get" + }, + { + "associatedValues" : [ + + ], + "name" : "post" + } + ], + "emitStyle" : "const", + "name" : "SupportedMethod", + "namespace" : [ + "Networking", + "APIV2", + "Internal" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Internal.SupportedMethod", + "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "GraphOperations", + "namespace" : [ + "Services", + "Graph" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createGraph", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "rootId", + "name" : "rootId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "nodeCount", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_validate", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : true + }, + "name" : "validate", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GraphOperations", + "tsFullPath" : "Services.Graph.GraphOperations" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift similarity index 68% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 9683b5307..47d1ff60a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -41,10 +41,10 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } -extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload { +extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Configuration.Port: _BridgedSwiftEnumNoPayload { +extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @@ -82,6 +82,53 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } } +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_createGraph") +@_cdecl("bjs_Services_Graph_GraphOperations_static_createGraph") +public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.createGraph(rootId: Int.bridgeJSLiftParameter(rootId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_nodeCount") +@_cdecl("bjs_Services_Graph_GraphOperations_static_nodeCount") +public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.nodeCount(graphId: Int.bridgeJSLiftParameter(graphId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_validate") +@_cdecl("bjs_Services_Graph_GraphOperations_static_validate") +public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + do { + let ret = try GraphOperations.validate(graphId: Int.bridgeJSLiftParameter(graphId)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Converter_init") @_cdecl("bjs_Converter_init") public func _bjs_Converter_init() -> UnsafeMutableRawPointer { @@ -122,12 +169,15 @@ extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Converter_wrap_extern(pointer) +} @_expose(wasm, "bjs_HTTPServer_init") @_cdecl("bjs_HTTPServer_init") @@ -168,12 +218,15 @@ extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObje #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_HTTPServer_wrap_extern(pointer) +} @_expose(wasm, "bjs_TestServer_init") @_cdecl("bjs_TestServer_init") @@ -214,9 +267,12 @@ extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestServer_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json new file mode 100644 index 000000000..ba36405ba --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json @@ -0,0 +1,1567 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light", + "rawValue" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark", + "rawValue" : "dark" + }, + { + "associatedValues" : [ + + ], + "name" : "auto", + "rawValue" : "auto" + } + ], + "emitStyle" : "const", + "name" : "Theme", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Theme", + "tsFullPath" : "Theme" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light", + "rawValue" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark", + "rawValue" : "dark" + }, + { + "associatedValues" : [ + + ], + "name" : "auto", + "rawValue" : "auto" + } + ], + "emitStyle" : "tsEnum", + "name" : "TSTheme", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TSTheme", + "tsFullPath" : "TSTheme" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "enabled", + "rawValue" : "true" + }, + { + "associatedValues" : [ + + ], + "name" : "disabled", + "rawValue" : "false" + } + ], + "emitStyle" : "const", + "name" : "FeatureFlag", + "rawType" : "Bool", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "FeatureFlag", + "tsFullPath" : "FeatureFlag" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "ok", + "rawValue" : "200" + }, + { + "associatedValues" : [ + + ], + "name" : "notFound", + "rawValue" : "404" + }, + { + "associatedValues" : [ + + ], + "name" : "serverError", + "rawValue" : "500" + } + ], + "emitStyle" : "const", + "name" : "HttpStatus", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "HttpStatus", + "tsFullPath" : "HttpStatus" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "ok", + "rawValue" : "200" + }, + { + "associatedValues" : [ + + ], + "name" : "notFound", + "rawValue" : "404" + }, + { + "associatedValues" : [ + + ], + "name" : "serverError", + "rawValue" : "500" + } + ], + "emitStyle" : "tsEnum", + "name" : "TSHttpStatus", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TSHttpStatus", + "tsFullPath" : "TSHttpStatus" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "lowest", + "rawValue" : "-1" + }, + { + "associatedValues" : [ + + ], + "name" : "low", + "rawValue" : "2" + }, + { + "associatedValues" : [ + + ], + "name" : "medium", + "rawValue" : "3" + }, + { + "associatedValues" : [ + + ], + "name" : "high", + "rawValue" : "4" + }, + { + "associatedValues" : [ + + ], + "name" : "highest", + "rawValue" : "5" + } + ], + "emitStyle" : "const", + "name" : "Priority", + "rawType" : "Int32", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Priority", + "tsFullPath" : "Priority" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "tiny", + "rawValue" : "1024" + }, + { + "associatedValues" : [ + + ], + "name" : "small", + "rawValue" : "10240" + }, + { + "associatedValues" : [ + + ], + "name" : "medium", + "rawValue" : "102400" + }, + { + "associatedValues" : [ + + ], + "name" : "large", + "rawValue" : "1048576" + } + ], + "emitStyle" : "const", + "name" : "FileSize", + "rawType" : "Int64", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "FileSize", + "tsFullPath" : "FileSize" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "guest", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "user", + "rawValue" : "1000" + }, + { + "associatedValues" : [ + + ], + "name" : "admin", + "rawValue" : "9999" + } + ], + "emitStyle" : "const", + "name" : "UserId", + "rawType" : "UInt", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "UserId", + "tsFullPath" : "UserId" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "invalid", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "session", + "rawValue" : "12345" + }, + { + "associatedValues" : [ + + ], + "name" : "refresh", + "rawValue" : "67890" + } + ], + "emitStyle" : "const", + "name" : "TokenId", + "rawType" : "UInt32", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TokenId", + "tsFullPath" : "TokenId" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "none", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "active", + "rawValue" : "9876543210" + }, + { + "associatedValues" : [ + + ], + "name" : "expired", + "rawValue" : "1234567890" + } + ], + "emitStyle" : "const", + "name" : "SessionId", + "rawType" : "UInt64", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "SessionId", + "tsFullPath" : "SessionId" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "rough", + "rawValue" : "0.1" + }, + { + "associatedValues" : [ + + ], + "name" : "normal", + "rawValue" : "0.01" + }, + { + "associatedValues" : [ + + ], + "name" : "fine", + "rawValue" : "0.001" + } + ], + "emitStyle" : "const", + "name" : "Precision", + "rawType" : "Float", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Precision", + "tsFullPath" : "Precision" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "quarter", + "rawValue" : "0.25" + }, + { + "associatedValues" : [ + + ], + "name" : "half", + "rawValue" : "0.5" + }, + { + "associatedValues" : [ + + ], + "name" : "golden", + "rawValue" : "1.618" + }, + { + "associatedValues" : [ + + ], + "name" : "pi", + "rawValue" : "3.14159" + } + ], + "emitStyle" : "const", + "name" : "Ratio", + "rawType" : "Double", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Ratio", + "tsFullPath" : "Ratio" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_setTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTheme", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalTheme", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setTSTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getTSTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTSTheme", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalTSTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalTSTheme", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setFeatureFlag", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setFeatureFlag", + "parameters" : [ + { + "label" : "_", + "name" : "flag", + "type" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getFeatureFlag", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getFeatureFlag", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalFeatureFlag", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalFeatureFlag", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "status", + "type" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getHttpStatus", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setTSHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "status", + "type" : { + "rawValueEnum" : { + "_0" : "TSHttpStatus", + "_1" : "Int" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getTSHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTSHttpStatus", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "TSHttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSHttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSHttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setPriority", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setPriority", + "parameters" : [ + { + "label" : "_", + "name" : "priority", + "type" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int32" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getPriority", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getPriority", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int32" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalPriority", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalPriority", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int32" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int32" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setFileSize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setFileSize", + "parameters" : [ + { + "label" : "_", + "name" : "size", + "type" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getFileSize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getFileSize", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalFileSize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalFileSize", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setUserId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setUserId", + "parameters" : [ + { + "label" : "_", + "name" : "id", + "type" : { + "rawValueEnum" : { + "_0" : "UserId", + "_1" : "UInt" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getUserId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getUserId", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "UserId", + "_1" : "UInt" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalUserId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalUserId", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "UserId", + "_1" : "UInt" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "UserId", + "_1" : "UInt" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setTokenId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTokenId", + "parameters" : [ + { + "label" : "_", + "name" : "token", + "type" : { + "rawValueEnum" : { + "_0" : "TokenId", + "_1" : "UInt32" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getTokenId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTokenId", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "TokenId", + "_1" : "UInt32" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalTokenId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalTokenId", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TokenId", + "_1" : "UInt32" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TokenId", + "_1" : "UInt32" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setSessionId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setSessionId", + "parameters" : [ + { + "label" : "_", + "name" : "session", + "type" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getSessionId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getSessionId", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalSessionId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalSessionId", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setPrecision", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setPrecision", + "parameters" : [ + { + "label" : "_", + "name" : "precision", + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getPrecision", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getPrecision", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalPrecision", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalPrecision", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setRatio", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setRatio", + "parameters" : [ + { + "label" : "_", + "name" : "ratio", + "type" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_getRatio", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getRatio", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalRatio", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalRatio", + "parameters" : [ + { + "label" : "_", + "name" : "input", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_processTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_convertPriority", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "convertPriority", + "parameters" : [ + { + "label" : "_", + "name" : "status", + "type" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int32" + } + } + }, + { + "abiName" : "bjs_validateSession", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "validateSession", + "parameters" : [ + { + "label" : "_", + "name" : "session", + "type" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "takesFeatureFlag", + "parameters" : [ + { + "name" : "flag", + "type" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "returnsFeatureFlag", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift similarity index 83% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index 12fdeba04..c3c3d5e7f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -1,37 +1,37 @@ -extension Theme: _BridgedSwiftEnumNoPayload { +extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension TSTheme: _BridgedSwiftEnumNoPayload { +extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension FeatureFlag: _BridgedSwiftEnumNoPayload { +extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension HttpStatus: _BridgedSwiftEnumNoPayload { +extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension TSHttpStatus: _BridgedSwiftEnumNoPayload { +extension TSHttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Priority: _BridgedSwiftEnumNoPayload { +extension Priority: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension FileSize: _BridgedSwiftEnumNoPayload { +extension FileSize: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension UserId: _BridgedSwiftEnumNoPayload { +extension UserId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension TokenId: _BridgedSwiftEnumNoPayload { +extension TokenId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension SessionId: _BridgedSwiftEnumNoPayload { +extension SessionId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Precision: _BridgedSwiftEnumNoPayload { +extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Ratio: _BridgedSwiftEnumNoPayload { +extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } @_expose(wasm, "bjs_setTheme") @@ -100,9 +100,9 @@ public func _bjs_roundTripOptionalTSTheme(_ inputIsSome: Int32, _ inputBytes: In @_expose(wasm, "bjs_setFeatureFlag") @_cdecl("bjs_setFeatureFlag") -public func _bjs_setFeatureFlag(_ flag: Int32) -> Void { +public func _bjs_setFeatureFlag(_ flagBytes: Int32, _ flagLength: Int32) -> Void { #if arch(wasm32) - setFeatureFlag(_: FeatureFlag.bridgeJSLiftParameter(flag)) + setFeatureFlag(_: FeatureFlag.bridgeJSLiftParameter(flagBytes, flagLength)) #else fatalError("Only available on WebAssembly") #endif @@ -110,7 +110,7 @@ public func _bjs_setFeatureFlag(_ flag: Int32) -> Void { @_expose(wasm, "bjs_getFeatureFlag") @_cdecl("bjs_getFeatureFlag") -public func _bjs_getFeatureFlag() -> Int32 { +public func _bjs_getFeatureFlag() -> Void { #if arch(wasm32) let ret = getFeatureFlag() return ret.bridgeJSLowerReturn() @@ -121,9 +121,9 @@ public func _bjs_getFeatureFlag() -> Int32 { @_expose(wasm, "bjs_roundTripOptionalFeatureFlag") @_cdecl("bjs_roundTripOptionalFeatureFlag") -public func _bjs_roundTripOptionalFeatureFlag(_ inputIsSome: Int32, _ inputValue: Int32) -> Void { +public func _bjs_roundTripOptionalFeatureFlag(_ inputIsSome: Int32, _ inputBytes: Int32, _ inputLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalFeatureFlag(_: Optional.bridgeJSLiftParameter(inputIsSome, inputValue)) + let ret = roundTripOptionalFeatureFlag(_: Optional.bridgeJSLiftParameter(inputIsSome, inputBytes, inputLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -449,4 +449,44 @@ public func _bjs_validateSession(_ session: Int32) -> Void { #else fatalError("Only available on WebAssembly") #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_takesFeatureFlag") +fileprivate func bjs_takesFeatureFlag_extern(_ flag: Int32) -> Void +#else +fileprivate func bjs_takesFeatureFlag_extern(_ flag: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_takesFeatureFlag(_ flag: Int32) -> Void { + return bjs_takesFeatureFlag_extern(flag) +} + +func _$takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void { + let flagValue = flag.bridgeJSLowerParameter() + bjs_takesFeatureFlag(flagValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_returnsFeatureFlag") +fileprivate func bjs_returnsFeatureFlag_extern() -> Int32 +#else +fileprivate func bjs_returnsFeatureFlag_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_returnsFeatureFlag() -> Int32 { + return bjs_returnsFeatureFlag_extern() +} + +func _$returnsFeatureFlag() throws(JSException) -> FeatureFlag { + let ret = bjs_returnsFeatureFlag() + if let error = _swift_js_take_exception() { + throw error + } + return FeatureFlag.bridgeJSLiftReturn(ret) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json new file mode 100644 index 000000000..55ac7dd70 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.json @@ -0,0 +1,56 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "globalGetters" : [ + { + "name" : "console", + "type" : { + "jsObject" : { + "_0" : "JSConsole" + } + } + } + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + { + "name" : "log", + "parameters" : [ + { + "name" : "message", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "JSConsole", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalGetter.ImportMacros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift similarity index 51% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalGetter.ImportMacros.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift index b5442b09e..b42f71563 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalGetter.ImportMacros.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift @@ -1,11 +1,14 @@ #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_console_get") -fileprivate func bjs_console_get() -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_console_get") +fileprivate func bjs_console_get_extern() -> Int32 #else -fileprivate func bjs_console_get() -> Int32 { +fileprivate func bjs_console_get_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_console_get() -> Int32 { + return bjs_console_get_extern() +} func _$console_get() throws(JSException) -> JSConsole { let ret = bjs_console_get() @@ -16,13 +19,16 @@ func _$console_get() throws(JSException) -> JSConsole { } #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void +@_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void #else -fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { + return bjs_JSConsole_log_extern(self, message) +} func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json new file mode 100644 index 000000000..5e002e34f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.json @@ -0,0 +1,114 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "from" : "global", + "jsName" : "parseInt", + "name" : "parseInt", + "parameters" : [ + { + "name" : "string", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + } + ], + "globalGetters" : [ + { + "from" : "global", + "name" : "console", + "type" : { + "jsObject" : { + "_0" : "JSConsole" + } + } + } + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + { + "name" : "log", + "parameters" : [ + { + "name" : "message", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "JSConsole", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "constructor" : { + "parameters" : [ + { + "name" : "url", + "type" : { + "string" : { + + } + } + } + ] + }, + "from" : "global", + "getters" : [ + + ], + "methods" : [ + { + "name" : "close", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "WebSocket", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalThisImports.ImportMacros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift similarity index 51% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalThisImports.ImportMacros.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift index 503da6189..58d69eed1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/GlobalThisImports.ImportMacros.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift @@ -1,11 +1,14 @@ #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_console_get") -fileprivate func bjs_console_get() -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_console_get") +fileprivate func bjs_console_get_extern() -> Int32 #else -fileprivate func bjs_console_get() -> Int32 { +fileprivate func bjs_console_get_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_console_get() -> Int32 { + return bjs_console_get_extern() +} func _$console_get() throws(JSException) -> JSConsole { let ret = bjs_console_get() @@ -16,13 +19,16 @@ func _$console_get() throws(JSException) -> JSConsole { } #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_parseInt") -fileprivate func bjs_parseInt(_ string: Int32) -> Float64 +@_extern(wasm, module: "TestModule", name: "bjs_parseInt") +fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 #else -fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { +fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { + return bjs_parseInt_extern(string) +} func _$parseInt(_ string: String) throws(JSException) -> Double { let stringValue = string.bridgeJSLowerParameter() @@ -34,13 +40,16 @@ func _$parseInt(_ string: String) throws(JSException) -> Double { } #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_JSConsole_log") -fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void +@_extern(wasm, module: "TestModule", name: "bjs_JSConsole_log") +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void #else -fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { +fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ message: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_JSConsole_log(_ self: Int32, _ message: Int32) -> Void { + return bjs_JSConsole_log_extern(self, message) +} func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() @@ -52,22 +61,28 @@ func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> } #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WebSocket_init") -fileprivate func bjs_WebSocket_init(_ url: Int32) -> Int32 +@_extern(wasm, module: "TestModule", name: "bjs_WebSocket_init") +fileprivate func bjs_WebSocket_init_extern(_ url: Int32) -> Int32 #else -fileprivate func bjs_WebSocket_init(_ url: Int32) -> Int32 { +fileprivate func bjs_WebSocket_init_extern(_ url: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_WebSocket_init(_ url: Int32) -> Int32 { + return bjs_WebSocket_init_extern(url) +} #if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WebSocket_close") -fileprivate func bjs_WebSocket_close(_ self: Int32) -> Void +@_extern(wasm, module: "TestModule", name: "bjs_WebSocket_close") +fileprivate func bjs_WebSocket_close_extern(_ self: Int32) -> Void #else -fileprivate func bjs_WebSocket_close(_ self: Int32) -> Void { +fileprivate func bjs_WebSocket_close_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_WebSocket_close(_ self: Int32) -> Void { + return bjs_WebSocket_close_extern(self) +} func _$WebSocket_init(_ url: String) throws(JSException) -> JSObject { let urlValue = url.bridgeJSLowerParameter() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json new file mode 100644 index 000000000..b884e0cb9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -0,0 +1,62 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "roundtrip", + "parameters" : [ + { + "name" : "items", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "name" : "logStrings", + "parameters" : [ + { + "name" : "items", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift new file mode 100644 index 000000000..db1f136e7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift @@ -0,0 +1,40 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundtrip") +fileprivate func bjs_roundtrip_extern() -> Void +#else +fileprivate func bjs_roundtrip_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundtrip() -> Void { + return bjs_roundtrip_extern() +} + +func _$roundtrip(_ items: [Int]) throws(JSException) -> [Int] { + let _ = items.bridgeJSLowerParameter() + bjs_roundtrip() + if let error = _swift_js_take_exception() { + throw error + } + return [Int].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_logStrings") +fileprivate func bjs_logStrings_extern() -> Void +#else +fileprivate func bjs_logStrings_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_logStrings() -> Void { + return bjs_logStrings_extern() +} + +func _$logStrings(_ items: [String]) throws(JSException) -> Void { + let _ = items.bridgeJSLowerParameter() + bjs_logStrings() + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json new file mode 100644 index 000000000..f57e77d21 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json @@ -0,0 +1,202 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_makeFoo", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "makeFoo", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "Foo" + } + } + }, + { + "abiName" : "bjs_processFooArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processFooArray", + "parameters" : [ + { + "label" : "_", + "name" : "foos", + "type" : { + "array" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + } + } + } + }, + { + "abiName" : "bjs_processOptionalFooArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processOptionalFooArray", + "parameters" : [ + { + "label" : "_", + "name" : "foos", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_roundtripFooContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripFooContainer", + "parameters" : [ + { + "label" : "_", + "name" : "container", + "type" : { + "swiftStruct" : { + "_0" : "FooContainer" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "FooContainer" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "FooContainer", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "foo", + "type" : { + "jsObject" : { + "_0" : "Foo" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalFoo", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "FooContainer" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "constructor" : { + "parameters" : [ + + ] + }, + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "Foo", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift new file mode 100644 index 000000000..c72cda7ed --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -0,0 +1,145 @@ +extension FooContainer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> FooContainer { + let optionalFoo = Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) } + let foo = Foo(unsafelyWrapping: JSObject.bridgeJSStackPop()) + return FooContainer(foo: foo, optionalFoo: optionalFoo) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.foo.jsObject.bridgeJSStackPush() + let __bjs_isSome_optionalFoo = self.optionalFoo != nil + if let __bjs_unwrapped_optionalFoo = self.optionalFoo { + __bjs_unwrapped_optionalFoo.jsObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_optionalFoo ? 1 : 0) + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_FooContainer(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_FooContainer())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_FooContainer") +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_FooContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_FooContainer_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_FooContainer") +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_FooContainer() -> Int32 { + return _bjs_struct_lift_FooContainer_extern() +} + +@_expose(wasm, "bjs_makeFoo") +@_cdecl("bjs_makeFoo") +public func _bjs_makeFoo() -> Int32 { + #if arch(wasm32) + do { + let ret = try makeFoo() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processFooArray") +@_cdecl("bjs_processFooArray") +public func _bjs_processFooArray() -> Void { + #if arch(wasm32) + let ret = processFooArray(_: [JSObject].bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) + ret.map { $0.jsObject }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_processOptionalFooArray") +@_cdecl("bjs_processOptionalFooArray") +public func _bjs_processOptionalFooArray() -> Void { + #if arch(wasm32) + let ret = processOptionalFooArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.jsObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripFooContainer") +@_cdecl("bjs_roundtripFooContainer") +public func _bjs_roundtripFooContainer() -> Void { + #if arch(wasm32) + let ret = roundtripFooContainer(_: FooContainer.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Foo_init") +fileprivate func bjs_Foo_init_extern() -> Int32 +#else +fileprivate func bjs_Foo_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Foo_init() -> Int32 { + return bjs_Foo_init_extern() +} + +func _$Foo_init() throws(JSException) -> JSObject { + let ret = bjs_Foo_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json new file mode 100644 index 000000000..935f7a7f2 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.json @@ -0,0 +1,246 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "createWeirdObject", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "WeirdNaming" + } + } + }, + { + "name" : "createWeirdClass", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "_Weird" + } + } + } + ], + "types" : [ + { + "getters" : [ + { + "name" : "normalProperty", + "type" : { + "string" : { + + } + } + }, + { + "jsName" : "property-with-dashes", + "name" : "property_with_dashes", + "type" : { + "double" : { + + } + } + }, + { + "jsName" : "123invalidStart", + "name" : "_123invalidStart", + "type" : { + "bool" : { + + } + } + }, + { + "jsName" : "property with spaces", + "name" : "property_with_spaces", + "type" : { + "string" : { + + } + } + }, + { + "jsName" : "@specialChar", + "name" : "_specialChar", + "type" : { + "double" : { + + } + } + }, + { + "name" : "constructor", + "type" : { + "string" : { + + } + } + }, + { + "name" : "for", + "type" : { + "string" : { + + } + } + }, + { + "name" : "Any", + "type" : { + "string" : { + + } + } + } + ], + "methods" : [ + { + "name" : "as", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "try", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "WeirdNaming", + "setters" : [ + { + "functionName" : "normalProperty_set", + "name" : "normalProperty", + "type" : { + "string" : { + + } + } + }, + { + "functionName" : "property_with_dashes_set", + "jsName" : "property-with-dashes", + "name" : "property_with_dashes", + "type" : { + "double" : { + + } + } + }, + { + "functionName" : "_123invalidStart_set", + "jsName" : "123invalidStart", + "name" : "_123invalidStart", + "type" : { + "bool" : { + + } + } + }, + { + "functionName" : "property_with_spaces_set", + "jsName" : "property with spaces", + "name" : "property_with_spaces", + "type" : { + "string" : { + + } + } + }, + { + "functionName" : "_specialChar_set", + "jsName" : "@specialChar", + "name" : "_specialChar", + "type" : { + "double" : { + + } + } + }, + { + "functionName" : "constructor_set", + "name" : "constructor", + "type" : { + "string" : { + + } + } + }, + { + "functionName" : "for_set", + "name" : "for", + "type" : { + "string" : { + + } + } + }, + { + "functionName" : "any_set", + "jsName" : "Any", + "name" : "any", + "type" : { + "string" : { + + } + } + } + ], + "staticMethods" : [ + + ] + }, + { + "constructor" : { + "parameters" : [ + + ] + }, + "getters" : [ + + ], + "jsName" : "$Weird", + "methods" : [ + { + "jsName" : "method-with-dashes", + "name" : "method_with_dashes", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "_Weird", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift new file mode 100644 index 000000000..2ff17ea24 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift @@ -0,0 +1,455 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_createWeirdObject") +fileprivate func bjs_createWeirdObject_extern() -> Int32 +#else +fileprivate func bjs_createWeirdObject_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_createWeirdObject() -> Int32 { + return bjs_createWeirdObject_extern() +} + +func _$createWeirdObject() throws(JSException) -> WeirdNaming { + let ret = bjs_createWeirdObject() + if let error = _swift_js_take_exception() { + throw error + } + return WeirdNaming.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_createWeirdClass") +fileprivate func bjs_createWeirdClass_extern() -> Int32 +#else +fileprivate func bjs_createWeirdClass_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_createWeirdClass() -> Int32 { + return bjs_createWeirdClass_extern() +} + +func _$createWeirdClass() throws(JSException) -> _Weird { + let ret = bjs_createWeirdClass() + if let error = _swift_js_take_exception() { + throw error + } + return _Weird.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_normalProperty_get") +fileprivate func bjs_WeirdNaming_normalProperty_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming_normalProperty_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming_normalProperty_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_dashes_get") +fileprivate func bjs_WeirdNaming_property_with_dashes_get_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_WeirdNaming_property_with_dashes_get_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_property_with_dashes_get(_ self: Int32) -> Float64 { + return bjs_WeirdNaming_property_with_dashes_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming__123invalidStart_get") +fileprivate func bjs_WeirdNaming__123invalidStart_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming__123invalidStart_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming__123invalidStart_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming__123invalidStart_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_spaces_get") +fileprivate func bjs_WeirdNaming_property_with_spaces_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming_property_with_spaces_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming_property_with_spaces_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming__specialChar_get") +fileprivate func bjs_WeirdNaming__specialChar_get_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_WeirdNaming__specialChar_get_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming__specialChar_get(_ self: Int32) -> Float64 { + return bjs_WeirdNaming__specialChar_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_constructor_get") +fileprivate func bjs_WeirdNaming_constructor_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming_constructor_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_constructor_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming_constructor_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_for_get") +fileprivate func bjs_WeirdNaming_for_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming_for_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_for_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming_for_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_Any_get") +fileprivate func bjs_WeirdNaming_Any_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WeirdNaming_Any_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_Any_get(_ self: Int32) -> Int32 { + return bjs_WeirdNaming_Any_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_normalProperty_set") +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_normalProperty_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming_normalProperty_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_dashes_set") +fileprivate func bjs_WeirdNaming_property_with_dashes_set_extern(_ self: Int32, _ newValue: Float64) -> Void +#else +fileprivate func bjs_WeirdNaming_property_with_dashes_set_extern(_ self: Int32, _ newValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_property_with_dashes_set(_ self: Int32, _ newValue: Float64) -> Void { + return bjs_WeirdNaming_property_with_dashes_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming__123invalidStart_set") +fileprivate func bjs_WeirdNaming__123invalidStart_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming__123invalidStart_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming__123invalidStart_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming__123invalidStart_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_property_with_spaces_set") +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_property_with_spaces_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming_property_with_spaces_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming__specialChar_set") +fileprivate func bjs_WeirdNaming__specialChar_set_extern(_ self: Int32, _ newValue: Float64) -> Void +#else +fileprivate func bjs_WeirdNaming__specialChar_set_extern(_ self: Int32, _ newValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming__specialChar_set(_ self: Int32, _ newValue: Float64) -> Void { + return bjs_WeirdNaming__specialChar_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_constructor_set") +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_constructor_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming_constructor_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_for_set") +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_for_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming_for_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_any_set") +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_any_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_WeirdNaming_any_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_as") +fileprivate func bjs_WeirdNaming_as_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_as_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_as(_ self: Int32) -> Void { + return bjs_WeirdNaming_as_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WeirdNaming_try") +fileprivate func bjs_WeirdNaming_try_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WeirdNaming_try_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WeirdNaming_try(_ self: Int32) -> Void { + return bjs_WeirdNaming_try_extern(self) +} + +func _$WeirdNaming_normalProperty_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_normalProperty_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_property_with_dashes_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_property_with_dashes_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming__123invalidStart_get(_ self: JSObject) throws(JSException) -> Bool { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming__123invalidStart_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_property_with_spaces_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_property_with_spaces_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming__specialChar_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming__specialChar_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_constructor_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_constructor_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_for_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_for_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_Any_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WeirdNaming_Any_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_normalProperty_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_property_with_dashes_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_property_with_dashes_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming__123invalidStart_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming__123invalidStart_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_property_with_spaces_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming__specialChar_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_constructor_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_for_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_any_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_WeirdNaming_any_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_as(_ self: JSObject) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + bjs_WeirdNaming_as(selfValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WeirdNaming_try(_ self: JSObject) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + bjs_WeirdNaming_try(selfValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs__Weird_init") +fileprivate func bjs__Weird_init_extern() -> Int32 +#else +fileprivate func bjs__Weird_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs__Weird_init() -> Int32 { + return bjs__Weird_init_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs__Weird_method_with_dashes") +fileprivate func bjs__Weird_method_with_dashes_extern(_ self: Int32) -> Void +#else +fileprivate func bjs__Weird_method_with_dashes_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs__Weird_method_with_dashes(_ self: Int32) -> Void { + return bjs__Weird_method_with_dashes_extern(self) +} + +func _$_Weird_init() throws(JSException) -> JSObject { + let ret = bjs__Weird_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$_Weird_method_with_dashes(_ self: JSObject) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + bjs__Weird_method_with_dashes(selfValue) + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json new file mode 100644 index 000000000..689e86150 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.json @@ -0,0 +1,160 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "returnAnimatable", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "Animatable" + } + } + } + ], + "types" : [ + { + "constructor" : { + "parameters" : [ + { + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "getters" : [ + { + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "name" : "age", + "type" : { + "double" : { + + } + } + } + ], + "methods" : [ + { + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "name" : "changeName", + "parameters" : [ + { + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "Greeter", + "setters" : [ + { + "functionName" : "name_set", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "staticMethods" : [ + + ] + }, + { + "getters" : [ + + ], + "methods" : [ + { + "name" : "animate", + "parameters" : [ + { + "name" : "keyframes", + "type" : { + "jsObject" : { + + } + } + }, + { + "name" : "options", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "name" : "getAnimations", + "parameters" : [ + { + "name" : "options", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + } + ], + "name" : "Animatable", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift new file mode 100644 index 000000000..11a644759 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift @@ -0,0 +1,190 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_returnAnimatable") +fileprivate func bjs_returnAnimatable_extern() -> Int32 +#else +fileprivate func bjs_returnAnimatable_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_returnAnimatable() -> Int32 { + return bjs_returnAnimatable_extern() +} + +func _$returnAnimatable() throws(JSException) -> Animatable { + let ret = bjs_returnAnimatable() + if let error = _swift_js_take_exception() { + throw error + } + return Animatable.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_init") +fileprivate func bjs_Greeter_init_extern(_ name: Int32) -> Int32 +#else +fileprivate func bjs_Greeter_init_extern(_ name: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_init(_ name: Int32) -> Int32 { + return bjs_Greeter_init_extern(name) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_name_get") +fileprivate func bjs_Greeter_name_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Greeter_name_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_name_get(_ self: Int32) -> Int32 { + return bjs_Greeter_name_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_age_get") +fileprivate func bjs_Greeter_age_get_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_Greeter_age_get_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_age_get(_ self: Int32) -> Float64 { + return bjs_Greeter_age_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_name_set") +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_Greeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_Greeter_name_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_greet") +fileprivate func bjs_Greeter_greet_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Greeter_greet_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_greet(_ self: Int32) -> Int32 { + return bjs_Greeter_greet_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_changeName") +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void +#else +fileprivate func bjs_Greeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Greeter_changeName(_ self: Int32, _ name: Int32) -> Void { + return bjs_Greeter_changeName_extern(self, name) +} + +func _$Greeter_init(_ name: String) throws(JSException) -> JSObject { + let nameValue = name.bridgeJSLowerParameter() + let ret = bjs_Greeter_init(nameValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$Greeter_name_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Greeter_name_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$Greeter_age_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Greeter_age_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$Greeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_Greeter_name_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$Greeter_greet(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Greeter_greet(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$Greeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let nameValue = name.bridgeJSLowerParameter() + bjs_Greeter_changeName(selfValue, nameValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Animatable_animate") +fileprivate func bjs_Animatable_animate_extern(_ self: Int32, _ keyframes: Int32, _ options: Int32) -> Int32 +#else +fileprivate func bjs_Animatable_animate_extern(_ self: Int32, _ keyframes: Int32, _ options: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animatable_animate(_ self: Int32, _ keyframes: Int32, _ options: Int32) -> Int32 { + return bjs_Animatable_animate_extern(self, keyframes, options) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Animatable_getAnimations") +fileprivate func bjs_Animatable_getAnimations_extern(_ self: Int32, _ options: Int32) -> Int32 +#else +fileprivate func bjs_Animatable_getAnimations_extern(_ self: Int32, _ options: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animatable_getAnimations(_ self: Int32, _ options: Int32) -> Int32 { + return bjs_Animatable_getAnimations_extern(self, options) +} + +func _$Animatable_animate(_ self: JSObject, _ keyframes: JSObject, _ options: JSObject) throws(JSException) -> JSObject { + let selfValue = self.bridgeJSLowerParameter() + let keyframesValue = keyframes.bridgeJSLowerParameter() + let optionsValue = options.bridgeJSLowerParameter() + let ret = bjs_Animatable_animate(selfValue, keyframesValue, optionsValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$Animatable_getAnimations(_ self: JSObject, _ options: JSObject) throws(JSException) -> JSObject { + let selfValue = self.bridgeJSLowerParameter() + let optionsValue = options.bridgeJSLowerParameter() + let ret = bjs_Animatable_getAnimations(selfValue, optionsValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json new file mode 100644 index 000000000..a8b64558f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.json @@ -0,0 +1,134 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + { + "name" : "value", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + } + ], + "name" : "StaticBox", + "setters" : [ + + ], + "staticMethods" : [ + { + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } + }, + { + "name" : "value", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "name" : "makeDefault", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } + }, + { + "jsName" : "with-dashes", + "name" : "dashed", + "parameters" : [ + + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } + } + ] + }, + { + "constructor" : { + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + } + ] + }, + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "WithCtor", + "setters" : [ + + ], + "staticMethods" : [ + { + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "WithCtor" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.swift new file mode 100644 index 000000000..94dfd002b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClassStaticFunctions.swift @@ -0,0 +1,143 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_StaticBox_create_static") +fileprivate func bjs_StaticBox_create_static_extern(_ value: Float64) -> Int32 +#else +fileprivate func bjs_StaticBox_create_static_extern(_ value: Float64) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StaticBox_create_static(_ value: Float64) -> Int32 { + return bjs_StaticBox_create_static_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_StaticBox_value_static") +fileprivate func bjs_StaticBox_value_static_extern() -> Float64 +#else +fileprivate func bjs_StaticBox_value_static_extern() -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StaticBox_value_static() -> Float64 { + return bjs_StaticBox_value_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_StaticBox_makeDefault_static") +fileprivate func bjs_StaticBox_makeDefault_static_extern() -> Int32 +#else +fileprivate func bjs_StaticBox_makeDefault_static_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StaticBox_makeDefault_static() -> Int32 { + return bjs_StaticBox_makeDefault_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_StaticBox_dashed_static") +fileprivate func bjs_StaticBox_dashed_static_extern() -> Int32 +#else +fileprivate func bjs_StaticBox_dashed_static_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StaticBox_dashed_static() -> Int32 { + return bjs_StaticBox_dashed_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_StaticBox_value") +fileprivate func bjs_StaticBox_value_extern(_ self: Int32) -> Float64 +#else +fileprivate func bjs_StaticBox_value_extern(_ self: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_StaticBox_value(_ self: Int32) -> Float64 { + return bjs_StaticBox_value_extern(self) +} + +func _$StaticBox_create(_ value: Double) throws(JSException) -> StaticBox { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_StaticBox_create_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return StaticBox.bridgeJSLiftReturn(ret) +} + +func _$StaticBox_value() throws(JSException) -> Double { + let ret = bjs_StaticBox_value_static() + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$StaticBox_makeDefault() throws(JSException) -> StaticBox { + let ret = bjs_StaticBox_makeDefault_static() + if let error = _swift_js_take_exception() { + throw error + } + return StaticBox.bridgeJSLiftReturn(ret) +} + +func _$StaticBox_dashed() throws(JSException) -> StaticBox { + let ret = bjs_StaticBox_dashed_static() + if let error = _swift_js_take_exception() { + throw error + } + return StaticBox.bridgeJSLiftReturn(ret) +} + +func _$StaticBox_value(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_StaticBox_value(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithCtor_init") +fileprivate func bjs_WithCtor_init_extern(_ value: Float64) -> Int32 +#else +fileprivate func bjs_WithCtor_init_extern(_ value: Float64) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithCtor_init(_ value: Float64) -> Int32 { + return bjs_WithCtor_init_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithCtor_create_static") +fileprivate func bjs_WithCtor_create_static_extern(_ value: Float64) -> Int32 +#else +fileprivate func bjs_WithCtor_create_static_extern(_ value: Float64) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithCtor_create_static(_ value: Float64) -> Int32 { + return bjs_WithCtor_create_static_extern(value) +} + +func _$WithCtor_init(_ value: Double) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_WithCtor_init(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$WithCtor_create(_ value: Double) throws(JSException) -> WithCtor { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_WithCtor_create_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return WithCtor.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json new file mode 100644 index 000000000..5bd83be27 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json @@ -0,0 +1,375 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_JSValueHolder_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "jsValue" : { + + } + } + }, + { + "label" : "optionalValue", + "name" : "optionalValue", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_JSValueHolder_update", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "update", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "jsValue" : { + + } + } + }, + { + "label" : "optionalValue", + "name" : "optionalValue", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_JSValueHolder_echo", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "echo", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "jsValue" : { + + } + } + } + ], + "returnType" : { + "jsValue" : { + + } + } + }, + { + "abiName" : "bjs_JSValueHolder_echoOptional", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "echoOptional", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "JSValueHolder", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "jsValue" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalValue", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "JSValueHolder" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundTripJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "jsValue" : { + + } + } + } + ], + "returnType" : { + "jsValue" : { + + } + } + }, + { + "abiName" : "bjs_roundTripOptionalJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalJSValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripJSValueArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSValueArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + }, + { + "abiName" : "bjs_roundTripOptionalJSValueArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalJSValueArray", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "jsEchoJSValue", + "parameters" : [ + { + "name" : "value", + "type" : { + "jsValue" : { + + } + } + } + ], + "returnType" : { + "jsValue" : { + + } + } + }, + { + "name" : "jsEchoJSValueArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift new file mode 100644 index 000000000..ba7fee7af --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.swift @@ -0,0 +1,198 @@ +@_expose(wasm, "bjs_roundTripJSValue") +@_cdecl("bjs_roundTripJSValue") +public func _bjs_roundTripJSValue(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripJSValue(_: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalJSValue") +@_cdecl("bjs_roundTripOptionalJSValue") +public func _bjs_roundTripOptionalJSValue(_ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalJSValue(_: Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripJSValueArray") +@_cdecl("bjs_roundTripJSValueArray") +public func _bjs_roundTripJSValueArray() -> Void { + #if arch(wasm32) + let ret = roundTripJSValueArray(_: [JSValue].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalJSValueArray") +@_cdecl("bjs_roundTripOptionalJSValueArray") +public func _bjs_roundTripOptionalJSValueArray() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalJSValueArray(_: Optional<[JSValue]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_init") +@_cdecl("bjs_JSValueHolder_init") +public func _bjs_JSValueHolder_init(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ optionalValueIsSome: Int32, _ optionalValueKind: Int32, _ optionalValuePayload1: Int32, _ optionalValuePayload2: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = JSValueHolder(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2), optionalValue: Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_update") +@_cdecl("bjs_JSValueHolder_update") +public func _bjs_JSValueHolder_update(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64, _ optionalValueIsSome: Int32, _ optionalValueKind: Int32, _ optionalValuePayload1: Int32, _ optionalValuePayload2: Float64) -> Void { + #if arch(wasm32) + JSValueHolder.bridgeJSLiftParameter(_self).update(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2), optionalValue: Optional.bridgeJSLiftParameter(optionalValueIsSome, optionalValueKind, optionalValuePayload1, optionalValuePayload2)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_echo") +@_cdecl("bjs_JSValueHolder_echo") +public func _bjs_JSValueHolder_echo(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + let ret = JSValueHolder.bridgeJSLiftParameter(_self).echo(value: JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_echoOptional") +@_cdecl("bjs_JSValueHolder_echoOptional") +public func _bjs_JSValueHolder_echoOptional(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + let ret = JSValueHolder.bridgeJSLiftParameter(_self).echoOptional(_: Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_value_get") +@_cdecl("bjs_JSValueHolder_value_get") +public func _bjs_JSValueHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = JSValueHolder.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_value_set") +@_cdecl("bjs_JSValueHolder_value_set") +public func _bjs_JSValueHolder_value_set(_ _self: UnsafeMutableRawPointer, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + JSValueHolder.bridgeJSLiftParameter(_self).value = JSValue.bridgeJSLiftParameter(valueKind, valuePayload1, valuePayload2) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_optionalValue_get") +@_cdecl("bjs_JSValueHolder_optionalValue_get") +public func _bjs_JSValueHolder_optionalValue_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = JSValueHolder.bridgeJSLiftParameter(_self).optionalValue + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_optionalValue_set") +@_cdecl("bjs_JSValueHolder_optionalValue_set") +public func _bjs_JSValueHolder_optionalValue_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + #if arch(wasm32) + JSValueHolder.bridgeJSLiftParameter(_self).optionalValue = Optional.bridgeJSLiftParameter(valueIsSome, valueKind, valuePayload1, valuePayload2) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSValueHolder_deinit") +@_cdecl("bjs_JSValueHolder_deinit") +public func _bjs_JSValueHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension JSValueHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_JSValueHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_JSValueHolder_wrap") +fileprivate func _bjs_JSValueHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_JSValueHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_JSValueHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_JSValueHolder_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_jsEchoJSValue") +fileprivate func bjs_jsEchoJSValue_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func bjs_jsEchoJSValue_extern(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsEchoJSValue(_ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return bjs_jsEchoJSValue_extern(valueKind, valuePayload1, valuePayload2) +} + +func _$jsEchoJSValue(_ value: JSValue) throws(JSException) -> JSValue { + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + bjs_jsEchoJSValue(valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { + throw error + } + return JSValue.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_jsEchoJSValueArray") +fileprivate func bjs_jsEchoJSValueArray_extern() -> Void +#else +fileprivate func bjs_jsEchoJSValueArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsEchoJSValueArray() -> Void { + return bjs_jsEchoJSValueArray_extern() +} + +func _$jsEchoJSValueArray(_ values: [JSValue]) throws(JSException) -> [JSValue] { + let _ = values.bridgeJSLowerParameter() + bjs_jsEchoJSValueArray() + if let error = _swift_js_take_exception() { + throw error + } + return [JSValue].bridgeJSLiftReturn() +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json new file mode 100644 index 000000000..1241c232d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json @@ -0,0 +1,79 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_GlobalClass_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_GlobalClass_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "GlobalClass", + "namespace" : [ + "GlobalAPI" + ], + "properties" : [ + + ], + "swiftCallName" : "GlobalClass" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_GlobalAPI_globalFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "globalFunction", + "namespace" : [ + "GlobalAPI" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift similarity index 82% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift index 981e01be4..195a00fa1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.swift @@ -49,9 +49,12 @@ extension GlobalClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_GlobalClass_wrap") -fileprivate func _bjs_GlobalClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_GlobalClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_GlobalClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_GlobalClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GlobalClass_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json new file mode 100644 index 000000000..96e188fd2 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json @@ -0,0 +1,79 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PrivateClass_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_PrivateClass_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "PrivateClass", + "namespace" : [ + "PrivateAPI" + ], + "properties" : [ + + ], + "swiftCallName" : "PrivateClass" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_PrivateAPI_privateFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "privateFunction", + "namespace" : [ + "PrivateAPI" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift similarity index 82% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift index 1e9eae2bf..6112dd3e4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.swift @@ -49,9 +49,12 @@ extension PrivateClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PrivateClass_wrap") -fileprivate func _bjs_PrivateClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PrivateClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PrivateClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_PrivateClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PrivateClass_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json new file mode 100644 index 000000000..a87bffa6b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -0,0 +1,185 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "namespace" : [ + "__Swift", + "Foundation" + ], + "properties" : [ + + ], + "swiftCallName" : "Greeter" + }, + { + "constructor" : { + "abiName" : "bjs_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Converter_toString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "toString", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Utils", + "Converters" + ], + "properties" : [ + + ], + "swiftCallName" : "Converter" + }, + { + "methods" : [ + { + "abiName" : "bjs_UUID_uuidString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "uuidString", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "UUID", + "namespace" : [ + "__Swift", + "Foundation" + ], + "properties" : [ + + ], + "swiftCallName" : "UUID" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : true, + "functions" : [ + { + "abiName" : "bjs_plainFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "plainFunction", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_MyModule_Utils_namespacedFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "namespacedFunction", + "namespace" : [ + "MyModule", + "Utils" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift similarity index 81% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift index cb19c6854..c4db9f0fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.swift @@ -60,12 +60,15 @@ extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_Converter_init") @_cdecl("bjs_Converter_init") @@ -107,12 +110,15 @@ extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Converter_wrap_extern(pointer) +} @_expose(wasm, "bjs_UUID_uuidString") @_cdecl("bjs_UUID_uuidString") @@ -143,9 +149,12 @@ extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_UUID_wrap") -fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_UUID_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json new file mode 100644 index 000000000..766d93a5d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -0,0 +1,185 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "namespace" : [ + "__Swift", + "Foundation" + ], + "properties" : [ + + ], + "swiftCallName" : "Greeter" + }, + { + "constructor" : { + "abiName" : "bjs_Converter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Converter_toString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "toString", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Converter", + "namespace" : [ + "Utils", + "Converters" + ], + "properties" : [ + + ], + "swiftCallName" : "Converter" + }, + { + "methods" : [ + { + "abiName" : "bjs_UUID_uuidString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "uuidString", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "UUID", + "namespace" : [ + "__Swift", + "Foundation" + ], + "properties" : [ + + ], + "swiftCallName" : "UUID" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_plainFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "plainFunction", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_MyModule_Utils_namespacedFunction", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "namespacedFunction", + "namespace" : [ + "MyModule", + "Utils" + ], + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift similarity index 81% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift index cb19c6854..c4db9f0fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.swift @@ -60,12 +60,15 @@ extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_Converter_init") @_cdecl("bjs_Converter_init") @@ -107,12 +110,15 @@ extension Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Converter_wrap_extern(pointer) +} @_expose(wasm, "bjs_UUID_uuidString") @_cdecl("bjs_UUID_uuidString") @@ -143,9 +149,12 @@ extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_UUID_wrap") -fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_UUID_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json new file mode 100644 index 000000000..9c99bb8c4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -0,0 +1,1233 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_changeName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "changeName", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Greeter" + }, + { + "constructor" : { + "abiName" : "bjs_OptionalPropertyHolder_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "OptionalPropertyHolder", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalName", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalAge", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalGreeter", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "OptionalPropertyHolder" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundTripOptionalClass", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalClass", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testOptionalPropertyRoundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testOptionalPropertyRoundtrip", + "parameters" : [ + { + "label" : "_", + "name" : "holder", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "OptionalPropertyHolder" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "OptionalPropertyHolder" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripString", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripBool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripBool", + "parameters" : [ + { + "label" : "flag", + "name" : "flag", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripFloat", + "parameters" : [ + { + "label" : "number", + "name" : "number", + "type" : { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDouble", + "parameters" : [ + { + "label" : "precision", + "name" : "precision", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripSyntax", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripSyntax", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripMixSyntax", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMixSyntax", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripSwiftSyntax", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripSwiftSyntax", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripMixedSwiftSyntax", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMixedSwiftSyntax", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripWithSpaces", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripWithSpaces", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripAlias", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripAlias", + "parameters" : [ + { + "label" : "age", + "name" : "age", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalAlias", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalAlias", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_testMixedOptionals", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testMixedOptionals", + "parameters" : [ + { + "label" : "firstName", + "name" : "firstName", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "label" : "lastName", + "name" : "lastName", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "label" : "age", + "name" : "age", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "label" : "active", + "name" : "active", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "constructor" : { + "parameters" : [ + { + "name" : "valueOrNull", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "valueOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + } + ] + }, + "getters" : [ + { + "name" : "stringOrNull", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "stringOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "doubleOrNull", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "doubleOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "boolOrNull", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "boolOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "intOrNull", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "intOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "methods" : [ + { + "name" : "roundTripStringOrNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "roundTripStringOrUndefined", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "roundTripDoubleOrNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "roundTripDoubleOrUndefined", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "roundTripBoolOrNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "roundTripBoolOrUndefined", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "roundTripIntOrNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "roundTripIntOrUndefined", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "name" : "WithOptionalJSClass", + "setters" : [ + { + "functionName" : "stringOrNull_set", + "name" : "stringOrNull", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "functionName" : "stringOrUndefined_set", + "name" : "stringOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "functionName" : "doubleOrNull_set", + "name" : "doubleOrNull", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + { + "functionName" : "doubleOrUndefined_set", + "name" : "doubleOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "functionName" : "boolOrNull_set", + "name" : "boolOrNull", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "functionName" : "boolOrUndefined_set", + "name" : "boolOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "functionName" : "intOrNull_set", + "name" : "intOrNull", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "functionName" : "intOrUndefined_set", + "name" : "intOrUndefined", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift new file mode 100644 index 000000000..eafbd3253 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -0,0 +1,881 @@ +@_expose(wasm, "bjs_roundTripOptionalClass") +@_cdecl("bjs_roundTripOptionalClass") +public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_testOptionalPropertyRoundtrip") +@_cdecl("bjs_testOptionalPropertyRoundtrip") +public func _bjs_testOptionalPropertyRoundtrip(_ holderIsSome: Int32, _ holderValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = testOptionalPropertyRoundtrip(_: Optional.bridgeJSLiftParameter(holderIsSome, holderValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripString") +@_cdecl("bjs_roundTripString") +public func _bjs_roundTripString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripInt") +@_cdecl("bjs_roundTripInt") +public func _bjs_roundTripInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripBool") +@_cdecl("bjs_roundTripBool") +public func _bjs_roundTripBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripFloat") +@_cdecl("bjs_roundTripFloat") +public func _bjs_roundTripFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { + #if arch(wasm32) + let ret = roundTripFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripDouble") +@_cdecl("bjs_roundTripDouble") +public func _bjs_roundTripDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripSyntax") +@_cdecl("bjs_roundTripSyntax") +public func _bjs_roundTripSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripMixSyntax") +@_cdecl("bjs_roundTripMixSyntax") +public func _bjs_roundTripMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripSwiftSyntax") +@_cdecl("bjs_roundTripSwiftSyntax") +public func _bjs_roundTripSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripMixedSwiftSyntax") +@_cdecl("bjs_roundTripMixedSwiftSyntax") +public func _bjs_roundTripMixedSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripMixedSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripWithSpaces") +@_cdecl("bjs_roundTripWithSpaces") +public func _bjs_roundTripWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripAlias") +@_cdecl("bjs_roundTripAlias") +public func _bjs_roundTripAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAlias") +@_cdecl("bjs_roundTripOptionalAlias") +public func _bjs_roundTripOptionalAlias(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAlias(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_testMixedOptionals") +@_cdecl("bjs_testMixedOptionals") +public func _bjs_testMixedOptionals(_ firstNameIsSome: Int32, _ firstNameBytes: Int32, _ firstNameLength: Int32, _ lastNameIsSome: Int32, _ lastNameBytes: Int32, _ lastNameLength: Int32, _ ageIsSome: Int32, _ ageValue: Int32, _ active: Int32) -> Void { + #if arch(wasm32) + let ret = testMixedOptionals(firstName: Optional.bridgeJSLiftParameter(firstNameIsSome, firstNameBytes, firstNameLength), lastName: Optional.bridgeJSLiftParameter(lastNameIsSome, lastNameBytes, lastNameLength), age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue), active: Bool.bridgeJSLiftParameter(active)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_init") +@_cdecl("bjs_Greeter_init") +public func _bjs_Greeter_init(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Greeter(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_greet") +@_cdecl("bjs_Greeter_greet") +public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greet() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_changeName") +@_cdecl("bjs_Greeter_changeName") +public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + Greeter.bridgeJSLiftParameter(_self).changeName(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_name_get") +@_cdecl("bjs_Greeter_name_get") +public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_name_set") +@_cdecl("bjs_Greeter_name_set") +public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Greeter.bridgeJSLiftParameter(_self).name = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_deinit") +@_cdecl("bjs_Greeter_deinit") +public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_init") +@_cdecl("bjs_OptionalPropertyHolder_init") +public func _bjs_OptionalPropertyHolder_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = OptionalPropertyHolder() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") +public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") +public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") +public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") +public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") +public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") +public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") +@_cdecl("bjs_OptionalPropertyHolder_deinit") +public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_OptionalPropertyHolder_wrap") +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalPropertyHolder_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_init") +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 +#else +fileprivate func bjs_WithOptionalJSClass_init_extern(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_init(_ valueOrNullIsSome: Int32, _ valueOrNullValue: Int32, _ valueOrUndefinedIsSome: Int32, _ valueOrUndefinedValue: Int32) -> Int32 { + return bjs_WithOptionalJSClass_init_extern(valueOrNullIsSome, valueOrNullValue, valueOrUndefinedIsSome, valueOrUndefinedValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrNull_get") +fileprivate func bjs_WithOptionalJSClass_stringOrNull_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_stringOrNull_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrNull_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrUndefined_get") +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrUndefined_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_doubleOrNull_get") +fileprivate func bjs_WithOptionalJSClass_doubleOrNull_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_doubleOrNull_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_doubleOrNull_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_doubleOrNull_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_doubleOrUndefined_get") +fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_doubleOrUndefined_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_boolOrNull_get") +fileprivate func bjs_WithOptionalJSClass_boolOrNull_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WithOptionalJSClass_boolOrNull_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_boolOrNull_get(_ self: Int32) -> Int32 { + return bjs_WithOptionalJSClass_boolOrNull_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_boolOrUndefined_get") +fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_get(_ self: Int32) -> Int32 { + return bjs_WithOptionalJSClass_boolOrUndefined_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_intOrNull_get") +fileprivate func bjs_WithOptionalJSClass_intOrNull_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_intOrNull_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_intOrNull_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_intOrNull_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_intOrUndefined_get") +fileprivate func bjs_WithOptionalJSClass_intOrUndefined_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_intOrUndefined_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_intOrUndefined_get(_ self: Int32) -> Void { + return bjs_WithOptionalJSClass_intOrUndefined_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrNull_set") +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_stringOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrNull_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_stringOrUndefined_set") +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_stringOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_stringOrUndefined_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_doubleOrNull_set") +fileprivate func bjs_WithOptionalJSClass_doubleOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_doubleOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_doubleOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void { + return bjs_WithOptionalJSClass_doubleOrNull_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_doubleOrUndefined_set") +fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_doubleOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Float64) -> Void { + return bjs_WithOptionalJSClass_doubleOrUndefined_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_boolOrNull_set") +fileprivate func bjs_WithOptionalJSClass_boolOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_boolOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_boolOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_boolOrNull_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_boolOrUndefined_set") +fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_boolOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_boolOrUndefined_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_intOrNull_set") +fileprivate func bjs_WithOptionalJSClass_intOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_intOrNull_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_intOrNull_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_intOrNull_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_intOrUndefined_set") +fileprivate func bjs_WithOptionalJSClass_intOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_intOrUndefined_set_extern(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_intOrUndefined_set(_ self: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_intOrUndefined_set_extern(self, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrNull") +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrNull_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripStringOrUndefined") +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripStringOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripStringOrUndefined_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripDoubleOrNull") +fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { + return bjs_WithOptionalJSClass_roundTripDoubleOrNull_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripDoubleOrUndefined") +fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripDoubleOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { + return bjs_WithOptionalJSClass_roundTripDoubleOrUndefined_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripBoolOrNull") +fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 +#else +fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 { + return bjs_WithOptionalJSClass_roundTripBoolOrNull_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripBoolOrUndefined") +fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 +#else +fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripBoolOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Int32 { + return bjs_WithOptionalJSClass_roundTripBoolOrUndefined_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripIntOrNull") +fileprivate func bjs_WithOptionalJSClass_roundTripIntOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripIntOrNull_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripIntOrNull(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripIntOrNull_extern(self, valueIsSome, valueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_WithOptionalJSClass_roundTripIntOrUndefined") +fileprivate func bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WithOptionalJSClass_roundTripIntOrUndefined(_ self: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_WithOptionalJSClass_roundTripIntOrUndefined_extern(self, valueIsSome, valueValue) +} + +func _$WithOptionalJSClass_init(_ valueOrNull: Optional, _ valueOrUndefined: JSUndefinedOr) throws(JSException) -> JSObject { + let (valueOrNullIsSome, valueOrNullValue) = valueOrNull.bridgeJSLowerParameter() + let (valueOrUndefinedIsSome, valueOrUndefinedValue) = valueOrUndefined.bridgeJSLowerParameter() + let ret = bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullValue, valueOrUndefinedIsSome, valueOrUndefinedValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$WithOptionalJSClass_stringOrNull_get(_ self: JSObject) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_stringOrNull_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_stringOrUndefined_get(_ self: JSObject) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_stringOrUndefined_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_doubleOrNull_get(_ self: JSObject) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_doubleOrNull_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_doubleOrUndefined_get(_ self: JSObject) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_doubleOrUndefined_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_boolOrNull_get(_ self: JSObject) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WithOptionalJSClass_boolOrNull_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} + +func _$WithOptionalJSClass_boolOrUndefined_get(_ self: JSObject) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WithOptionalJSClass_boolOrUndefined_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturn(ret) +} + +func _$WithOptionalJSClass_intOrNull_get(_ self: JSObject) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_intOrNull_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_intOrUndefined_get(_ self: JSObject) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_intOrUndefined_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_stringOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_doubleOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_doubleOrNull_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_doubleOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_doubleOrUndefined_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_boolOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_boolOrNull_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_boolOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_boolOrUndefined_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_intOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_intOrNull_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_intOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_intOrUndefined_set(selfValue, newValueIsSome, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripStringOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripDoubleOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripDoubleOrNull(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripDoubleOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripDoubleOrUndefined(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripBoolOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let ret = bjs_WithOptionalJSClass_roundTripBoolOrNull(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} + +func _$WithOptionalJSClass_roundTripBoolOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let ret = bjs_WithOptionalJSClass_roundTripBoolOrUndefined(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturn(ret) +} + +func _$WithOptionalJSClass_roundTripIntOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripIntOrNull(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() +} + +func _$WithOptionalJSClass_roundTripIntOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let selfValue = self.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_WithOptionalJSClass_roundTripIntOrUndefined(selfValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json new file mode 100644 index 000000000..8b586dbe0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -0,0 +1,118 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_check", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "check", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "uint" : { + + } + } + }, + { + "label" : "c", + "name" : "c", + "type" : { + "float" : { + + } + } + }, + { + "label" : "d", + "name" : "d", + "type" : { + "double" : { + + } + } + }, + { + "label" : "e", + "name" : "e", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "check", + "parameters" : [ + { + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "name" : "b", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift new file mode 100644 index 000000000..3f9448a4b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift @@ -0,0 +1,30 @@ +@_expose(wasm, "bjs_check") +@_cdecl("bjs_check") +public func _bjs_check(_ a: Int32, _ b: Int32, _ c: Float32, _ d: Float64, _ e: Int32) -> Void { + #if arch(wasm32) + check(a: Int.bridgeJSLiftParameter(a), b: UInt.bridgeJSLiftParameter(b), c: Float.bridgeJSLiftParameter(c), d: Double.bridgeJSLiftParameter(d), e: Bool.bridgeJSLiftParameter(e)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_check") +fileprivate func bjs_check_extern(_ a: Float64, _ b: Int32) -> Void +#else +fileprivate func bjs_check_extern(_ a: Float64, _ b: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_check(_ a: Float64, _ b: Int32) -> Void { + return bjs_check_extern(a, b) +} + +func _$check(_ a: Double, _ b: Bool) throws(JSException) -> Void { + let aValue = a.bridgeJSLowerParameter() + let bValue = b.bridgeJSLowerParameter() + bjs_check(aValue, bValue) + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json new file mode 100644 index 000000000..aae09ea49 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -0,0 +1,138 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_checkInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkInt", + "parameters" : [ + + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_checkUInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkUInt", + "parameters" : [ + + ], + "returnType" : { + "uint" : { + + } + } + }, + { + "abiName" : "bjs_checkFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkFloat", + "parameters" : [ + + ], + "returnType" : { + "float" : { + + } + } + }, + { + "abiName" : "bjs_checkDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkDouble", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_checkBool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkBool", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "checkNumber", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "name" : "checkBoolean", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.swift similarity index 53% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.swift index 74ee7b1c3..ace70a9c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.swift @@ -51,4 +51,44 @@ public func _bjs_checkBool() -> Int32 { #else fatalError("Only available on WebAssembly") #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkNumber") +fileprivate func bjs_checkNumber_extern() -> Float64 +#else +fileprivate func bjs_checkNumber_extern() -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkNumber() -> Float64 { + return bjs_checkNumber_extern() +} + +func _$checkNumber() throws(JSException) -> Double { + let ret = bjs_checkNumber() + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkBoolean") +fileprivate func bjs_checkBoolean_extern() -> Int32 +#else +fileprivate func bjs_checkBoolean_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkBoolean() -> Int32 { + return bjs_checkBoolean_extern() +} + +func _$checkBoolean() throws(JSException) -> Bool { + let ret = bjs_checkBoolean() + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json new file mode 100644 index 000000000..1c71b2b8f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json @@ -0,0 +1,363 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PropertyHolder_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "intValue", + "name" : "intValue", + "type" : { + "int" : { + + } + } + }, + { + "label" : "floatValue", + "name" : "floatValue", + "type" : { + "float" : { + + } + } + }, + { + "label" : "doubleValue", + "name" : "doubleValue", + "type" : { + "double" : { + + } + } + }, + { + "label" : "boolValue", + "name" : "boolValue", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { + + } + } + }, + { + "label" : "jsObject", + "name" : "jsObject", + "type" : { + "jsObject" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_PropertyHolder_getAllValues", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getAllValues", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "PropertyHolder", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "intValue", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "floatValue", + "type" : { + "float" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "doubleValue", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "boolValue", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "stringValue", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "readonlyInt", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "readonlyFloat", + "type" : { + "float" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "readonlyDouble", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "readonlyBool", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "readonlyString", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "jsObject", + "type" : { + "jsObject" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "sibling", + "type" : { + "swiftHeapObject" : { + "_0" : "PropertyHolder" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "lazyValue", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "computedReadonly", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "computedReadWrite", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "observedProperty", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "PropertyHolder" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_createPropertyHolder", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createPropertyHolder", + "parameters" : [ + { + "label" : "intValue", + "name" : "intValue", + "type" : { + "int" : { + + } + } + }, + { + "label" : "floatValue", + "name" : "floatValue", + "type" : { + "float" : { + + } + } + }, + { + "label" : "doubleValue", + "name" : "doubleValue", + "type" : { + "double" : { + + } + } + }, + { + "label" : "boolValue", + "name" : "boolValue", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { + + } + } + }, + { + "label" : "jsObject", + "name" : "jsObject", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "PropertyHolder" + } + } + }, + { + "abiName" : "bjs_testPropertyHolder", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testPropertyHolder", + "parameters" : [ + { + "label" : "holder", + "name" : "holder", + "type" : { + "swiftHeapObject" : { + "_0" : "PropertyHolder" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift similarity index 97% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift index b5b3c8d9e..de59f5166 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.swift @@ -336,9 +336,12 @@ extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PropertyHolder_wrap") -fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PropertyHolder_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json new file mode 100644 index 000000000..e9f5264cd --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -0,0 +1,909 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Helper_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Helper_increment", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "increment", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "Helper", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "Helper" + }, + { + "constructor" : { + "abiName" : "bjs_MyViewController_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "delegate", + "name" : "delegate", + "type" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_MyViewController_triggerEvent", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "triggerEvent", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewController_updateValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "updateValue", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewController_updateCount", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "updateCount", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_MyViewController_updateLabel", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "updateLabel", + "parameters" : [ + { + "label" : "_", + "name" : "prefix", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "suffix", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewController_checkEvenCount", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkEvenCount", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_MyViewController_sendHelper", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sendHelper", + "parameters" : [ + { + "label" : "_", + "name" : "helper", + "type" : { + "swiftHeapObject" : { + "_0" : "Helper" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "MyViewController", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "delegate", + "type" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "secondDelegate", + "type" : { + "nullable" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "MyViewController" + }, + { + "constructor" : { + "abiName" : "bjs_DelegateManager_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "delegates", + "name" : "delegates", + "type" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_DelegateManager_notifyAll", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "notifyAll", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "DelegateManager", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "delegates", + "type" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } + } + ], + "swiftCallName" : "DelegateManager" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "Direction", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "test", + "rawValue" : "test" + }, + { + "associatedValues" : [ + + ], + "name" : "test2", + "rawValue" : "test2" + } + ], + "emitStyle" : "const", + "name" : "ExampleEnum", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ExampleEnum", + "tsFullPath" : "ExampleEnum" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + } + ], + "emitStyle" : "const", + "name" : "Result", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Result", + "tsFullPath" : "Result" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "low", + "rawValue" : "-1" + }, + { + "associatedValues" : [ + + ], + "name" : "medium", + "rawValue" : "0" + }, + { + "associatedValues" : [ + + ], + "name" : "high", + "rawValue" : "1" + } + ], + "emitStyle" : "const", + "name" : "Priority", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Priority", + "tsFullPath" : "Priority" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_processDelegates", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processDelegates", + "parameters" : [ + { + "label" : "_", + "name" : "delegates", + "type" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftProtocol" : { + "_0" : "MyViewControllerDelegate" + } + } + } + } + } + ], + "protocols" : [ + { + "methods" : [ + { + "abiName" : "bjs_MyViewControllerDelegate_onSomethingHappened", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onSomethingHappened", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_onValueChanged", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onValueChanged", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_onCountUpdated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onCountUpdated", + "parameters" : [ + { + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_onLabelUpdated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onLabelUpdated", + "parameters" : [ + { + "label" : "_", + "name" : "prefix", + "type" : { + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "suffix", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_isCountEven", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "isCountEven", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_onHelperUpdated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onHelperUpdated", + "parameters" : [ + { + "label" : "_", + "name" : "helper", + "type" : { + "swiftHeapObject" : { + "_0" : "Helper" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_createHelper", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createHelper", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Helper" + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_onOptionalHelperUpdated", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onOptionalHelperUpdated", + "parameters" : [ + { + "label" : "_", + "name" : "helper", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Helper" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_createOptionalHelper", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createOptionalHelper", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Helper" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_createEnum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createEnum", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "ExampleEnum", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_handleResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "handleResult", + "parameters" : [ + { + "label" : "_", + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "Result" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_MyViewControllerDelegate_getResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getResult", + "parameters" : [ + + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "Result" + } + } + } + ], + "name" : "MyViewControllerDelegate", + "properties" : [ + { + "isReadonly" : false, + "name" : "eventCount", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "name" : "delegateName", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "name" : "optionalName", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalRawEnum", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "ExampleEnum", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "rawStringEnum", + "type" : { + "rawValueEnum" : { + "_0" : "ExampleEnum", + "_1" : "String" + } + } + }, + { + "isReadonly" : false, + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "Result" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalResult", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "Result" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "direction", + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + { + "isReadonly" : false, + "name" : "directionOptional", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "priority", + "type" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int" + } + } + }, + { + "isReadonly" : false, + "name" : "priorityOptional", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Priority", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + } + ] + } + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift similarity index 57% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 0558e2a1f..785cb997a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -217,104 +217,401 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } } +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onSomethingHappened") -fileprivate func _extern_onSomethingHappened(_ jsObject: Int32) -> Void +fileprivate func _extern_onSomethingHappened_extern(_ jsObject: Int32) -> Void +#else +fileprivate func _extern_onSomethingHappened_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onSomethingHappened(_ jsObject: Int32) -> Void { + return _extern_onSomethingHappened_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onValueChanged") -fileprivate func _extern_onValueChanged(_ jsObject: Int32, _ value: Int32) -> Void +fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ value: Int32) -> Void +#else +fileprivate func _extern_onValueChanged_extern(_ jsObject: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onValueChanged(_ jsObject: Int32, _ value: Int32) -> Void { + return _extern_onValueChanged_extern(jsObject, value) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onCountUpdated") -fileprivate func _extern_onCountUpdated(_ jsObject: Int32, _ count: Int32) -> Int32 +fileprivate func _extern_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 +#else +fileprivate func _extern_onCountUpdated_extern(_ jsObject: Int32, _ count: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onCountUpdated(_ jsObject: Int32, _ count: Int32) -> Int32 { + return _extern_onCountUpdated_extern(jsObject, count) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onLabelUpdated") -fileprivate func _extern_onLabelUpdated(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void +fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void +#else +fileprivate func _extern_onLabelUpdated_extern(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onLabelUpdated(_ jsObject: Int32, _ prefix: Int32, _ suffix: Int32) -> Void { + return _extern_onLabelUpdated_extern(jsObject, prefix, suffix) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_isCountEven") -fileprivate func _extern_isCountEven(_ jsObject: Int32) -> Int32 +fileprivate func _extern_isCountEven_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_isCountEven_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_isCountEven(_ jsObject: Int32) -> Int32 { + return _extern_isCountEven_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onHelperUpdated") -fileprivate func _extern_onHelperUpdated(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void +fileprivate func _extern_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void +#else +fileprivate func _extern_onHelperUpdated_extern(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onHelperUpdated(_ jsObject: Int32, _ helper: UnsafeMutableRawPointer) -> Void { + return _extern_onHelperUpdated_extern(jsObject, helper) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createHelper") -fileprivate func _extern_createHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func _extern_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createHelper_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_onOptionalHelperUpdated") -fileprivate func _extern_onOptionalHelperUpdated(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void +fileprivate func _extern_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void +#else +fileprivate func _extern_onOptionalHelperUpdated_extern(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onOptionalHelperUpdated(_ jsObject: Int32, _ helperIsSome: Int32, _ helperPointer: UnsafeMutableRawPointer) -> Void { + return _extern_onOptionalHelperUpdated_extern(jsObject, helperIsSome, helperPointer) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createOptionalHelper") -fileprivate func _extern_createOptionalHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func _extern_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createOptionalHelper_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createOptionalHelper(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createOptionalHelper_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_createEnum") -fileprivate func _extern_createEnum(_ jsObject: Int32) -> Int32 +fileprivate func _extern_createEnum_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_createEnum_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createEnum(_ jsObject: Int32) -> Int32 { + return _extern_createEnum_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_handleResult") -fileprivate func _extern_handleResult(_ jsObject: Int32, _ result: Int32) -> Void +fileprivate func _extern_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void +#else +fileprivate func _extern_handleResult_extern(_ jsObject: Int32, _ result: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_handleResult(_ jsObject: Int32, _ result: Int32) -> Void { + return _extern_handleResult_extern(jsObject, result) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_getResult") -fileprivate func _extern_getResult(_ jsObject: Int32) -> Int32 +fileprivate func _extern_getResult_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getResult_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getResult(_ jsObject: Int32) -> Int32 { + return _extern_getResult_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_eventCount_get") -fileprivate func bjs_MyViewControllerDelegate_eventCount_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_eventCount_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_eventCount_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_eventCount_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_eventCount_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_eventCount_set") -fileprivate func bjs_MyViewControllerDelegate_eventCount_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_eventCount_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_eventCount_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_eventCount_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_eventCount_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_delegateName_get") -fileprivate func bjs_MyViewControllerDelegate_delegateName_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_delegateName_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_delegateName_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_delegateName_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_delegateName_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalName_get") -fileprivate func bjs_MyViewControllerDelegate_optionalName_get(_ jsObject: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalName_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_optionalName_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_get(_ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalName_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalName_set") -fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_optionalName_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalName_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalName_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalRawEnum_get") -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get(_ jsObject: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_get(_ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalRawEnum_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalRawEnum_set") -fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalRawEnum_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalRawEnum_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_rawStringEnum_get") -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_rawStringEnum_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_rawStringEnum_set") -fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_rawStringEnum_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_rawStringEnum_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_result_get") -fileprivate func bjs_MyViewControllerDelegate_result_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_result_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_result_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_result_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_result_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_result_set") -fileprivate func bjs_MyViewControllerDelegate_result_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_result_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_result_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_result_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_result_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalResult_get") -fileprivate func bjs_MyViewControllerDelegate_optionalResult_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_optionalResult_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_optionalResult_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalResult_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_optionalResult_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_optionalResult_set") -fileprivate func bjs_MyViewControllerDelegate_optionalResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_optionalResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_optionalResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_optionalResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + return bjs_MyViewControllerDelegate_optionalResult_set_extern(jsObject, newValueIsSome, newValueCaseId) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_direction_get") -fileprivate func bjs_MyViewControllerDelegate_direction_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_direction_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_direction_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_direction_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_direction_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_direction_set") -fileprivate func bjs_MyViewControllerDelegate_direction_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_direction_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_direction_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_direction_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_direction_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_directionOptional_get") -fileprivate func bjs_MyViewControllerDelegate_directionOptional_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_directionOptional_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_directionOptional_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_directionOptional_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_directionOptional_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_directionOptional_set") -fileprivate func bjs_MyViewControllerDelegate_directionOptional_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_directionOptional_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_directionOptional_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_directionOptional_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_directionOptional_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_priority_get") -fileprivate func bjs_MyViewControllerDelegate_priority_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_MyViewControllerDelegate_priority_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_MyViewControllerDelegate_priority_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_priority_get(_ jsObject: Int32) -> Int32 { + return bjs_MyViewControllerDelegate_priority_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_priority_set") -fileprivate func bjs_MyViewControllerDelegate_priority_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_priority_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_priority_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_priority_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_priority_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_priorityOptional_get") -fileprivate func bjs_MyViewControllerDelegate_priorityOptional_get(_ jsObject: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_priorityOptional_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_priorityOptional_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_priorityOptional_get(_ jsObject: Int32) -> Void { + return bjs_MyViewControllerDelegate_priorityOptional_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewControllerDelegate_priorityOptional_set") -fileprivate func bjs_MyViewControllerDelegate_priorityOptional_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_MyViewControllerDelegate_priorityOptional_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_MyViewControllerDelegate_priorityOptional_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyViewControllerDelegate_priorityOptional_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_MyViewControllerDelegate_priorityOptional_set_extern(jsObject, newValueIsSome, newValueValue) +} extension Direction: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { @@ -359,82 +656,42 @@ extension Direction: _BridgedSwiftCaseEnum { } } -extension ExampleEnum: _BridgedSwiftEnumNoPayload { +extension ExampleEnum: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension Result: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> Result { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Result { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(Int.bridgeJSStackPop()) default: fatalError("Unknown Result case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0): - _swift_js_push_i32(Int32(param0)) + param0.bridgeJSStackPush() return Int32(1) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - } - } } -extension Priority: _BridgedSwiftEnumNoPayload { +extension Priority: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } @_expose(wasm, "bjs_processDelegates") @_cdecl("bjs_processDelegates") public func _bjs_processDelegates() -> Void { #if arch(wasm32) - let ret = processDelegates(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [AnyMyViewControllerDelegate] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(AnyMyViewControllerDelegate.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! AnyMyViewControllerDelegate).bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = processDelegates(_: [AnyMyViewControllerDelegate].bridgeJSStackPop()) + ret.map { $0 as! AnyMyViewControllerDelegate }.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -500,12 +757,15 @@ extension Helper: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Helper_wrap") -fileprivate func _bjs_Helper_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Helper_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Helper_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Helper_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Helper_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Helper_wrap_extern(pointer) +} @_expose(wasm, "bjs_MyViewController_init") @_cdecl("bjs_MyViewController_init") @@ -605,9 +865,7 @@ public func _bjs_MyViewController_delegate_set(_ _self: UnsafeMutableRawPointer, @_cdecl("bjs_MyViewController_secondDelegate_get") public func _bjs_MyViewController_secondDelegate_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MyViewController.bridgeJSLiftParameter(_self).secondDelegate.flatMap { - $0 as? AnyMyViewControllerDelegate - } + let ret = (MyViewController.bridgeJSLiftParameter(_self).secondDelegate).flatMap { $0 as? AnyMyViewControllerDelegate } return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -642,27 +900,21 @@ extension MyViewController: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MyViewController_wrap") -fileprivate func _bjs_MyViewController_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_MyViewController_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_MyViewController_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_MyViewController_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_MyViewController_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_MyViewController_wrap_extern(pointer) +} @_expose(wasm, "bjs_DelegateManager_init") @_cdecl("bjs_DelegateManager_init") public func _bjs_DelegateManager_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DelegateManager(delegates: { - let __count = Int(_swift_js_pop_i32()) - var __result: [AnyMyViewControllerDelegate] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(AnyMyViewControllerDelegate.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) + let ret = DelegateManager(delegates: [AnyMyViewControllerDelegate].bridgeJSStackPop()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -684,9 +936,7 @@ public func _bjs_DelegateManager_notifyAll(_ _self: UnsafeMutableRawPointer) -> public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) let ret = DelegateManager.bridgeJSLiftParameter(_self).delegates - for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! AnyMyViewControllerDelegate).bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + ret.map { $0 as! AnyMyViewControllerDelegate }.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -696,16 +946,7 @@ public func _bjs_DelegateManager_delegates_get(_ _self: UnsafeMutableRawPointer) @_cdecl("bjs_DelegateManager_delegates_set") public func _bjs_DelegateManager_delegates_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DelegateManager.bridgeJSLiftParameter(_self).delegates = { - let __count = Int(_swift_js_pop_i32()) - var __result: [AnyMyViewControllerDelegate] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(AnyMyViewControllerDelegate.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }() + DelegateManager.bridgeJSLiftParameter(_self).delegates = [AnyMyViewControllerDelegate].bridgeJSStackPop() #else fatalError("Only available on WebAssembly") #endif @@ -729,9 +970,12 @@ extension DelegateManager: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_DelegateManager_wrap") -fileprivate func _bjs_DelegateManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_DelegateManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_DelegateManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_DelegateManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_DelegateManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_DelegateManager_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json new file mode 100644 index 000000000..b0eac3313 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -0,0 +1,339 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_MathUtils_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_MathUtils_static_subtract", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "subtract", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } + }, + { + "abiName" : "bjs_MathUtils_static_add", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "add", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } + }, + { + "abiName" : "bjs_MathUtils_multiply", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "multiply", + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + } + } + ], + "name" : "MathUtils", + "properties" : [ + + ], + "swiftCallName" : "MathUtils" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "scientific" + }, + { + "associatedValues" : [ + + ], + "name" : "basic" + } + ], + "emitStyle" : "const", + "name" : "Calculator", + "staticMethods" : [ + { + "abiName" : "bjs_Calculator_static_square", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "square", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Calculator", + "tsFullPath" : "Calculator" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + } + ], + "emitStyle" : "const", + "name" : "APIResult", + "staticMethods" : [ + { + "abiName" : "bjs_APIResult_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "staticContext" : { + "enumName" : { + "_0" : "APIResult" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utils", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "String", + "namespace" : [ + "Utils" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Utils_String_static_uppercase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "uppercase", + "namespace" : [ + "Utils", + "String" + ], + "parameters" : [ + { + "label" : "_", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "Utils.String" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils.String", + "tsFullPath" : "Utils.String" + } + ], + "exposeToGlobal" : true, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift similarity index 75% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 378eff8bb..b6d35a215 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -45,56 +45,27 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { } extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(Int.bridgeJSStackPop()) default: fatalError("Unknown APIResult case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0): - _swift_js_push_i32(Int32(param0)) + param0.bridgeJSStackPush() return Int32(1) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - } - } } @_expose(wasm, "bjs_APIResult_static_roundtrip") @@ -181,9 +152,12 @@ extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MathUtils_wrap") -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_MathUtils_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json new file mode 100644 index 000000000..e4ec22855 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -0,0 +1,339 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_MathUtils_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_MathUtils_static_subtract", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "subtract", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } + }, + { + "abiName" : "bjs_MathUtils_static_add", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "add", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "int" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "className" : { + "_0" : "MathUtils" + } + } + }, + { + "abiName" : "bjs_MathUtils_multiply", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "multiply", + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + } + } + ], + "name" : "MathUtils", + "properties" : [ + + ], + "swiftCallName" : "MathUtils" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "scientific" + }, + { + "associatedValues" : [ + + ], + "name" : "basic" + } + ], + "emitStyle" : "const", + "name" : "Calculator", + "staticMethods" : [ + { + "abiName" : "bjs_Calculator_static_square", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "square", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Calculator" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Calculator", + "tsFullPath" : "Calculator" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + } + ], + "emitStyle" : "const", + "name" : "APIResult", + "staticMethods" : [ + { + "abiName" : "bjs_APIResult_static_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "roundtrip", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "staticContext" : { + "enumName" : { + "_0" : "APIResult" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Utils", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils", + "tsFullPath" : "Utils" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "String", + "namespace" : [ + "Utils" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Utils_String_static_uppercase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "uppercase", + "namespace" : [ + "Utils", + "String" + ], + "parameters" : [ + { + "label" : "_", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "Utils.String" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils.String", + "tsFullPath" : "Utils.String" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift similarity index 75% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 378eff8bb..b6d35a215 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -45,56 +45,27 @@ public func _bjs_Calculator_static_square(_ value: Int32) -> Int32 { } extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(Int.bridgeJSStackPop()) default: fatalError("Unknown APIResult case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0): - _swift_js_push_i32(Int32(param0)) + param0.bridgeJSStackPush() return Int32(1) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - } - } } @_expose(wasm, "bjs_APIResult_static_roundtrip") @@ -181,9 +152,12 @@ extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_MathUtils_wrap") -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_MathUtils_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json new file mode 100644 index 000000000..bb9e48091 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json @@ -0,0 +1,343 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PropertyClass_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "PropertyClass", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "staticConstant", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "staticVariable", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "jsObjectProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "jsObject" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "classVariable", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "computedProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "readOnlyComputed", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "optionalProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "PropertyClass" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "value1" + }, + { + "associatedValues" : [ + + ], + "name" : "value2" + } + ], + "emitStyle" : "const", + "name" : "PropertyEnum", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumProperty", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "enumConstant", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "computedEnum", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "PropertyEnum", + "tsFullPath" : "PropertyEnum" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "PropertyNamespace", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "namespaceProperty", + "namespace" : [ + "PropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "namespaceConstant", + "namespace" : [ + "PropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "PropertyNamespace", + "tsFullPath" : "PropertyNamespace" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Nested", + "namespace" : [ + "PropertyNamespace" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedProperty", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "nestedConstant", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedDouble", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "PropertyNamespace.Nested", + "tsFullPath" : "PropertyNamespace.Nested" + } + ], + "exposeToGlobal" : true, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift similarity index 97% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index 6510fd89f..43b1861ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -327,9 +327,12 @@ extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PropertyClass_wrap") -fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PropertyClass_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json new file mode 100644 index 000000000..d385e3887 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json @@ -0,0 +1,343 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PropertyClass_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "PropertyClass", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "staticConstant", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "staticVariable", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "jsObjectProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "jsObject" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "classVariable", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "computedProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "readOnlyComputed", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "optionalProperty", + "staticContext" : { + "className" : { + "_0" : "PropertyClass" + } + }, + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "PropertyClass" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "value1" + }, + { + "associatedValues" : [ + + ], + "name" : "value2" + } + ], + "emitStyle" : "const", + "name" : "PropertyEnum", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "enumProperty", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "enumConstant", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "computedEnum", + "staticContext" : { + "enumName" : { + "_0" : "PropertyEnum" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "PropertyEnum", + "tsFullPath" : "PropertyEnum" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "PropertyNamespace", + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "namespaceProperty", + "namespace" : [ + "PropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "namespaceConstant", + "namespace" : [ + "PropertyNamespace" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "PropertyNamespace", + "tsFullPath" : "PropertyNamespace" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Nested", + "namespace" : [ + "PropertyNamespace" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedProperty", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "nestedConstant", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "nestedDouble", + "namespace" : [ + "PropertyNamespace", + "Nested" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "PropertyNamespace.Nested" + } + }, + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "PropertyNamespace.Nested", + "tsFullPath" : "PropertyNamespace.Nested" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift similarity index 97% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index 6510fd89f..43b1861ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -327,9 +327,12 @@ extension PropertyClass: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PropertyClass_wrap") -fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PropertyClass_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json new file mode 100644 index 000000000..b0aa8c35b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json @@ -0,0 +1,125 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_checkString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkString", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_roundtripString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripString", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "checkString", + "parameters" : [ + { + "name" : "a", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "checkStringWithLength", + "parameters" : [ + { + "name" : "a", + "type" : { + "string" : { + + } + } + }, + { + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift new file mode 100644 index 000000000..427c2b576 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.swift @@ -0,0 +1,61 @@ +@_expose(wasm, "bjs_checkString") +@_cdecl("bjs_checkString") +public func _bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { + #if arch(wasm32) + checkString(a: String.bridgeJSLiftParameter(aBytes, aLength)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripString") +@_cdecl("bjs_roundtripString") +public func _bjs_roundtripString(_ aBytes: Int32, _ aLength: Int32) -> Void { + #if arch(wasm32) + let ret = roundtripString(a: String.bridgeJSLiftParameter(aBytes, aLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkString") +fileprivate func bjs_checkString_extern(_ a: Int32) -> Void +#else +fileprivate func bjs_checkString_extern(_ a: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkString(_ a: Int32) -> Void { + return bjs_checkString_extern(a) +} + +func _$checkString(_ a: String) throws(JSException) -> Void { + let aValue = a.bridgeJSLowerParameter() + bjs_checkString(aValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkStringWithLength") +fileprivate func bjs_checkStringWithLength_extern(_ a: Int32, _ b: Float64) -> Void +#else +fileprivate func bjs_checkStringWithLength_extern(_ a: Int32, _ b: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkStringWithLength(_ a: Int32, _ b: Float64) -> Void { + return bjs_checkStringWithLength_extern(a, b) +} + +func _$checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void { + let aValue = a.bridgeJSLowerParameter() + let bValue = b.bridgeJSLowerParameter() + bjs_checkStringWithLength(aValue, bValue) + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json new file mode 100644 index 000000000..3f9271592 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json @@ -0,0 +1,59 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_checkString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "checkString", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "checkString", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.swift new file mode 100644 index 000000000..6a4cf795a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.swift @@ -0,0 +1,30 @@ +@_expose(wasm, "bjs_checkString") +@_cdecl("bjs_checkString") +public func _bjs_checkString() -> Void { + #if arch(wasm32) + let ret = checkString() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_checkString") +fileprivate func bjs_checkString_extern() -> Int32 +#else +fileprivate func bjs_checkString_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_checkString() -> Int32 { + return bjs_checkString_extern() +} + +func _$checkString() throws(JSException) -> String { + let ret = bjs_checkString() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json new file mode 100644 index 000000000..7cebdd5e6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -0,0 +1,202 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_changeName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "changeName", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Greeter" + }, + { + "explicitAccessControl" : "public", + "methods" : [ + + ], + "name" : "PublicGreeter", + "properties" : [ + + ], + "swiftCallName" : "PublicGreeter" + }, + { + "explicitAccessControl" : "package", + "methods" : [ + + ], + "name" : "PackageGreeter", + "properties" : [ + + ], + "swiftCallName" : "PackageGreeter" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_takeGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeGreeter", + "parameters" : [ + { + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "jsRoundTripGreeter", + "parameters" : [ + { + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "name" : "jsRoundTripOptionalGreeter", + "parameters" : [ + { + "name" : "greeter", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift similarity index 59% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift index 216dfc684..0e9434832 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.swift @@ -79,12 +79,15 @@ extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_PublicGreeter_deinit") @_cdecl("bjs_PublicGreeter_deinit") @@ -104,12 +107,15 @@ extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PublicGreeter_wrap") -fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PublicGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_PackageGreeter_deinit") @_cdecl("bjs_PackageGreeter_deinit") @@ -129,9 +135,54 @@ extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PackageGreeter_wrap") -fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PackageGreeter_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_jsRoundTripGreeter") +fileprivate func bjs_jsRoundTripGreeter_extern(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_jsRoundTripGreeter_extern(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func bjs_jsRoundTripGreeter(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return bjs_jsRoundTripGreeter_extern(greeter) +} + +func _$jsRoundTripGreeter(_ greeter: Greeter) throws(JSException) -> Greeter { + let greeterPointer = greeter.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripGreeter(greeterPointer) + if let error = _swift_js_take_exception() { + throw error + } + return Greeter.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_jsRoundTripOptionalGreeter") +fileprivate func bjs_jsRoundTripOptionalGreeter_extern(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer +#else +fileprivate func bjs_jsRoundTripOptionalGreeter_extern(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalGreeter(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return bjs_jsRoundTripOptionalGreeter_extern(greeterIsSome, greeterPointer) +} + +func _$jsRoundTripOptionalGreeter(_ greeter: Optional) throws(JSException) -> Optional { + let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripOptionalGreeter(greeterIsSome, greeterPointer) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json new file mode 100644 index 000000000..11c6cb893 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -0,0 +1,1809 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Person_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "explicitAccessControl" : "public", + "methods" : [ + + ], + "name" : "Person", + "properties" : [ + + ], + "swiftCallName" : "Person" + }, + { + "constructor" : { + "abiName" : "bjs_TestProcessor_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "transform", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "TestProcessor", + "properties" : [ + + ], + "swiftCallName" : "TestProcessor" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ + + ], + "name" : "west" + } + ], + "emitStyle" : "const", + "name" : "Direction", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Direction", + "tsFullPath" : "Direction" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light", + "rawValue" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark", + "rawValue" : "dark" + }, + { + "associatedValues" : [ + + ], + "name" : "auto", + "rawValue" : "auto" + } + ], + "emitStyle" : "const", + "name" : "Theme", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Theme", + "tsFullPath" : "Theme" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "ok", + "rawValue" : "200" + }, + { + "associatedValues" : [ + + ], + "name" : "notFound", + "rawValue" : "404" + }, + { + "associatedValues" : [ + + ], + "name" : "serverError", + "rawValue" : "500" + }, + { + "associatedValues" : [ + + ], + "name" : "unknown", + "rawValue" : "-1" + } + ], + "emitStyle" : "const", + "name" : "HttpStatus", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "HttpStatus", + "tsFullPath" : "HttpStatus" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "int" : { + + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "bool" : { + + } + } + } + ], + "name" : "flag" + }, + { + "associatedValues" : [ + { + "type" : { + "float" : { + + } + } + } + ], + "name" : "rate" + }, + { + "associatedValues" : [ + { + "type" : { + "double" : { + + } + } + } + ], + "name" : "precise" + }, + { + "associatedValues" : [ + + ], + "name" : "info" + } + ], + "emitStyle" : "const", + "name" : "APIResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIResult", + "tsFullPath" : "APIResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundtripString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripString", + "parameters" : [ + { + "label" : "_", + "name" : "stringClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripInt", + "parameters" : [ + { + "label" : "_", + "name" : "intClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSi_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSi_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripBool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripBool", + "parameters" : [ + { + "label" : "_", + "name" : "boolClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSb_Sb", + "moduleName" : "TestModule", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSb_Sb", + "moduleName" : "TestModule", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripFloat", + "parameters" : [ + { + "label" : "_", + "name" : "floatClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSf_Sf", + "moduleName" : "TestModule", + "parameters" : [ + { + "float" : { + + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSf_Sf", + "moduleName" : "TestModule", + "parameters" : [ + { + "float" : { + + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripDouble", + "parameters" : [ + { + "label" : "_", + "name" : "doubleClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSd_Sd", + "moduleName" : "TestModule", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSd_Sd", + "moduleName" : "TestModule", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalString", + "parameters" : [ + { + "label" : "_", + "name" : "stringClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSS_SqSS", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSS_SqSS", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalInt", + "parameters" : [ + { + "label" : "_", + "name" : "intClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSi_SqSi", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSi_SqSi", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalBool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalBool", + "parameters" : [ + { + "label" : "_", + "name" : "boolClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSb_SqSb", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSb_SqSb", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalFloat", + "parameters" : [ + { + "label" : "_", + "name" : "floatClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSf_SqSf", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSf_SqSf", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "float" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalDouble", + "parameters" : [ + { + "label" : "_", + "name" : "doubleClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSd_SqSd", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSqSd_SqSd", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "double" : { + + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripPerson", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripPerson", + "parameters" : [ + { + "label" : "_", + "name" : "personClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule6PersonC_6PersonC", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftHeapObject" : { + "_0" : "Person" + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Person" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule6PersonC_6PersonC", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftHeapObject" : { + "_0" : "Person" + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Person" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalPerson", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalPerson", + "parameters" : [ + { + "label" : "_", + "name" : "personClosure", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq6PersonC_Sq6PersonC", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Person" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Person" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq6PersonC_Sq6PersonC", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Person" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Person" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripDirection", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule9DirectionO_9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "caseEnum" : { + "_0" : "Direction" + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule9DirectionO_9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "caseEnum" : { + "_0" : "Direction" + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Direction" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripTheme", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule5ThemeO_5ThemeO", + "moduleName" : "TestModule", + "parameters" : [ + { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule5ThemeO_5ThemeO", + "moduleName" : "TestModule", + "parameters" : [ + { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule10HttpStatusO_10HttpStatusO", + "moduleName" : "TestModule", + "parameters" : [ + { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule10HttpStatusO_10HttpStatusO", + "moduleName" : "TestModule", + "parameters" : [ + { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripAPIResult", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule9APIResultO_9APIResultO", + "moduleName" : "TestModule", + "parameters" : [ + { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule9APIResultO_9APIResultO", + "moduleName" : "TestModule", + "parameters" : [ + { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalDirection", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9DirectionO_Sq9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9DirectionO_Sq9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalTheme", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq5ThemeO_Sq5ThemeO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq5ThemeO_Sq5ThemeO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq10HttpStatusO_Sq10HttpStatusO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq10HttpStatusO_Sq10HttpStatusO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalAPIResult", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9APIResultO_Sq9APIResultO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9APIResultO_Sq9APIResultO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_roundtripOptionalDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripOptionalDirection", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9DirectionO_Sq9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSq9DirectionO_Sq9DirectionO", + "moduleName" : "TestModule", + "parameters" : [ + { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift new file mode 100644 index 000000000..d4bdc4a58 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -0,0 +1,1660 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO") +fileprivate func invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO") +fileprivate func make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule10HttpStatusO_10HttpStatusO { + static func bridgeJSLift(_ callbackId: Int32) -> (HttpStatus) -> HttpStatus { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO(callbackValue, param0Value) + return HttpStatus.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (HttpStatus) -> HttpStatus { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (HttpStatus) -> HttpStatus) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO") +@_cdecl("invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO") +public func _invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(HttpStatus) -> HttpStatus>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(HttpStatus.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO") +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO") +fileprivate func make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule5ThemeO_5ThemeO { + static func bridgeJSLift(_ callbackId: Int32) -> (Theme) -> Theme { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Value) + return Theme.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Theme) -> Theme { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Theme) -> Theme) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO") +@_cdecl("invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO") +public func _invoke_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> Theme>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC") +fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer +#else +fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule6PersonC_6PersonC") +fileprivate func make_swift_closure_TestModule_10TestModule6PersonC_6PersonC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule6PersonC_6PersonC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule6PersonC_6PersonC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule6PersonC_6PersonC_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule6PersonC_6PersonC { + static func bridgeJSLift(_ callbackId: Int32) -> (Person) -> Person { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Pointer = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC(callbackValue, param0Pointer) + return Person.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Person) -> Person { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Person) -> Person) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule6PersonC_6PersonC, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC") +@_cdecl("invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC") +public func _invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Person) -> Person>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Person.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO") +fileprivate func invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO") +fileprivate func make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule9APIResultO_9APIResultO { + static func bridgeJSLift(_ callbackId: Int32) -> (APIResult) -> APIResult { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0CaseId = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO(callbackValue, param0CaseId) + return APIResult.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (APIResult) -> APIResult { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (APIResult) -> APIResult) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO") +@_cdecl("invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO") +public func _invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(APIResult) -> APIResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(APIResult.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO") +fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO") +fileprivate func make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule9DirectionO_9DirectionO { + static func bridgeJSLift(_ callbackId: Int32) -> (Direction) -> Direction { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO(callbackValue, param0Value) + return Direction.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Direction) -> Direction { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Direction) -> Direction) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO") +@_cdecl("invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO") +public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> Direction>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Direction.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSS_SS") +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSS_SS_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSS_SS") +fileprivate func make_swift_closure_TestModule_10TestModuleSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Value) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> String) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSS_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSS_SS") +public func _invoke_swift_closure_TestModule_10TestModuleSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSb_Sb") +fileprivate func invoke_js_callback_TestModule_10TestModuleSb_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSb_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSb_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSb_Sb_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSb_Sb") +fileprivate func make_swift_closure_TestModule_10TestModuleSb_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSb_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSb_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSb_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSb_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> (Bool) -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSb_Sb(callbackValue, param0Value) + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Bool) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Bool) -> Bool) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSb_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSb_Sb") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSb_Sb") +public func _invoke_swift_closure_TestModule_10TestModuleSb_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Bool.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSd_Sd") +fileprivate func invoke_js_callback_TestModule_10TestModuleSd_Sd_extern(_ callback: Int32, _ param0: Float64) -> Float64 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSd_Sd_extern(_ callback: Int32, _ param0: Float64) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSd_Sd(_ callback: Int32, _ param0: Float64) -> Float64 { + return invoke_js_callback_TestModule_10TestModuleSd_Sd_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSd_Sd") +fileprivate func make_swift_closure_TestModule_10TestModuleSd_Sd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSd_Sd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSd_Sd_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSd_Sd { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) -> Double { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSd_Sd(callbackValue, param0Value) + return Double.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Double) -> Double { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) -> Double) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSd_Sd, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSd_Sd") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSd_Sd") +public func _invoke_swift_closure_TestModule_10TestModuleSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Float64 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Double>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Double.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSf_Sf") +fileprivate func invoke_js_callback_TestModule_10TestModuleSf_Sf_extern(_ callback: Int32, _ param0: Float32) -> Float32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSf_Sf_extern(_ callback: Int32, _ param0: Float32) -> Float32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSf_Sf(_ callback: Int32, _ param0: Float32) -> Float32 { + return invoke_js_callback_TestModule_10TestModuleSf_Sf_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSf_Sf") +fileprivate func make_swift_closure_TestModule_10TestModuleSf_Sf_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSf_Sf_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSf_Sf(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSf_Sf_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSf_Sf { + static func bridgeJSLift(_ callbackId: Int32) -> (Float) -> Float { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSf_Sf(callbackValue, param0Value) + return Float.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Float) -> Float { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Float) -> Float) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSf_Sf, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSf_Sf") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSf_Sf") +public func _invoke_swift_closure_TestModule_10TestModuleSf_Sf(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float32) -> Float32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Float) -> Float>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Float.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSi_Si") +fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSi_Si_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSi_Si") +fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSi_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSi_Si(callbackValue, param0Value) + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Int) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int) -> Int) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSi_Si") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSi_Si") +public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO") +fileprivate func make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq10HttpStatusO_Sq10HttpStatusO { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO") +public func _invoke_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") +fileprivate func make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO") +public func _invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(callback, param0IsSome, param0Pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC") +fileprivate func make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq6PersonC_Sq6PersonC { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC(callbackValue, param0IsSome, param0Pointer) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC") +public func _invoke_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(callback, param0IsSome, param0CaseId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO") +fileprivate func make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq9APIResultO_Sq9APIResultO { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(callbackValue, param0IsSome, param0CaseId) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO") +public func _invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO") +fileprivate func invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO") +fileprivate func make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO") +public func _invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSS_SqSS") +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSS_SqSS_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSqSS_SqSS") +fileprivate func make_swift_closure_TestModule_10TestModuleSqSS_SqSS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSqSS_SqSS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSqSS_SqSS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSqSS_SqSS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSqSS_SqSS { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSqSS_SqSS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSqSS_SqSS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSS_SqSS") +public func _invoke_swift_closure_TestModule_10TestModuleSqSS_SqSS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSb_SqSb") +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSb_SqSb_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSb_SqSb_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSb_SqSb(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSqSb_SqSb_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSqSb_SqSb") +fileprivate func make_swift_closure_TestModule_10TestModuleSqSb_SqSb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSqSb_SqSb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSqSb_SqSb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSqSb_SqSb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSqSb_SqSb { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSqSb_SqSb(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSqSb_SqSb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb") +public func _invoke_swift_closure_TestModule_10TestModuleSqSb_SqSb(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSd_SqSd") +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSd_SqSd_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSd_SqSd_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSd_SqSd(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSd_SqSd_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSqSd_SqSd") +fileprivate func make_swift_closure_TestModule_10TestModuleSqSd_SqSd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSqSd_SqSd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSqSd_SqSd(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSqSd_SqSd_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSqSd_SqSd { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSqSd_SqSd(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSqSd_SqSd, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSqSd_SqSd") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSd_SqSd") +public func _invoke_swift_closure_TestModule_10TestModuleSqSd_SqSd(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSf_SqSf") +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSf_SqSf_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSf_SqSf_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSf_SqSf(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSf_SqSf_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSqSf_SqSf") +fileprivate func make_swift_closure_TestModule_10TestModuleSqSf_SqSf_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSqSf_SqSf_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSqSf_SqSf(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSqSf_SqSf_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSqSf_SqSf { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSqSf_SqSf(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSqSf_SqSf, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf") +public func _invoke_swift_closure_TestModule_10TestModuleSqSf_SqSf(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSqSi_SqSi") +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSi_SqSi_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSqSi_SqSi_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSqSi_SqSi(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSqSi_SqSi_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSqSi_SqSi") +fileprivate func make_swift_closure_TestModule_10TestModuleSqSi_SqSi_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSqSi_SqSi_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSqSi_SqSi(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSqSi_SqSi_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSqSi_SqSi { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleSqSi_SqSi(callbackValue, param0IsSome, param0Value) + return Optional.bridgeJSLiftReturnFromSideChannel() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSqSi_SqSi, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi") +public func _invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Direction: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { + return Direction(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + private init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + case 2: + self = .east + case 3: + self = .west + default: + return nil + } + } + + private var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + case .east: + return 2 + case .west: + return 3 + } + } +} + +extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension APIResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .flag(Bool.bridgeJSStackPop()) + case 3: + return .rate(Float.bridgeJSStackPop()) + case 4: + return .precise(Double.bridgeJSStackPop()) + case 5: + return .info + default: + fatalError("Unknown APIResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .flag(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .rate(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .precise(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .info: + return Int32(5) + } + } +} + +@_expose(wasm, "bjs_roundtripString") +@_cdecl("bjs_roundtripString") +public func _bjs_roundtripString(_ stringClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripString(_: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(stringClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripInt") +@_cdecl("bjs_roundtripInt") +public func _bjs_roundtripInt(_ intClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripInt(_: _BJS_Closure_10TestModuleSi_Si.bridgeJSLift(intClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripBool") +@_cdecl("bjs_roundtripBool") +public func _bjs_roundtripBool(_ boolClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripBool(_: _BJS_Closure_10TestModuleSb_Sb.bridgeJSLift(boolClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripFloat") +@_cdecl("bjs_roundtripFloat") +public func _bjs_roundtripFloat(_ floatClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripFloat(_: _BJS_Closure_10TestModuleSf_Sf.bridgeJSLift(floatClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripDouble") +@_cdecl("bjs_roundtripDouble") +public func _bjs_roundtripDouble(_ doubleClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripDouble(_: _BJS_Closure_10TestModuleSd_Sd.bridgeJSLift(doubleClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalString") +@_cdecl("bjs_roundtripOptionalString") +public func _bjs_roundtripOptionalString(_ stringClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalString(_: _BJS_Closure_10TestModuleSqSS_SqSS.bridgeJSLift(stringClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalInt") +@_cdecl("bjs_roundtripOptionalInt") +public func _bjs_roundtripOptionalInt(_ intClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalInt(_: _BJS_Closure_10TestModuleSqSi_SqSi.bridgeJSLift(intClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalBool") +@_cdecl("bjs_roundtripOptionalBool") +public func _bjs_roundtripOptionalBool(_ boolClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalBool(_: _BJS_Closure_10TestModuleSqSb_SqSb.bridgeJSLift(boolClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalFloat") +@_cdecl("bjs_roundtripOptionalFloat") +public func _bjs_roundtripOptionalFloat(_ floatClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalFloat(_: _BJS_Closure_10TestModuleSqSf_SqSf.bridgeJSLift(floatClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalDouble") +@_cdecl("bjs_roundtripOptionalDouble") +public func _bjs_roundtripOptionalDouble(_ doubleClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalDouble(_: _BJS_Closure_10TestModuleSqSd_SqSd.bridgeJSLift(doubleClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripPerson") +@_cdecl("bjs_roundtripPerson") +public func _bjs_roundtripPerson(_ personClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripPerson(_: _BJS_Closure_10TestModule6PersonC_6PersonC.bridgeJSLift(personClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalPerson") +@_cdecl("bjs_roundtripOptionalPerson") +public func _bjs_roundtripOptionalPerson(_ personClosure: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalPerson(_: _BJS_Closure_10TestModuleSq6PersonC_Sq6PersonC.bridgeJSLift(personClosure)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripDirection") +@_cdecl("bjs_roundtripDirection") +public func _bjs_roundtripDirection(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripDirection(_: _BJS_Closure_10TestModule9DirectionO_9DirectionO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripTheme") +@_cdecl("bjs_roundtripTheme") +public func _bjs_roundtripTheme(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripTheme(_: _BJS_Closure_10TestModule5ThemeO_5ThemeO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripHttpStatus") +@_cdecl("bjs_roundtripHttpStatus") +public func _bjs_roundtripHttpStatus(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripHttpStatus(_: _BJS_Closure_10TestModule10HttpStatusO_10HttpStatusO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripAPIResult") +@_cdecl("bjs_roundtripAPIResult") +public func _bjs_roundtripAPIResult(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripAPIResult(_: _BJS_Closure_10TestModule9APIResultO_9APIResultO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalDirection") +@_cdecl("bjs_roundtripOptionalDirection") +public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalDirection(_: _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalTheme") +@_cdecl("bjs_roundtripOptionalTheme") +public func _bjs_roundtripOptionalTheme(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalTheme(_: _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalHttpStatus") +@_cdecl("bjs_roundtripOptionalHttpStatus") +public func _bjs_roundtripOptionalHttpStatus(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalHttpStatus(_: _BJS_Closure_10TestModuleSq10HttpStatusO_Sq10HttpStatusO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalAPIResult") +@_cdecl("bjs_roundtripOptionalAPIResult") +public func _bjs_roundtripOptionalAPIResult(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalAPIResult(_: _BJS_Closure_10TestModuleSq9APIResultO_Sq9APIResultO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripOptionalDirection") +@_cdecl("bjs_roundtripOptionalDirection") +public func _bjs_roundtripOptionalDirection(_ callback: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundtripOptionalDirection(_: _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Person_init") +@_cdecl("bjs_Person_init") +public func _bjs_Person_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Person(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Person_deinit") +@_cdecl("bjs_Person_deinit") +public func _bjs_Person_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Person: ConvertibleToJSValue, _BridgedSwiftHeapObject { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Person_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Person_wrap") +fileprivate func _bjs_Person_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Person_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Person_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Person_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_TestProcessor_init") +@_cdecl("bjs_TestProcessor_init") +public func _bjs_TestProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = TestProcessor(transform: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(transform)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_TestProcessor_deinit") +@_cdecl("bjs_TestProcessor_deinit") +public func _bjs_TestProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension TestProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TestProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_TestProcessor_wrap") +fileprivate func _bjs_TestProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TestProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TestProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestProcessor_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json new file mode 100644 index 000000000..0013c810c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -0,0 +1,94 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "applyInt", + "parameters" : [ + { + "name" : "value", + "type" : { + "int" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSi_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "name" : "makeAdder", + "parameters" : [ + { + "name" : "base", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleSi_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift new file mode 100644 index 000000000..f87c8ecca --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift @@ -0,0 +1,108 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSi_Si") +fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleSi_Si_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleSi_Si") +fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleSi_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleSi_Si(callbackValue, param0Value) + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Int) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int) -> Int) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSi_Si") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleSi_Si") +public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_applyInt") +fileprivate func bjs_applyInt_extern(_ value: Int32, _ transform: Int32) -> Int32 +#else +fileprivate func bjs_applyInt_extern(_ value: Int32, _ transform: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_applyInt(_ value: Int32, _ transform: Int32) -> Int32 { + return bjs_applyInt_extern(value, transform) +} + +func _$applyInt(_ value: Int, _ transform: @escaping (Int) -> Int) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let transform = JSTypedClosure<(Int) -> Int>(transform) + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = withExtendedLifetime((transform)) { + bjs_applyInt(valueValue, transformFuncRef) + } + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_makeAdder") +fileprivate func bjs_makeAdder_extern(_ base: Int32) -> Int32 +#else +fileprivate func bjs_makeAdder_extern(_ base: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_makeAdder(_ base: Int32) -> Int32 { + return bjs_makeAdder_extern(base) +} + +func _$makeAdder(_ base: Int) throws(JSException) -> (Int) -> Int { + let baseValue = base.bridgeJSLowerParameter() + let ret = bjs_makeAdder(baseValue) + if let error = _swift_js_take_exception() { + throw error + } + return _BJS_Closure_10TestModuleSi_Si.bridgeJSLift(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json new file mode 100644 index 000000000..00c6af5cb --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -0,0 +1,589 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Greeter" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "rough", + "rawValue" : "0.1" + }, + { + "associatedValues" : [ + + ], + "name" : "fine", + "rawValue" : "0.001" + } + ], + "emitStyle" : "const", + "name" : "Precision", + "rawType" : "Float", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Precision", + "tsFullPath" : "Precision" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundtrip", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtrip", + "parameters" : [ + { + "label" : "_", + "name" : "session", + "type" : { + "swiftStruct" : { + "_0" : "Person" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Person" + } + } + }, + { + "abiName" : "bjs_roundtripContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripContainer", + "parameters" : [ + { + "label" : "_", + "name" : "container", + "type" : { + "swiftStruct" : { + "_0" : "Container" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Container" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_DataPoint_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + }, + { + "label" : "optCount", + "name" : "optCount", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "label" : "optFlag", + "name" : "optFlag", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "DataPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optCount", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optFlag", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "DataPoint" + }, + { + "methods" : [ + + ], + "name" : "Address", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "street", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "city", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "zipCode", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Address" + }, + { + "methods" : [ + + ], + "name" : "Person", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "age", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "address", + "type" : { + "swiftStruct" : { + "_0" : "Address" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "email", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Person" + }, + { + "methods" : [ + + ], + "name" : "Session", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "owner", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "swiftCallName" : "Session" + }, + { + "methods" : [ + + ], + "name" : "Measurement", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "precision", + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalPrecision", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Measurement" + }, + { + "methods" : [ + { + "abiName" : "bjs_ConfigStruct_static_update", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "update", + "parameters" : [ + { + "label" : "_", + "name" : "timeout", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + }, + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + } + } + ], + "name" : "ConfigStruct", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : true, + "name" : "maxRetries", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "defaultConfig", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "timeout", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "computedSetting", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "ConfigStruct" + }, + { + "methods" : [ + + ], + "name" : "Container", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "object", + "type" : { + "jsObject" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalObject", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Container" + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift similarity index 54% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index af4428979..2adffc113 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -1,67 +1,67 @@ -extension Precision: _BridgedSwiftEnumNoPayload { +extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension DataPoint: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> DataPoint { - let optFlag = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let optCount = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let label = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let y = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let x = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> DataPoint { + let optFlag = Optional.bridgeJSStackPop() + let optCount = Optional.bridgeJSStackPop() + let label = String.bridgeJSStackPop() + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() return DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.x) - _swift_js_push_f64(self.y) - var __bjs_label = self.label - __bjs_label.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + self.label.bridgeJSStackPush() let __bjs_isSome_optCount = self.optCount != nil if let __bjs_unwrapped_optCount = self.optCount { - _swift_js_push_i32(Int32(__bjs_unwrapped_optCount)) + __bjs_unwrapped_optCount.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optCount ? 1 : 0) let __bjs_isSome_optFlag = self.optFlag != nil if let __bjs_unwrapped_optFlag = self.optFlag { - _swift_js_push_i32(__bjs_unwrapped_optFlag ? 1 : 0) + __bjs_unwrapped_optFlag.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optFlag ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_DataPoint())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_DataPoint") -fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_DataPoint_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_DataPoint") -fileprivate func _bjs_struct_lift_DataPoint() -> Int32 +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { + return _bjs_struct_lift_DataPoint_extern() +} @_expose(wasm, "bjs_DataPoint_init") @_cdecl("bjs_DataPoint_init") @@ -75,258 +75,260 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, } extension Address: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Address { - let zipCode = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let city = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let street = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { + let zipCode = Optional.bridgeJSStackPop() + let city = String.bridgeJSStackPop() + let street = String.bridgeJSStackPop() return Address(street: street, city: city, zipCode: zipCode) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_street = self.street - __bjs_street.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_city = self.city - __bjs_city.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.street.bridgeJSStackPush() + self.city.bridgeJSStackPush() let __bjs_isSome_zipCode = self.zipCode != nil if let __bjs_unwrapped_zipCode = self.zipCode { - _swift_js_push_i32(Int32(__bjs_unwrapped_zipCode)) + __bjs_unwrapped_zipCode.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_zipCode ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Address())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Address") -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Address_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Address") -fileprivate func _bjs_struct_lift_Address() -> Int32 +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Address() -> Int32 { +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Address() -> Int32 { + return _bjs_struct_lift_Address_extern() +} extension Person: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Person { - let email = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32()) - let address = Address.bridgeJSLiftParameter() - let age = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Person { + let email = Optional.bridgeJSStackPop() + let address = Address.bridgeJSStackPop() + let age = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return Person(name: name, age: age, address: address, email: email) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.age)) - self.address.bridgeJSLowerReturn() + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.age.bridgeJSStackPush() + self.address.bridgeJSStackPush() let __bjs_isSome_email = self.email != nil if let __bjs_unwrapped_email = self.email { - var __bjs_str_email = __bjs_unwrapped_email - __bjs_str_email.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + __bjs_unwrapped_email.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Person(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Person(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Person())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Person") -fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Person_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Person_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Person(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Person_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Person") -fileprivate func _bjs_struct_lift_Person() -> Int32 +fileprivate func _bjs_struct_lift_Person_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Person() -> Int32 { +fileprivate func _bjs_struct_lift_Person_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Person() -> Int32 { + return _bjs_struct_lift_Person_extern() +} extension Session: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Session { - let owner = Greeter.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Session { + let owner = Greeter.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return Session(id: id, owner: owner) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) - _swift_js_push_pointer(self.owner.bridgeJSLowerReturn()) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.owner.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Session(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Session(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Session())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Session") -fileprivate func _bjs_struct_lower_Session(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Session_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Session(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Session_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Session(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Session_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Session") -fileprivate func _bjs_struct_lift_Session() -> Int32 +fileprivate func _bjs_struct_lift_Session_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Session() -> Int32 { +fileprivate func _bjs_struct_lift_Session_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Session() -> Int32 { + return _bjs_struct_lift_Session_extern() +} extension Measurement: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Measurement { - let optionalPrecision = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f32()) - let precision = Precision.bridgeJSLiftParameter(_swift_js_pop_f32()) - let value = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Measurement { + let optionalPrecision = Optional.bridgeJSStackPop() + let precision = Precision.bridgeJSStackPop() + let value = Double.bridgeJSStackPop() return Measurement(value: value, precision: precision, optionalPrecision: optionalPrecision) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.value) - _swift_js_push_f32(self.precision.bridgeJSLowerParameter()) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.value.bridgeJSStackPush() + self.precision.bridgeJSStackPush() let __bjs_isSome_optionalPrecision = self.optionalPrecision != nil if let __bjs_unwrapped_optionalPrecision = self.optionalPrecision { - _swift_js_push_f32(__bjs_unwrapped_optionalPrecision.bridgeJSLowerParameter()) + __bjs_unwrapped_optionalPrecision.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optionalPrecision ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Measurement(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Measurement(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Measurement())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Measurement") -fileprivate func _bjs_struct_lower_Measurement(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Measurement_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Measurement(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Measurement_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Measurement(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Measurement_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Measurement") -fileprivate func _bjs_struct_lift_Measurement() -> Int32 +fileprivate func _bjs_struct_lift_Measurement_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Measurement() -> Int32 { +fileprivate func _bjs_struct_lift_Measurement_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Measurement() -> Int32 { + return _bjs_struct_lift_Measurement_extern() +} extension ConfigStruct: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> ConfigStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ConfigStruct { return ConfigStruct() } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ConfigStruct())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ConfigStruct") -fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ConfigStruct_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ConfigStruct") -fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { + return _bjs_struct_lift_ConfigStruct_extern() +} @_expose(wasm, "bjs_ConfigStruct_static_maxRetries_get") @_cdecl("bjs_ConfigStruct_static_maxRetries_get") @@ -403,6 +405,58 @@ public func _bjs_ConfigStruct_static_update(_ timeout: Float64) -> Float64 { #endif } +extension Container: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Container { + let optionalObject = Optional.bridgeJSStackPop() + let object = JSObject.bridgeJSStackPop() + return Container(object: object, optionalObject: optionalObject) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.object.bridgeJSStackPush() + let __bjs_isSome_optionalObject = self.optionalObject != nil + if let __bjs_unwrapped_optionalObject = self.optionalObject { + __bjs_unwrapped_optionalObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_optionalObject ? 1 : 0) + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Container(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Container())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Container") +fileprivate func _bjs_struct_lower_Container_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Container_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Container(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Container_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Container") +fileprivate func _bjs_struct_lift_Container_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Container_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Container() -> Int32 { + return _bjs_struct_lift_Container_extern() +} + @_expose(wasm, "bjs_roundtrip") @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { @@ -414,6 +468,17 @@ public func _bjs_roundtrip() -> Void { #endif } +@_expose(wasm, "bjs_roundtripContainer") +@_cdecl("bjs_roundtripContainer") +public func _bjs_roundtripContainer() -> Void { + #if arch(wasm32) + let ret = roundtripContainer(_: Container.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Greeter_init") @_cdecl("bjs_Greeter_init") public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { @@ -475,9 +540,12 @@ extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json new file mode 100644 index 000000000..50af441a9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -0,0 +1,94 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Point", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "Point" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "translate", + "parameters" : [ + { + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "Point" + } + } + }, + { + "name" : "dx", + "type" : { + "int" : { + + } + } + }, + { + "name" : "dy", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Point" + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift new file mode 100644 index 000000000..fe79f786c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -0,0 +1,70 @@ +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_translate") +fileprivate func bjs_translate_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 +#else +fileprivate func bjs_translate_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_translate(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { + return bjs_translate_extern(point, dx, dy) +} + +func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { + let pointObjectId = point.bridgeJSLowerParameter() + let dxValue = dx.bridgeJSLowerParameter() + let dyValue = dy.bridgeJSLowerParameter() + let ret = bjs_translate(pointObjectId, dxValue, dyValue) + if let error = _swift_js_take_exception() { + throw error + } + return Point.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json new file mode 100644 index 000000000..02796479f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json @@ -0,0 +1,37 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_throwsSomething", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsSomething", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Throws.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Throws.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json new file mode 100644 index 000000000..1eb9e47ec --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json @@ -0,0 +1,416 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_takeUnsafeRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeUnsafeRawPointer", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_takeUnsafeMutableRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeUnsafeMutableRawPointer", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_takeOpaquePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeOpaquePointer", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_takeUnsafePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeUnsafePointer", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_takeUnsafeMutablePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeUnsafeMutablePointer", + "parameters" : [ + { + "label" : "_", + "name" : "p", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_returnUnsafeRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "returnUnsafeRawPointer", + "parameters" : [ + + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "abiName" : "bjs_returnUnsafeMutableRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "returnUnsafeMutableRawPointer", + "parameters" : [ + + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "abiName" : "bjs_returnOpaquePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "returnOpaquePointer", + "parameters" : [ + + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "abiName" : "bjs_returnUnsafePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "returnUnsafePointer", + "parameters" : [ + + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "abiName" : "bjs_returnUnsafeMutablePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "returnUnsafeMutablePointer", + "parameters" : [ + + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "abiName" : "bjs_roundTripPointerFields", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripPointerFields", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "swiftStruct" : { + "_0" : "PointerFields" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PointerFields" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_PointerFields_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "raw", + "name" : "raw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "label" : "mutRaw", + "name" : "mutRaw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "label" : "opaque", + "name" : "opaque", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "label" : "ptr", + "name" : "ptr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "label" : "mutPtr", + "name" : "mutPtr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "PointerFields", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "raw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "mutRaw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "opaque", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "ptr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "mutPtr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "swiftCallName" : "PointerFields" + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift similarity index 78% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.swift rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift index 4c368908b..b97729084 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift @@ -1,53 +1,56 @@ extension PointerFields: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> PointerFields { - let mutPtr = UnsafeMutablePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let ptr = UnsafePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let opaque = OpaquePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let mutRaw = UnsafeMutableRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let raw = UnsafeRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PointerFields { + let mutPtr = UnsafeMutablePointer.bridgeJSStackPop() + let ptr = UnsafePointer.bridgeJSStackPop() + let opaque = OpaquePointer.bridgeJSStackPop() + let mutRaw = UnsafeMutableRawPointer.bridgeJSStackPop() + let raw = UnsafeRawPointer.bridgeJSStackPop() return PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_pointer(self.raw.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.mutRaw.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.opaque.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.ptr.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.mutPtr.bridgeJSLowerReturn()) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.raw.bridgeJSStackPush() + self.mutRaw.bridgeJSStackPush() + self.opaque.bridgeJSStackPush() + self.ptr.bridgeJSStackPush() + self.mutPtr.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PointerFields())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PointerFields") -fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PointerFields_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PointerFields") -fileprivate func _bjs_struct_lift_PointerFields() -> Int32 +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { + return _bjs_struct_lift_PointerFields_extern() +} @_expose(wasm, "bjs_PointerFields_init") @_cdecl("bjs_PointerFields_init") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json new file mode 100644 index 000000000..14da32841 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json @@ -0,0 +1,59 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_check", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "check", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "name" : "check", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule" +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.swift new file mode 100644 index 000000000..777cd1c3a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.swift @@ -0,0 +1,28 @@ +@_expose(wasm, "bjs_check") +@_cdecl("bjs_check") +public func _bjs_check() -> Void { + #if arch(wasm32) + check() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_check") +fileprivate func bjs_check_extern() -> Void +#else +fileprivate func bjs_check_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_check() -> Void { + return bjs_check_extern() +} + +func _$check() throws(JSException) -> Void { + bjs_check() + if let error = _swift_js_take_exception() { + throw error + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayParameter.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayParameter.Import.d.ts deleted file mode 100644 index 2a6771ca7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayParameter.Import.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - checkArray(a: any): void; - checkArrayWithLength(a: any, b: number): void; - checkArray(a: any): void; -} -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/ArrayParameter.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayParameter.Import.js deleted file mode 100644 index 8add18b9f..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayParameter.Import.js +++ /dev/null @@ -1,245 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_checkArray"] = function bjs_checkArray(a) { - try { - imports.checkArray(swift.memory.getObject(a)); - } catch (error) { - setException(error); - } - } - TestModule["bjs_checkArrayWithLength"] = function bjs_checkArrayWithLength(a, b) { - try { - imports.checkArrayWithLength(swift.memory.getObject(a), b); - } catch (error) { - setException(error); - } - } - TestModule["bjs_checkArray"] = function bjs_checkArray(a) { - try { - imports.checkArray(swift.memory.getObject(a)); - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts similarity index 84% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts index 988626f3e..8dc76156b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts @@ -62,10 +62,20 @@ export type Exports = { processNestedPointArray(points: Point[][]): Point[][]; processItemArray(items: Item[]): Item[]; processNestedItemArray(items: Item[][]): Item[][]; + processJSObjectArray(objects: any[]): any[]; + processOptionalJSObjectArray(objects: (any | null)[]): (any | null)[]; + processNestedJSObjectArray(objects: any[][]): any[][]; Direction: DirectionObject Status: StatusObject } export type Imports = { + checkArray(a: any): void; + checkArrayWithLength(a: any, b: number): void; + importProcessNumbers(values: number[]): void; + importGetNumbers(): number[]; + importTransformNumbers(values: number[]): number[]; + importProcessStrings(values: string[]): string[]; + importProcessBooleans(values: boolean[]): boolean[]; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js similarity index 59% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 7388f4150..b206b9a9f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -31,36 +31,27 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; - const __bjs_createPointHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamF64s.push(value.x); - tmpParamF64s.push(value.y); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const f64 = tmpRetF64s.pop(); - const f641 = tmpRetF64s.pop(); - return { x: f641, y: f64 }; - } - }); - }; + const __bjs_createPointHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.x); + f64Stack.push(value.y); + }, + lift: () => { + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + return { x: f641, y: f64 }; + } + }); return { /** @@ -69,12 +60,14 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); tmpRetString = textDecoder.decode(bytes); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -96,57 +89,40 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_struct_lower_Point"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Point.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Point.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Point.lift(); return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { @@ -239,14 +215,112 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Item_wrap"] = function(pointer) { - const obj = Item.__construct(pointer); + const obj = _exports['Item'].__construct(pointer); return swift.memory.retain(obj); }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_checkArray"] = function bjs_checkArray(a) { + try { + imports.checkArray(swift.memory.getObject(a)); + } catch (error) { + setException(error); + } + } + TestModule["bjs_checkArrayWithLength"] = function bjs_checkArrayWithLength(a, b) { + try { + imports.checkArrayWithLength(swift.memory.getObject(a), b); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importProcessNumbers"] = function bjs_importProcessNumbers() { + try { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const f64 = f64Stack.pop(); + arrayResult.push(f64); + } + arrayResult.reverse(); + imports.importProcessNumbers(arrayResult); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGetNumbers"] = function bjs_importGetNumbers() { + try { + let ret = imports.importGetNumbers(); + for (const elem of ret) { + f64Stack.push(elem); + } + i32Stack.push(ret.length); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importTransformNumbers"] = function bjs_importTransformNumbers() { + try { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const f64 = f64Stack.pop(); + arrayResult.push(f64); + } + arrayResult.reverse(); + let ret = imports.importTransformNumbers(arrayResult); + for (const elem of ret) { + f64Stack.push(elem); + } + i32Stack.push(ret.length); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importProcessStrings"] = function bjs_importProcessStrings() { + try { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const string = strStack.pop(); + arrayResult.push(string); + } + arrayResult.reverse(); + let ret = imports.importProcessStrings(arrayResult); + for (const elem of ret) { + const bytes = textEncoder.encode(elem); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + } + i32Stack.push(ret.length); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importProcessBooleans"] = function bjs_importProcessBooleans() { + try { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const bool = i32Stack.pop() !== 0; + arrayResult.push(bool); + } + arrayResult.reverse(); + let ret = imports.importProcessBooleans(arrayResult); + for (const elem of ret) { + i32Stack.push(elem ? 1 : 0); + } + i32Stack.push(ret.length); + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; @@ -259,326 +333,295 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Item extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Item_deinit, Item.prototype); } - + } - const PointHelpers = __bjs_createPointHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + const PointHelpers = __bjs_createPointHelpers(); structHelpers.Point = PointHelpers; - + const exports = { Item, processIntArray: function bjs_processIntArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processIntArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); arrayResult.push(int); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processStringArray: function bjs_processStringArray(values) { - const arrayCleanups = []; for (const elem of values) { const bytes = textEncoder.encode(elem); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - arrayCleanups.push(() => { - swift.memory.release(id); - }); + i32Stack.push(bytes.length); + i32Stack.push(id); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processStringArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); arrayResult.push(string); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processDoubleArray: function bjs_processDoubleArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamF64s.push(elem); + f64Stack.push(elem); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processDoubleArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const f64 = tmpRetF64s.pop(); + const f64 = f64Stack.pop(); arrayResult.push(f64); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processBoolArray: function bjs_processBoolArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push(elem ? 1 : 0); + i32Stack.push(elem ? 1 : 0); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processBoolArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const bool = tmpRetInts.pop() !== 0; + const bool = i32Stack.pop() !== 0; arrayResult.push(bool); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processPointArray: function bjs_processPointArray(points) { - const arrayCleanups = []; for (const elem of points) { - const { cleanup: cleanup } = structHelpers.Point.lower(elem); - arrayCleanups.push(() => { - if (cleanup) { cleanup(); } - }); + structHelpers.Point.lower(elem); } - tmpParamInts.push(points.length); + i32Stack.push(points.length); instance.exports.bjs_processPointArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const struct = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const struct = structHelpers.Point.lift(); arrayResult.push(struct); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processDirectionArray: function bjs_processDirectionArray(directions) { - const arrayCleanups = []; for (const elem of directions) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(directions.length); + i32Stack.push(directions.length); instance.exports.bjs_processDirectionArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const caseId = tmpRetInts.pop(); + const caseId = i32Stack.pop(); arrayResult.push(caseId); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processStatusArray: function bjs_processStatusArray(statuses) { - const arrayCleanups = []; for (const elem of statuses) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(statuses.length); + i32Stack.push(statuses.length); instance.exports.bjs_processStatusArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const rawValue = tmpRetInts.pop(); + const rawValue = i32Stack.pop(); arrayResult.push(rawValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, sumIntArray: function bjs_sumIntArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); const ret = instance.exports.bjs_sumIntArray(); - for (const cleanup of arrayCleanups) { cleanup(); } return ret; }, findFirstPoint: function bjs_findFirstPoint(points, matching) { - const arrayCleanups = []; for (const elem of points) { - const { cleanup: cleanup } = structHelpers.Point.lower(elem); - arrayCleanups.push(() => { - if (cleanup) { cleanup(); } - }); + structHelpers.Point.lower(elem); } - tmpParamInts.push(points.length); + i32Stack.push(points.length); const matchingBytes = textEncoder.encode(matching); const matchingId = swift.memory.retain(matchingBytes); instance.exports.bjs_findFirstPoint(matchingId, matchingBytes.length); - const structValue = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - for (const cleanup of arrayCleanups) { cleanup(); } - swift.memory.release(matchingId); + const structValue = structHelpers.Point.lift(); return structValue; }, processUnsafeRawPointerArray: function bjs_processUnsafeRawPointerArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamPointers.push((elem | 0)); + ptrStack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processUnsafeRawPointerArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const pointer = tmpRetPointers.pop(); + const pointer = ptrStack.pop(); arrayResult.push(pointer); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processUnsafeMutableRawPointerArray: function bjs_processUnsafeMutableRawPointerArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamPointers.push((elem | 0)); + ptrStack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processUnsafeMutableRawPointerArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const pointer = tmpRetPointers.pop(); + const pointer = ptrStack.pop(); arrayResult.push(pointer); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOpaquePointerArray: function bjs_processOpaquePointerArray(values) { - const arrayCleanups = []; for (const elem of values) { - tmpParamPointers.push((elem | 0)); + ptrStack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processOpaquePointerArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const pointer = tmpRetPointers.pop(); + const pointer = ptrStack.pop(); arrayResult.push(pointer); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOptionalIntArray: function bjs_processOptionalIntArray(values) { - const arrayCleanups = []; for (const elem of values) { const isSome = elem != null ? 1 : 0; if (isSome) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } else { - tmpParamInts.push(0); + i32Stack.push(0); } - tmpParamInts.push(isSome); + i32Stack.push(isSome); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processOptionalIntArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const isSome1 = tmpRetInts.pop(); + const isSome1 = i32Stack.pop(); let optValue; if (isSome1 === 0) { optValue = null; } else { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); optValue = int; } arrayResult.push(optValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOptionalStringArray: function bjs_processOptionalStringArray(values) { - const arrayCleanups = []; for (const elem of values) { const isSome = elem != null ? 1 : 0; if (isSome) { const bytes = textEncoder.encode(elem); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - arrayCleanups.push(() => { swift.memory.release(id); }); + i32Stack.push(bytes.length); + i32Stack.push(id); } else { - tmpParamInts.push(0); - tmpParamInts.push(0); + i32Stack.push(0); + i32Stack.push(0); } - tmpParamInts.push(isSome); + i32Stack.push(isSome); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processOptionalStringArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const isSome1 = tmpRetInts.pop(); + const isSome1 = i32Stack.pop(); let optValue; if (isSome1 === 0) { optValue = null; } else { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); optValue = string; } arrayResult.push(optValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOptionalArray: function bjs_processOptionalArray(values) { const isSome = values != null; - const valuesCleanups = []; if (isSome) { - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(values.length); - valuesCleanups.push(() => { for (const cleanup of arrayCleanups) { cleanup(); } }); + i32Stack.push(values.length); } - instance.exports.bjs_processOptionalArray(+isSome); - const isSome1 = tmpRetInts.pop(); + i32Stack.push(+isSome); + instance.exports.bjs_processOptionalArray(); + const isSome1 = i32Stack.pop(); let optResult; if (isSome1) { - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); arrayResult.push(int); } arrayResult.reverse(); @@ -586,245 +629,280 @@ export async function createInstantiator(options, swift) { } else { optResult = null; } - for (const cleanup of valuesCleanups) { cleanup(); } return optResult; }, processOptionalPointArray: function bjs_processOptionalPointArray(points) { - const arrayCleanups = []; for (const elem of points) { const isSome = elem != null ? 1 : 0; if (isSome) { - const { cleanup: cleanup } = structHelpers.Point.lower(elem); - arrayCleanups.push(() => { if (cleanup) { cleanup(); } }); - } else { + structHelpers.Point.lower(elem); } - tmpParamInts.push(isSome); + i32Stack.push(isSome); } - tmpParamInts.push(points.length); + i32Stack.push(points.length); instance.exports.bjs_processOptionalPointArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const isSome1 = tmpRetInts.pop(); + const isSome1 = i32Stack.pop(); let optValue; if (isSome1 === 0) { optValue = null; } else { - const struct = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const struct = structHelpers.Point.lift(); optValue = struct; } arrayResult.push(optValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOptionalDirectionArray: function bjs_processOptionalDirectionArray(directions) { - const arrayCleanups = []; for (const elem of directions) { const isSome = elem != null ? 1 : 0; if (isSome) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } else { - tmpParamInts.push(0); + i32Stack.push(0); } - tmpParamInts.push(isSome); + i32Stack.push(isSome); } - tmpParamInts.push(directions.length); + i32Stack.push(directions.length); instance.exports.bjs_processOptionalDirectionArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const isSome1 = tmpRetInts.pop(); + const isSome1 = i32Stack.pop(); let optValue; if (isSome1 === 0) { optValue = null; } else { - const caseId = tmpRetInts.pop(); + const caseId = i32Stack.pop(); optValue = caseId; } arrayResult.push(optValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processOptionalStatusArray: function bjs_processOptionalStatusArray(statuses) { - const arrayCleanups = []; for (const elem of statuses) { const isSome = elem != null ? 1 : 0; if (isSome) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } else { - tmpParamInts.push(0); + i32Stack.push(0); } - tmpParamInts.push(isSome); + i32Stack.push(isSome); } - tmpParamInts.push(statuses.length); + i32Stack.push(statuses.length); instance.exports.bjs_processOptionalStatusArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const isSome1 = tmpRetInts.pop(); + const isSome1 = i32Stack.pop(); let optValue; if (isSome1 === 0) { optValue = null; } else { - const rawValue = tmpRetInts.pop(); + const rawValue = i32Stack.pop(); optValue = rawValue; } arrayResult.push(optValue); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processNestedIntArray: function bjs_processNestedIntArray(values) { - const arrayCleanups = []; for (const elem of values) { - const arrayCleanups1 = []; for (const elem1 of elem) { - tmpParamInts.push((elem1 | 0)); + i32Stack.push((elem1 | 0)); } - tmpParamInts.push(elem.length); - arrayCleanups.push(() => { - for (const cleanup of arrayCleanups1) { cleanup(); } - }); + i32Stack.push(elem.length); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processNestedIntArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = tmpRetInts.pop(); + const arrayLen1 = i32Stack.pop(); const arrayResult1 = []; for (let i1 = 0; i1 < arrayLen1; i1++) { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); arrayResult1.push(int); } arrayResult1.reverse(); arrayResult.push(arrayResult1); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processNestedStringArray: function bjs_processNestedStringArray(values) { - const arrayCleanups = []; for (const elem of values) { - const arrayCleanups1 = []; for (const elem1 of elem) { const bytes = textEncoder.encode(elem1); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - arrayCleanups1.push(() => { - swift.memory.release(id); - }); + i32Stack.push(bytes.length); + i32Stack.push(id); } - tmpParamInts.push(elem.length); - arrayCleanups.push(() => { - for (const cleanup of arrayCleanups1) { cleanup(); } - }); + i32Stack.push(elem.length); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_processNestedStringArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = tmpRetInts.pop(); + const arrayLen1 = i32Stack.pop(); const arrayResult1 = []; for (let i1 = 0; i1 < arrayLen1; i1++) { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); arrayResult1.push(string); } arrayResult1.reverse(); arrayResult.push(arrayResult1); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processNestedPointArray: function bjs_processNestedPointArray(points) { - const arrayCleanups = []; for (const elem of points) { - const arrayCleanups1 = []; for (const elem1 of elem) { - const { cleanup: cleanup } = structHelpers.Point.lower(elem1); - arrayCleanups1.push(() => { - if (cleanup) { cleanup(); } - }); + structHelpers.Point.lower(elem1); } - tmpParamInts.push(elem.length); - arrayCleanups.push(() => { - for (const cleanup of arrayCleanups1) { cleanup(); } - }); + i32Stack.push(elem.length); } - tmpParamInts.push(points.length); + i32Stack.push(points.length); instance.exports.bjs_processNestedPointArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = tmpRetInts.pop(); + const arrayLen1 = i32Stack.pop(); const arrayResult1 = []; for (let i1 = 0; i1 < arrayLen1; i1++) { - const struct = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const struct = structHelpers.Point.lift(); arrayResult1.push(struct); } arrayResult1.reverse(); arrayResult.push(arrayResult1); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processItemArray: function bjs_processItemArray(items) { - const arrayCleanups = []; for (const elem of items) { - tmpParamPointers.push(elem.pointer); + ptrStack.push(elem.pointer); } - tmpParamInts.push(items.length); + i32Stack.push(items.length); instance.exports.bjs_processItemArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const ptr = tmpRetPointers.pop(); - const obj = Item.__construct(ptr); + const ptr = ptrStack.pop(); + const obj = _exports['Item'].__construct(ptr); arrayResult.push(obj); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, processNestedItemArray: function bjs_processNestedItemArray(items) { - const arrayCleanups = []; for (const elem of items) { - const arrayCleanups1 = []; for (const elem1 of elem) { - tmpParamPointers.push(elem1.pointer); + ptrStack.push(elem1.pointer); } - tmpParamInts.push(elem.length); - arrayCleanups.push(() => { - for (const cleanup of arrayCleanups1) { cleanup(); } - }); + i32Stack.push(elem.length); } - tmpParamInts.push(items.length); + i32Stack.push(items.length); instance.exports.bjs_processNestedItemArray(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const arrayLen1 = i32Stack.pop(); + const arrayResult1 = []; + for (let i1 = 0; i1 < arrayLen1; i1++) { + const ptr = ptrStack.pop(); + const obj = _exports['Item'].__construct(ptr); + arrayResult1.push(obj); + } + arrayResult1.reverse(); + arrayResult.push(arrayResult1); + } + arrayResult.reverse(); + return arrayResult; + }, + processJSObjectArray: function bjs_processJSObjectArray(objects) { + for (const elem of objects) { + const objId = swift.memory.retain(elem); + i32Stack.push(objId); + } + i32Stack.push(objects.length); + instance.exports.bjs_processJSObjectArray(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const objId1 = i32Stack.pop(); + const obj = swift.memory.getObject(objId1); + swift.memory.release(objId1); + arrayResult.push(obj); + } + arrayResult.reverse(); + return arrayResult; + }, + processOptionalJSObjectArray: function bjs_processOptionalJSObjectArray(objects) { + for (const elem of objects) { + const isSome = elem != null ? 1 : 0; + if (isSome) { + const objId = swift.memory.retain(elem); + i32Stack.push(objId); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome); + } + i32Stack.push(objects.length); + instance.exports.bjs_processOptionalJSObjectArray(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const isSome1 = i32Stack.pop(); + let optValue; + if (isSome1 === 0) { + optValue = null; + } else { + const objId1 = i32Stack.pop(); + const obj = swift.memory.getObject(objId1); + swift.memory.release(objId1); + optValue = obj; + } + arrayResult.push(optValue); + } + arrayResult.reverse(); + return arrayResult; + }, + processNestedJSObjectArray: function bjs_processNestedJSObjectArray(objects) { + for (const elem of objects) { + for (const elem1 of elem) { + const objId = swift.memory.retain(elem1); + i32Stack.push(objId); + } + i32Stack.push(elem.length); + } + i32Stack.push(objects.length); + instance.exports.bjs_processNestedJSObjectArray(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = tmpRetInts.pop(); + const arrayLen1 = i32Stack.pop(); const arrayResult1 = []; for (let i1 = 0; i1 < arrayLen1; i1++) { - const ptr = tmpRetPointers.pop(); - const obj = Item.__construct(ptr); + const objId1 = i32Stack.pop(); + const obj = swift.memory.getObject(objId1); + swift.memory.release(objId1); arrayResult1.push(obj); } arrayResult1.reverse(); arrayResult.push(arrayResult1); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, Direction: DirectionValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Import.d.ts deleted file mode 100644 index dea0bd186..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Import.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - asyncReturnVoid(): JSPromise; - asyncRoundTripInt(v: number): JSPromise; - asyncRoundTripString(v: string): JSPromise; - asyncRoundTripBool(v: boolean): JSPromise; - asyncRoundTripFloat(v: number): JSPromise; - asyncRoundTripDouble(v: number): JSPromise; - asyncRoundTripJSObject(v: any): JSPromise; -} -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/Async.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Import.js deleted file mode 100644 index 981cecbe5..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Import.js +++ /dev/null @@ -1,289 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_asyncReturnVoid"] = function bjs_asyncReturnVoid() { - try { - let ret = imports.asyncReturnVoid(); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripInt"] = function bjs_asyncRoundTripInt(v) { - try { - let ret = imports.asyncRoundTripInt(v); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripString"] = function bjs_asyncRoundTripString(v) { - try { - const vObject = swift.memory.getObject(v); - swift.memory.release(v); - let ret = imports.asyncRoundTripString(vObject); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripBool"] = function bjs_asyncRoundTripBool(v) { - try { - let ret = imports.asyncRoundTripBool(v !== 0); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripFloat"] = function bjs_asyncRoundTripFloat(v) { - try { - let ret = imports.asyncRoundTripFloat(v); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripDouble"] = function bjs_asyncRoundTripDouble(v) { - try { - let ret = imports.asyncRoundTripDouble(v); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_asyncRoundTripJSObject"] = function bjs_asyncRoundTripJSObject(v) { - try { - let ret = imports.asyncRoundTripJSObject(swift.memory.getObject(v)); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js similarity index 87% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 4015b6261..6e7e810ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,6 +183,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { instance = i; @@ -232,7 +215,6 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_asyncRoundTripString(vId, vBytes.length); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); - swift.memory.release(vId); return ret1; }, asyncRoundTripBool: function bjs_asyncRoundTripBool(v) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js similarity index 67% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 978272568..a865882ef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -24,69 +24,52 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; - const __bjs_createConfigHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - const bytes = textEncoder.encode(value.name); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - tmpParamInts.push((value.value | 0)); - tmpParamInts.push(value.enabled ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - }; - return { cleanup }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const bool = tmpRetInts.pop() !== 0; - const int = tmpRetInts.pop(); - const string = tmpRetStrings.pop(); - return { name: string, value: int, enabled: bool }; - } - }); - }; - const __bjs_createMathOperationsHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamF64s.push(value.baseValue); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const f64 = tmpRetF64s.pop(); - const instance1 = { baseValue: f64 }; - instance1.add = function(a, b = 10.0) { - const { cleanup: structCleanup } = structHelpers.MathOperations.lower(this); - const ret = instance.exports.bjs_MathOperations_add(a, b); - if (structCleanup) { structCleanup(); } - return ret; - }.bind(instance1); - instance1.multiply = function(a, b) { - const { cleanup: structCleanup } = structHelpers.MathOperations.lower(this); - const ret = instance.exports.bjs_MathOperations_multiply(a, b); - if (structCleanup) { structCleanup(); } - return ret; - }.bind(instance1); - return instance1; - } - }); - }; + const __bjs_createConfigHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.name); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value.value | 0)); + i32Stack.push(value.enabled ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + const int = i32Stack.pop(); + const string = strStack.pop(); + return { name: string, value: int, enabled: bool }; + } + }); + const __bjs_createMathOperationsHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.baseValue); + }, + lift: () => { + const f64 = f64Stack.pop(); + const instance1 = { baseValue: f64 }; + instance1.add = function(a, b = 10.0) { + structHelpers.MathOperations.lower(this); + const ret = instance.exports.bjs_MathOperations_add(a, b); + return ret; + }.bind(instance1); + instance1.multiply = function(a, b) { + structHelpers.MathOperations.lower(this); + const ret = instance.exports.bjs_MathOperations_multiply(a, b); + return ret; + }.bind(instance1); + return instance1; + } + }); return { /** @@ -101,6 +84,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -122,68 +106,47 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_struct_lower_Config"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Config.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Config.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Config"] = function() { - const value = structHelpers.Config.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Config.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_MathOperations"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.MathOperations.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.MathOperations.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_MathOperations"] = function() { - const value = structHelpers.MathOperations.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.MathOperations.lift(); return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { @@ -276,20 +239,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_ConstructorDefaults_wrap"] = function(pointer) { - const obj = ConstructorDefaults.__construct(pointer); + const obj = _exports['ConstructorDefaults'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_DefaultGreeter_wrap"] = function(pointer) { - const obj = DefaultGreeter.__construct(pointer); + const obj = _exports['DefaultGreeter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_EmptyGreeter_wrap"] = function(pointer) { - const obj = EmptyGreeter.__construct(pointer); + const obj = _exports['EmptyGreeter'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -304,35 +268,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class DefaultGreeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DefaultGreeter_deinit, DefaultGreeter.prototype); } - + constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const ret = instance.exports.bjs_DefaultGreeter_init(nameId, nameBytes.length); - swift.memory.release(nameId); return DefaultGreeter.__construct(ret); } get name() { @@ -345,14 +318,13 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_DefaultGreeter_name_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } } class EmptyGreeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_EmptyGreeter_deinit, EmptyGreeter.prototype); } - + constructor() { const ret = instance.exports.bjs_EmptyGreeter_init(); return EmptyGreeter.__construct(ret); @@ -362,21 +334,22 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ConstructorDefaults_deinit, ConstructorDefaults.prototype); } - + constructor(name = "Default", count = 42, enabled = true, status = StatusValues.Active, tag = null) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const isSome = tag != null; - let tagId, tagBytes; + let result, result1; if (isSome) { - tagBytes = textEncoder.encode(tag); - tagId = swift.memory.retain(tagBytes); - } - const ret = instance.exports.bjs_ConstructorDefaults_init(nameId, nameBytes.length, count, enabled, status, +isSome, isSome ? tagId : 0, isSome ? tagBytes.length : 0); - swift.memory.release(nameId); - if (tagId != undefined) { - swift.memory.release(tagId); + const tagBytes = textEncoder.encode(tag); + const tagId = swift.memory.retain(tagBytes); + result = tagId; + result1 = tagBytes.length; + } else { + result = 0; + result1 = 0; } + const ret = instance.exports.bjs_ConstructorDefaults_init(nameId, nameBytes.length, count, enabled, status, +isSome, result, result1); return ConstructorDefaults.__construct(ret); } get name() { @@ -389,7 +362,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_ConstructorDefaults_name_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } get count() { const ret = instance.exports.bjs_ConstructorDefaults_count_get(this.pointer); @@ -420,23 +392,25 @@ export async function createInstantiator(options, swift) { } set tag(value) { const isSome = value != null; - let valueId, valueBytes; + let result, result1; if (isSome) { - valueBytes = textEncoder.encode(value); - valueId = swift.memory.retain(valueBytes); - } - instance.exports.bjs_ConstructorDefaults_tag_set(this.pointer, +isSome, isSome ? valueId : 0, isSome ? valueBytes.length : 0); - if (valueId != undefined) { - swift.memory.release(valueId); + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + result = valueId; + result1 = valueBytes.length; + } else { + result = 0; + result1 = 0; } + instance.exports.bjs_ConstructorDefaults_tag_set(this.pointer, +isSome, result, result1); } } - const ConfigHelpers = __bjs_createConfigHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + const ConfigHelpers = __bjs_createConfigHelpers(); structHelpers.Config = ConfigHelpers; - - const MathOperationsHelpers = __bjs_createMathOperationsHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const MathOperationsHelpers = __bjs_createMathOperationsHelpers(); structHelpers.MathOperations = MathOperationsHelpers; - + const exports = { DefaultGreeter, EmptyGreeter, @@ -447,7 +421,6 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_testStringDefault(messageId, messageBytes.length); const ret = tmpRetString; tmpRetString = undefined; - swift.memory.release(messageId); return ret; }, testNegativeIntDefault: function bjs_testNegativeIntDefault(value = -42) { @@ -468,32 +441,36 @@ export async function createInstantiator(options, swift) { }, testOptionalDefault: function bjs_testOptionalDefault(name = null) { const isSome = name != null; - let nameId, nameBytes; + let result, result1; if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; } - instance.exports.bjs_testOptionalDefault(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); + instance.exports.bjs_testOptionalDefault(+isSome, result, result1); const optResult = tmpRetString; tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } return optResult; }, testOptionalStringDefault: function bjs_testOptionalStringDefault(greeting = "Hi") { const isSome = greeting != null; - let greetingId, greetingBytes; + let result, result1; if (isSome) { - greetingBytes = textEncoder.encode(greeting); - greetingId = swift.memory.retain(greetingBytes); + const greetingBytes = textEncoder.encode(greeting); + const greetingId = swift.memory.retain(greetingBytes); + result = greetingId; + result1 = greetingBytes.length; + } else { + result = 0; + result1 = 0; } - instance.exports.bjs_testOptionalStringDefault(+isSome, isSome ? greetingId : 0, isSome ? greetingBytes.length : 0); + instance.exports.bjs_testOptionalStringDefault(+isSome, result, result1); const optResult = tmpRetString; tmpRetString = undefined; - if (greetingId != undefined) { - swift.memory.release(greetingId); - } return optResult; }, testMultipleDefaults: function bjs_testMultipleDefaults(title = "Default Title", count = 10, enabled = false) { @@ -502,7 +479,6 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_testMultipleDefaults(titleId, titleBytes.length, count, enabled); const ret = tmpRetString; tmpRetString = undefined; - swift.memory.release(titleId); return ret; }, testEnumDefault: function bjs_testEnumDefault(status = StatusValues.Active) { @@ -519,151 +495,121 @@ export async function createInstantiator(options, swift) { }, testOptionalStructDefault: function bjs_testOptionalStructDefault(point = null) { const isSome = point != null; - let pointCleanup; if (isSome) { - const structResult = structHelpers.Config.lower(point); - pointCleanup = structResult.cleanup; + structHelpers.Config.lower(point); } - instance.exports.bjs_testOptionalStructDefault(+isSome); - const isSome1 = tmpRetInts.pop(); - let optResult; - if (isSome1) { - optResult = structHelpers.Config.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - } else { - optResult = null; - } - if (pointCleanup) { pointCleanup(); } + i32Stack.push(+isSome); + instance.exports.bjs_testOptionalStructDefault(); + const isSome1 = i32Stack.pop(); + const optResult = isSome1 ? structHelpers.Config.lift() : null; return optResult; }, testOptionalStructWithValueDefault: function bjs_testOptionalStructWithValueDefault(point = { name: "default", value: 42, enabled: true }) { const isSome = point != null; - let pointCleanup; if (isSome) { - const structResult = structHelpers.Config.lower(point); - pointCleanup = structResult.cleanup; - } - instance.exports.bjs_testOptionalStructWithValueDefault(+isSome); - const isSome1 = tmpRetInts.pop(); - let optResult; - if (isSome1) { - optResult = structHelpers.Config.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - } else { - optResult = null; + structHelpers.Config.lower(point); } - if (pointCleanup) { pointCleanup(); } + i32Stack.push(+isSome); + instance.exports.bjs_testOptionalStructWithValueDefault(); + const isSome1 = i32Stack.pop(); + const optResult = isSome1 ? structHelpers.Config.lift() : null; return optResult; }, testIntArrayDefault: function bjs_testIntArrayDefault(values = [1, 2, 3]) { - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_testIntArrayDefault(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); arrayResult.push(int); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, testStringArrayDefault: function bjs_testStringArrayDefault(names = ["a", "b", "c"]) { - const arrayCleanups = []; for (const elem of names) { const bytes = textEncoder.encode(elem); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - arrayCleanups.push(() => { - swift.memory.release(id); - }); + i32Stack.push(bytes.length); + i32Stack.push(id); } - tmpParamInts.push(names.length); + i32Stack.push(names.length); instance.exports.bjs_testStringArrayDefault(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); arrayResult.push(string); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, testDoubleArrayDefault: function bjs_testDoubleArrayDefault(values = [1.5, 2.5, 3.5]) { - const arrayCleanups = []; for (const elem of values) { - tmpParamF64s.push(elem); + f64Stack.push(elem); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_testDoubleArrayDefault(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const f64 = tmpRetF64s.pop(); + const f64 = f64Stack.pop(); arrayResult.push(f64); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, testBoolArrayDefault: function bjs_testBoolArrayDefault(flags = [true, false, true]) { - const arrayCleanups = []; for (const elem of flags) { - tmpParamInts.push(elem ? 1 : 0); + i32Stack.push(elem ? 1 : 0); } - tmpParamInts.push(flags.length); + i32Stack.push(flags.length); instance.exports.bjs_testBoolArrayDefault(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const bool = tmpRetInts.pop() !== 0; + const bool = i32Stack.pop() !== 0; arrayResult.push(bool); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, testEmptyArrayDefault: function bjs_testEmptyArrayDefault(items = []) { - const arrayCleanups = []; for (const elem of items) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(items.length); + i32Stack.push(items.length); instance.exports.bjs_testEmptyArrayDefault(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); arrayResult.push(int); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, testMixedWithArrayDefault: function bjs_testMixedWithArrayDefault(name = "test", values = [10, 20, 30], enabled = true) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); - const arrayCleanups = []; for (const elem of values) { - tmpParamInts.push((elem | 0)); + i32Stack.push((elem | 0)); } - tmpParamInts.push(values.length); + i32Stack.push(values.length); instance.exports.bjs_testMixedWithArrayDefault(nameId, nameBytes.length, enabled); const ret = tmpRetString; tmpRetString = undefined; - swift.memory.release(nameId); - for (const cleanup of arrayCleanups) { cleanup(); } return ret; }, Status: StatusValues, MathOperations: { init: function(baseValue = 0.0) { instance.exports.bjs_MathOperations_init(baseValue); - const structValue = structHelpers.MathOperations.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const structValue = structHelpers.MathOperations.lift(); return structValue; }, subtract: function(a, b) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts new file mode 100644 index 000000000..dadcc74ba --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts @@ -0,0 +1,34 @@ +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Box extends SwiftHeapObject { +} +export type Exports = { + Box: { + } + mirrorDictionary(values: Record): Record; + optionalDictionary(values: Record | null): Record | null; + nestedDictionary(values: Record): Record; + boxDictionary(boxes: Record): Record; + optionalBoxDictionary(boxes: Record): Record; +} +export type Imports = { + importMirrorDictionary(values: Record): Record; +} +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/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js new file mode 100644 index 000000000..efbd9b09e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -0,0 +1,418 @@ +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); + bjs["swift_js_return_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + return swift.memory.retain(textDecoder.decode(bytes)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + const value = textDecoder.decode(bytes); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Box_wrap"] = function(pointer) { + const obj = _exports['Box'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_importMirrorDictionary"] = function bjs_importMirrorDictionary() { + try { + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const f64 = f64Stack.pop(); + const string = strStack.pop(); + dictResult[string] = f64; + } + let ret = imports.importMirrorDictionary(dictResult); + const entries = Object.entries(ret); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + f64Stack.push(value); + } + i32Stack.push(entries.length); + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class Box extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Box_deinit, Box.prototype); + } + + } + const exports = { + Box, + mirrorDictionary: function bjs_mirrorDictionary(values) { + const entries = Object.entries(values); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value | 0)); + } + i32Stack.push(entries.length); + instance.exports.bjs_mirrorDictionary(); + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const int = i32Stack.pop(); + const string = strStack.pop(); + dictResult[string] = int; + } + return dictResult; + }, + optionalDictionary: function bjs_optionalDictionary(values) { + const isSome = values != null; + if (isSome) { + const entries = Object.entries(values); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + const bytes1 = textEncoder.encode(value); + const id1 = swift.memory.retain(bytes1); + i32Stack.push(bytes1.length); + i32Stack.push(id1); + } + i32Stack.push(entries.length); + } + i32Stack.push(+isSome); + instance.exports.bjs_optionalDictionary(); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const string = strStack.pop(); + const string1 = strStack.pop(); + dictResult[string1] = string; + } + optResult = dictResult; + } else { + optResult = null; + } + return optResult; + }, + nestedDictionary: function bjs_nestedDictionary(values) { + const entries = Object.entries(values); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + for (const elem of value) { + i32Stack.push((elem | 0)); + } + i32Stack.push(value.length); + } + i32Stack.push(entries.length); + instance.exports.bjs_nestedDictionary(); + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i1 = 0; i1 < arrayLen; i1++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + const string = strStack.pop(); + dictResult[string] = arrayResult; + } + return dictResult; + }, + boxDictionary: function bjs_boxDictionary(boxes) { + const entries = Object.entries(boxes); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + ptrStack.push(value.pointer); + } + i32Stack.push(entries.length); + instance.exports.bjs_boxDictionary(); + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const ptr = ptrStack.pop(); + const obj = _exports['Box'].__construct(ptr); + const string = strStack.pop(); + dictResult[string] = obj; + } + return dictResult; + }, + optionalBoxDictionary: function bjs_optionalBoxDictionary(boxes) { + const entries = Object.entries(boxes); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + const isSome = value != null ? 1 : 0; + if (isSome) { + ptrStack.push(value.pointer); + } else { + ptrStack.push(0); + } + i32Stack.push(isSome); + } + i32Stack.push(entries.length); + instance.exports.bjs_optionalBoxDictionary(); + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const isSome1 = i32Stack.pop(); + let optValue; + if (isSome1 === 0) { + optValue = null; + } else { + const ptr = ptrStack.pop(); + const obj = _exports['Box'].__construct(ptr); + optValue = obj; + } + const string = strStack.pop(); + dictResult[string] = optValue; + } + return dictResult; + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.js deleted file mode 100644 index 2d8dbc0ca..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.js +++ /dev/null @@ -1,877 +0,0 @@ -// 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 APIResultValues = { - Tag: { - Success: 0, - Failure: 1, - Flag: 2, - Rate: 3, - Precise: 4, - Info: 5, - }, -}; - -const __bjs_createAPIResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case APIResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: APIResultValues.Tag.Success, cleanup }; - } - case APIResultValues.Tag.Failure: { - tmpParamInts.push((value.param0 | 0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Failure, cleanup }; - } - case APIResultValues.Tag.Flag: { - tmpParamInts.push(value.param0 ? 1 : 0); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Flag, cleanup }; - } - case APIResultValues.Tag.Rate: { - tmpParamF32s.push(Math.fround(value.param0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Rate, cleanup }; - } - case APIResultValues.Tag.Precise: { - tmpParamF64s.push(value.param0); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Precise, cleanup }; - } - case APIResultValues.Tag.Info: { - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Info, cleanup }; - } - default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case APIResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: APIResultValues.Tag.Success, param0: string }; - } - case APIResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); - return { tag: APIResultValues.Tag.Failure, param0: int }; - } - case APIResultValues.Tag.Flag: { - const bool = tmpRetInts.pop(); - return { tag: APIResultValues.Tag.Flag, param0: bool }; - } - case APIResultValues.Tag.Rate: { - const f32 = tmpRetF32s.pop(); - return { tag: APIResultValues.Tag.Rate, param0: f32 }; - } - case APIResultValues.Tag.Precise: { - const f64 = tmpRetF64s.pop(); - return { tag: APIResultValues.Tag.Precise, param0: f64 }; - } - case APIResultValues.Tag.Info: return { tag: APIResultValues.Tag.Info }; - default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export const ComplexResultValues = { - Tag: { - Success: 0, - Error: 1, - Status: 2, - Coordinates: 3, - Comprehensive: 4, - Info: 5, - }, -}; - -const __bjs_createComplexResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case ComplexResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ComplexResultValues.Tag.Success, cleanup }; - } - case ComplexResultValues.Tag.Error: { - tmpParamInts.push((value.param1 | 0)); - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ComplexResultValues.Tag.Error, cleanup }; - } - case ComplexResultValues.Tag.Status: { - const bytes = textEncoder.encode(value.param2); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - tmpParamInts.push((value.param1 | 0)); - tmpParamInts.push(value.param0 ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ComplexResultValues.Tag.Status, cleanup }; - } - case ComplexResultValues.Tag.Coordinates: { - tmpParamF64s.push(value.param2); - tmpParamF64s.push(value.param1); - tmpParamF64s.push(value.param0); - const cleanup = undefined; - return { caseId: ComplexResultValues.Tag.Coordinates, cleanup }; - } - case ComplexResultValues.Tag.Comprehensive: { - const bytes = textEncoder.encode(value.param8); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const bytes1 = textEncoder.encode(value.param7); - const id1 = swift.memory.retain(bytes1); - tmpParamInts.push(bytes1.length); - tmpParamInts.push(id1); - const bytes2 = textEncoder.encode(value.param6); - const id2 = swift.memory.retain(bytes2); - tmpParamInts.push(bytes2.length); - tmpParamInts.push(id2); - tmpParamF64s.push(value.param5); - tmpParamF64s.push(value.param4); - tmpParamInts.push((value.param3 | 0)); - tmpParamInts.push((value.param2 | 0)); - tmpParamInts.push(value.param1 ? 1 : 0); - tmpParamInts.push(value.param0 ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - swift.memory.release(id1); - swift.memory.release(id2); - }; - return { caseId: ComplexResultValues.Tag.Comprehensive, cleanup }; - } - case ComplexResultValues.Tag.Info: { - const cleanup = undefined; - return { caseId: ComplexResultValues.Tag.Info, cleanup }; - } - default: throw new Error("Unknown ComplexResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case ComplexResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: ComplexResultValues.Tag.Success, param0: string }; - } - case ComplexResultValues.Tag.Error: { - const int = tmpRetInts.pop(); - const string = tmpRetStrings.pop(); - return { tag: ComplexResultValues.Tag.Error, param0: string, param1: int }; - } - case ComplexResultValues.Tag.Status: { - const string = tmpRetStrings.pop(); - const int = tmpRetInts.pop(); - const bool = tmpRetInts.pop(); - return { tag: ComplexResultValues.Tag.Status, param0: bool, param1: int, param2: string }; - } - case ComplexResultValues.Tag.Coordinates: { - const f64 = tmpRetF64s.pop(); - const f641 = tmpRetF64s.pop(); - const f642 = tmpRetF64s.pop(); - return { tag: ComplexResultValues.Tag.Coordinates, param0: f642, param1: f641, param2: f64 }; - } - case ComplexResultValues.Tag.Comprehensive: { - const string = tmpRetStrings.pop(); - const string1 = tmpRetStrings.pop(); - const string2 = tmpRetStrings.pop(); - const f64 = tmpRetF64s.pop(); - const f641 = tmpRetF64s.pop(); - const int = tmpRetInts.pop(); - const int1 = tmpRetInts.pop(); - const bool = tmpRetInts.pop(); - const bool1 = tmpRetInts.pop(); - return { tag: ComplexResultValues.Tag.Comprehensive, param0: bool1, param1: bool, param2: int1, param3: int, param4: f641, param5: f64, param6: string2, param7: string1, param8: string }; - } - case ComplexResultValues.Tag.Info: return { tag: ComplexResultValues.Tag.Info }; - default: throw new Error("Unknown ComplexResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export const ResultValues = { - Tag: { - Success: 0, - Failure: 1, - Status: 2, - }, -}; - -const __bjs_createResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case ResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ResultValues.Tag.Success, cleanup }; - } - case ResultValues.Tag.Failure: { - tmpParamInts.push((value.param1 | 0)); - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ResultValues.Tag.Failure, cleanup }; - } - case ResultValues.Tag.Status: { - const bytes = textEncoder.encode(value.param2); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - tmpParamInts.push((value.param1 | 0)); - tmpParamInts.push(value.param0 ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ResultValues.Tag.Status, cleanup }; - } - default: throw new Error("Unknown ResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case ResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: ResultValues.Tag.Success, param0: string }; - } - case ResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); - const string = tmpRetStrings.pop(); - return { tag: ResultValues.Tag.Failure, param0: string, param1: int }; - } - case ResultValues.Tag.Status: { - const string = tmpRetStrings.pop(); - const int = tmpRetInts.pop(); - const bool = tmpRetInts.pop(); - return { tag: ResultValues.Tag.Status, param0: bool, param1: int, param2: string }; - } - default: throw new Error("Unknown ResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export const NetworkingResultValues = { - Tag: { - Success: 0, - Failure: 1, - }, -}; - -const __bjs_createNetworkingResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case NetworkingResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: NetworkingResultValues.Tag.Success, cleanup }; - } - case NetworkingResultValues.Tag.Failure: { - tmpParamInts.push((value.param1 | 0)); - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: NetworkingResultValues.Tag.Failure, cleanup }; - } - default: throw new Error("Unknown NetworkingResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case NetworkingResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: NetworkingResultValues.Tag.Success, param0: string }; - } - case NetworkingResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); - const string = tmpRetStrings.pop(); - return { tag: NetworkingResultValues.Tag.Failure, param0: string, param1: int }; - } - default: throw new Error("Unknown NetworkingResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export const APIOptionalResultValues = { - Tag: { - Success: 0, - Failure: 1, - Status: 2, - }, -}; - -const __bjs_createAPIOptionalResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case APIOptionalResultValues.Tag.Success: { - const isSome = value.param0 != null; - let id; - if (isSome) { - let bytes = textEncoder.encode(value.param0); - id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - } else { - tmpParamInts.push(0); - tmpParamInts.push(0); - } - tmpParamInts.push(isSome ? 1 : 0); - const cleanup = () => { - if(id) { - swift.memory.release(id); - } - }; - return { caseId: APIOptionalResultValues.Tag.Success, cleanup }; - } - case APIOptionalResultValues.Tag.Failure: { - const isSome = value.param1 != null; - tmpParamInts.push(isSome ? (value.param1 ? 1 : 0) : 0); - tmpParamInts.push(isSome ? 1 : 0); - const isSome1 = value.param0 != null; - tmpParamInts.push(isSome1 ? (value.param0 | 0) : 0); - tmpParamInts.push(isSome1 ? 1 : 0); - const cleanup = undefined; - return { caseId: APIOptionalResultValues.Tag.Failure, cleanup }; - } - case APIOptionalResultValues.Tag.Status: { - const isSome = value.param2 != null; - let id; - if (isSome) { - let bytes = textEncoder.encode(value.param2); - id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - } else { - tmpParamInts.push(0); - tmpParamInts.push(0); - } - tmpParamInts.push(isSome ? 1 : 0); - const isSome1 = value.param1 != null; - tmpParamInts.push(isSome1 ? (value.param1 | 0) : 0); - tmpParamInts.push(isSome1 ? 1 : 0); - const isSome2 = value.param0 != null; - tmpParamInts.push(isSome2 ? (value.param0 ? 1 : 0) : 0); - tmpParamInts.push(isSome2 ? 1 : 0); - const cleanup = () => { - if(id) { - swift.memory.release(id); - } - }; - return { caseId: APIOptionalResultValues.Tag.Status, cleanup }; - } - default: throw new Error("Unknown APIOptionalResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case APIOptionalResultValues.Tag.Success: { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const string = tmpRetStrings.pop(); - optional = string; - } else { - optional = null; - } - return { tag: APIOptionalResultValues.Tag.Success, param0: optional }; - } - case APIOptionalResultValues.Tag.Failure: { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const bool = tmpRetInts.pop(); - optional = bool; - } else { - optional = null; - } - const isSome1 = tmpRetInts.pop(); - let optional1; - if (isSome1) { - const int = tmpRetInts.pop(); - optional1 = int; - } else { - optional1 = null; - } - return { tag: APIOptionalResultValues.Tag.Failure, param0: optional1, param1: optional }; - } - case APIOptionalResultValues.Tag.Status: { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const string = tmpRetStrings.pop(); - optional = string; - } else { - optional = null; - } - const isSome1 = tmpRetInts.pop(); - let optional1; - if (isSome1) { - const int = tmpRetInts.pop(); - optional1 = int; - } else { - optional1 = null; - } - const isSome2 = tmpRetInts.pop(); - let optional2; - if (isSome2) { - const bool = tmpRetInts.pop(); - optional2 = bool; - } else { - optional2 = null; - } - return { tag: APIOptionalResultValues.Tag.Status, param0: optional2, param1: optional1, param2: optional }; - } - default: throw new Error("Unknown APIOptionalResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - const APIResultHelpers = __bjs_createAPIResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.APIResult = APIResultHelpers; - - const ComplexResultHelpers = __bjs_createComplexResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.ComplexResult = ComplexResultHelpers; - - const ResultHelpers = __bjs_createResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.Result = ResultHelpers; - - const NetworkingResultHelpers = __bjs_createNetworkingResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.NetworkingResult = NetworkingResultHelpers; - - const APIOptionalResultHelpers = __bjs_createAPIOptionalResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.APIOptionalResult = APIOptionalResultHelpers; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - handle: function bjs_handle(result) { - const { caseId: resultCaseId, cleanup: resultCleanup } = enumHelpers.APIResult.lower(result); - instance.exports.bjs_handle(resultCaseId); - if (resultCleanup) { resultCleanup(); } - }, - getResult: function bjs_getResult() { - instance.exports.bjs_getResult(); - const ret = enumHelpers.APIResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - return ret; - }, - roundtripAPIResult: function bjs_roundtripAPIResult(result) { - const { caseId: resultCaseId, cleanup: resultCleanup } = enumHelpers.APIResult.lower(result); - instance.exports.bjs_roundtripAPIResult(resultCaseId); - const ret = enumHelpers.APIResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - if (resultCleanup) { resultCleanup(); } - return ret; - }, - roundTripOptionalAPIResult: function bjs_roundTripOptionalAPIResult(result) { - const isSome = result != null; - let resultCaseId, resultCleanup; - if (isSome) { - const enumResult = enumHelpers.APIResult.lower(result); - resultCaseId = enumResult.caseId; - resultCleanup = enumResult.cleanup; - } - instance.exports.bjs_roundTripOptionalAPIResult(+isSome, isSome ? resultCaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.APIResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (resultCleanup) { resultCleanup(); } - return optResult; - }, - handleComplex: function bjs_handleComplex(result) { - const { caseId: resultCaseId, cleanup: resultCleanup } = enumHelpers.ComplexResult.lower(result); - instance.exports.bjs_handleComplex(resultCaseId); - if (resultCleanup) { resultCleanup(); } - }, - getComplexResult: function bjs_getComplexResult() { - instance.exports.bjs_getComplexResult(); - const ret = enumHelpers.ComplexResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - return ret; - }, - roundtripComplexResult: function bjs_roundtripComplexResult(result) { - const { caseId: resultCaseId, cleanup: resultCleanup } = enumHelpers.ComplexResult.lower(result); - instance.exports.bjs_roundtripComplexResult(resultCaseId); - const ret = enumHelpers.ComplexResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - if (resultCleanup) { resultCleanup(); } - return ret; - }, - roundTripOptionalComplexResult: function bjs_roundTripOptionalComplexResult(result) { - const isSome = result != null; - let resultCaseId, resultCleanup; - if (isSome) { - const enumResult = enumHelpers.ComplexResult.lower(result); - resultCaseId = enumResult.caseId; - resultCleanup = enumResult.cleanup; - } - instance.exports.bjs_roundTripOptionalComplexResult(+isSome, isSome ? resultCaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.ComplexResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (resultCleanup) { resultCleanup(); } - return optResult; - }, - roundTripOptionalUtilitiesResult: function bjs_roundTripOptionalUtilitiesResult(result) { - const isSome = result != null; - let resultCaseId, resultCleanup; - if (isSome) { - const enumResult = enumHelpers.Result.lower(result); - resultCaseId = enumResult.caseId; - resultCleanup = enumResult.cleanup; - } - instance.exports.bjs_roundTripOptionalUtilitiesResult(+isSome, isSome ? resultCaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.Result.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (resultCleanup) { resultCleanup(); } - return optResult; - }, - roundTripOptionalNetworkingResult: function bjs_roundTripOptionalNetworkingResult(result) { - const isSome = result != null; - let resultCaseId, resultCleanup; - if (isSome) { - const enumResult = enumHelpers.NetworkingResult.lower(result); - resultCaseId = enumResult.caseId; - resultCleanup = enumResult.cleanup; - } - instance.exports.bjs_roundTripOptionalNetworkingResult(+isSome, isSome ? resultCaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.NetworkingResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (resultCleanup) { resultCleanup(); } - return optResult; - }, - roundTripOptionalAPIOptionalResult: function bjs_roundTripOptionalAPIOptionalResult(result) { - const isSome = result != null; - let resultCaseId, resultCleanup; - if (isSome) { - const enumResult = enumHelpers.APIOptionalResult.lower(result); - resultCaseId = enumResult.caseId; - resultCleanup = enumResult.cleanup; - } - instance.exports.bjs_roundTripOptionalAPIOptionalResult(+isSome, isSome ? resultCaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.APIOptionalResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (resultCleanup) { resultCleanup(); } - return optResult; - }, - compareAPIResults: function bjs_compareAPIResults(result1, result2) { - const isSome = result1 != null; - let result1CaseId, result1Cleanup; - if (isSome) { - const enumResult = enumHelpers.APIOptionalResult.lower(result1); - result1CaseId = enumResult.caseId; - result1Cleanup = enumResult.cleanup; - } - const isSome1 = result2 != null; - let result2CaseId, result2Cleanup; - if (isSome1) { - const enumResult1 = enumHelpers.APIOptionalResult.lower(result2); - result2CaseId = enumResult1.caseId; - result2Cleanup = enumResult1.cleanup; - } - instance.exports.bjs_compareAPIResults(+isSome, isSome ? result1CaseId : 0, +isSome1, isSome1 ? result2CaseId : 0); - const isNull = (tmpRetTag === -1); - let optResult; - if (isNull) { - optResult = null; - } else { - optResult = enumHelpers.APIOptionalResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } - if (result1Cleanup) { result1Cleanup(); } - if (result2Cleanup) { result2Cleanup(); } - return optResult; - }, - APIResult: APIResultValues, - ComplexResult: ComplexResultValues, - APIOptionalResult: APIOptionalResultValues, - API: { - NetworkingResult: NetworkingResultValues, - }, - Utilities: { - Result: ResultValues, - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts similarity index 53% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts index 20962c388..13f77ae08 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts @@ -43,6 +43,65 @@ export const APIOptionalResultValues: { export type APIOptionalResultTag = { tag: typeof APIOptionalResultValues.Tag.Success; param0: string | null } | { tag: typeof APIOptionalResultValues.Tag.Failure; param0: number | null; param1: boolean | null } | { tag: typeof APIOptionalResultValues.Tag.Status; param0: boolean | null; param1: number | null; param2: string | null } +export const PrecisionValues: { + readonly Rough: 0.1; + readonly Fine: 0.001; +}; +export type PrecisionTag = typeof PrecisionValues[keyof typeof PrecisionValues]; + +export const CardinalDirectionValues: { + readonly North: 0; + readonly South: 1; + readonly East: 2; + readonly West: 3; +}; +export type CardinalDirectionTag = typeof CardinalDirectionValues[keyof typeof CardinalDirectionValues]; + +export const TypedPayloadResultValues: { + readonly Tag: { + readonly Precision: 0; + readonly Direction: 1; + readonly OptPrecision: 2; + readonly OptDirection: 3; + readonly Empty: 4; + }; +}; + +export type TypedPayloadResultTag = + { tag: typeof TypedPayloadResultValues.Tag.Precision; param0: PrecisionTag } | { tag: typeof TypedPayloadResultValues.Tag.Direction; param0: CardinalDirectionTag } | { tag: typeof TypedPayloadResultValues.Tag.OptPrecision; param0: PrecisionTag | null } | { tag: typeof TypedPayloadResultValues.Tag.OptDirection; param0: CardinalDirectionTag | null } | { tag: typeof TypedPayloadResultValues.Tag.Empty } + +export const AllTypesResultValues: { + readonly Tag: { + readonly StructPayload: 0; + readonly ClassPayload: 1; + readonly JsObjectPayload: 2; + readonly NestedEnum: 3; + readonly ArrayPayload: 4; + readonly Empty: 5; + }; +}; + +export type AllTypesResultTag = + { tag: typeof AllTypesResultValues.Tag.StructPayload; param0: Point } | { tag: typeof AllTypesResultValues.Tag.ClassPayload; param0: User } | { tag: typeof AllTypesResultValues.Tag.JsObjectPayload; param0: any } | { tag: typeof AllTypesResultValues.Tag.NestedEnum; param0: APIResultTag } | { tag: typeof AllTypesResultValues.Tag.ArrayPayload; param0: number[] } | { tag: typeof AllTypesResultValues.Tag.Empty } + +export const OptionalAllTypesResultValues: { + readonly Tag: { + readonly OptStruct: 0; + readonly OptClass: 1; + readonly OptJSObject: 2; + readonly OptNestedEnum: 3; + readonly OptArray: 4; + readonly Empty: 5; + }; +}; + +export type OptionalAllTypesResultTag = + { tag: typeof OptionalAllTypesResultValues.Tag.OptStruct; param0: Point | null } | { tag: typeof OptionalAllTypesResultValues.Tag.OptClass; param0: User | null } | { tag: typeof OptionalAllTypesResultValues.Tag.OptJSObject; param0: any | null } | { tag: typeof OptionalAllTypesResultValues.Tag.OptNestedEnum; param0: APIResultTag | null } | { tag: typeof OptionalAllTypesResultValues.Tag.OptArray; param0: number[] | null } | { tag: typeof OptionalAllTypesResultValues.Tag.Empty } + +export interface Point { + x: number; + y: number; +} export type APIResultObject = typeof APIResultValues; export type ComplexResultObject = typeof ComplexResultValues; @@ -53,6 +112,16 @@ export type NetworkingResultObject = typeof API.NetworkingResultValues; export type APIOptionalResultObject = typeof APIOptionalResultValues; +export type PrecisionObject = typeof PrecisionValues; + +export type CardinalDirectionObject = typeof CardinalDirectionValues; + +export type TypedPayloadResultObject = typeof TypedPayloadResultValues; + +export type AllTypesResultObject = typeof AllTypesResultValues; + +export type OptionalAllTypesResultObject = typeof OptionalAllTypesResultValues; + export namespace API { const NetworkingResultValues: { readonly Tag: { @@ -74,7 +143,18 @@ export namespace Utilities { type ResultTag = { tag: typeof ResultValues.Tag.Success; param0: string } | { tag: typeof ResultValues.Tag.Failure; param0: string; param1: number } | { tag: typeof ResultValues.Tag.Status; param0: boolean; param1: number; param2: string } } +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface User extends SwiftHeapObject { +} export type Exports = { + User: { + } handle(result: APIResultTag): void; getResult(): APIResultTag; roundtripAPIResult(result: APIResultTag): APIResultTag; @@ -87,9 +167,20 @@ export type Exports = { roundTripOptionalNetworkingResult(result: API.NetworkingResultTag | null): API.NetworkingResultTag | null; roundTripOptionalAPIOptionalResult(result: APIOptionalResultTag | null): APIOptionalResultTag | null; compareAPIResults(result1: APIOptionalResultTag | null, result2: APIOptionalResultTag | null): APIOptionalResultTag | null; + roundTripTypedPayloadResult(result: TypedPayloadResultTag): TypedPayloadResultTag; + roundTripOptionalTypedPayloadResult(result: TypedPayloadResultTag | null): TypedPayloadResultTag | null; + roundTripAllTypesResult(result: AllTypesResultTag): AllTypesResultTag; + roundTripOptionalAllTypesResult(result: AllTypesResultTag | null): AllTypesResultTag | null; + roundTripOptionalPayloadResult(result: OptionalAllTypesResultTag): OptionalAllTypesResultTag; + roundTripOptionalPayloadResultOpt(result: OptionalAllTypesResultTag | null): OptionalAllTypesResultTag | null; APIResult: APIResultObject ComplexResult: ComplexResultObject APIOptionalResult: APIOptionalResultObject + Precision: PrecisionObject + CardinalDirection: CardinalDirectionObject + TypedPayloadResult: TypedPayloadResultObject + AllTypesResult: AllTypesResultObject + OptionalAllTypesResult: OptionalAllTypesResultObject API: { NetworkingResult: NetworkingResultObject }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js new file mode 100644 index 000000000..55967a6a3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -0,0 +1,1212 @@ +// 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 APIResultValues = { + Tag: { + Success: 0, + Failure: 1, + Flag: 2, + Rate: 3, + Precise: 4, + Info: 5, + }, +}; +export const ComplexResultValues = { + Tag: { + Success: 0, + Error: 1, + Status: 2, + Coordinates: 3, + Comprehensive: 4, + Info: 5, + }, +}; +export const ResultValues = { + Tag: { + Success: 0, + Failure: 1, + Status: 2, + }, +}; +export const NetworkingResultValues = { + Tag: { + Success: 0, + Failure: 1, + }, +}; +export const APIOptionalResultValues = { + Tag: { + Success: 0, + Failure: 1, + Status: 2, + }, +}; +export const PrecisionValues = { + Rough: 0.1, + Fine: 0.001, +}; + +export const CardinalDirectionValues = { + North: 0, + South: 1, + East: 2, + West: 3, +}; + +export const TypedPayloadResultValues = { + Tag: { + Precision: 0, + Direction: 1, + OptPrecision: 2, + OptDirection: 3, + Empty: 4, + }, +}; +export const AllTypesResultValues = { + Tag: { + StructPayload: 0, + ClassPayload: 1, + JsObjectPayload: 2, + NestedEnum: 3, + ArrayPayload: 4, + Empty: 5, + }, +}; +export const OptionalAllTypesResultValues = { + Tag: { + OptStruct: 0, + OptClass: 1, + OptJSObject: 2, + OptNestedEnum: 3, + OptArray: 4, + Empty: 5, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createPointHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.x); + f64Stack.push(value.y); + }, + lift: () => { + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + return { x: f641, y: f64 }; + } + }); + const __bjs_createAPIResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case APIResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return APIResultValues.Tag.Success; + } + case APIResultValues.Tag.Failure: { + i32Stack.push((value.param0 | 0)); + return APIResultValues.Tag.Failure; + } + case APIResultValues.Tag.Flag: { + i32Stack.push(value.param0 ? 1 : 0); + return APIResultValues.Tag.Flag; + } + case APIResultValues.Tag.Rate: { + f32Stack.push(Math.fround(value.param0)); + return APIResultValues.Tag.Rate; + } + case APIResultValues.Tag.Precise: { + f64Stack.push(value.param0); + return APIResultValues.Tag.Precise; + } + case APIResultValues.Tag.Info: { + return APIResultValues.Tag.Info; + } + default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case APIResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: APIResultValues.Tag.Success, param0: string }; + } + case APIResultValues.Tag.Failure: { + const int = i32Stack.pop(); + return { tag: APIResultValues.Tag.Failure, param0: int }; + } + case APIResultValues.Tag.Flag: { + const bool = i32Stack.pop() !== 0; + return { tag: APIResultValues.Tag.Flag, param0: bool }; + } + case APIResultValues.Tag.Rate: { + const f32 = f32Stack.pop(); + return { tag: APIResultValues.Tag.Rate, param0: f32 }; + } + case APIResultValues.Tag.Precise: { + const f64 = f64Stack.pop(); + return { tag: APIResultValues.Tag.Precise, param0: f64 }; + } + case APIResultValues.Tag.Info: return { tag: APIResultValues.Tag.Info }; + default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createComplexResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case ComplexResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return ComplexResultValues.Tag.Success; + } + case ComplexResultValues.Tag.Error: { + i32Stack.push((value.param1 | 0)); + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return ComplexResultValues.Tag.Error; + } + case ComplexResultValues.Tag.Status: { + const bytes = textEncoder.encode(value.param2); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value.param1 | 0)); + i32Stack.push(value.param0 ? 1 : 0); + return ComplexResultValues.Tag.Status; + } + case ComplexResultValues.Tag.Coordinates: { + f64Stack.push(value.param2); + f64Stack.push(value.param1); + f64Stack.push(value.param0); + return ComplexResultValues.Tag.Coordinates; + } + case ComplexResultValues.Tag.Comprehensive: { + const bytes = textEncoder.encode(value.param8); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + const bytes1 = textEncoder.encode(value.param7); + const id1 = swift.memory.retain(bytes1); + i32Stack.push(bytes1.length); + i32Stack.push(id1); + const bytes2 = textEncoder.encode(value.param6); + const id2 = swift.memory.retain(bytes2); + i32Stack.push(bytes2.length); + i32Stack.push(id2); + f64Stack.push(value.param5); + f64Stack.push(value.param4); + i32Stack.push((value.param3 | 0)); + i32Stack.push((value.param2 | 0)); + i32Stack.push(value.param1 ? 1 : 0); + i32Stack.push(value.param0 ? 1 : 0); + return ComplexResultValues.Tag.Comprehensive; + } + case ComplexResultValues.Tag.Info: { + return ComplexResultValues.Tag.Info; + } + default: throw new Error("Unknown ComplexResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case ComplexResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: ComplexResultValues.Tag.Success, param0: string }; + } + case ComplexResultValues.Tag.Error: { + const int = i32Stack.pop(); + const string = strStack.pop(); + return { tag: ComplexResultValues.Tag.Error, param0: string, param1: int }; + } + case ComplexResultValues.Tag.Status: { + const string = strStack.pop(); + const int = i32Stack.pop(); + const bool = i32Stack.pop() !== 0; + return { tag: ComplexResultValues.Tag.Status, param0: bool, param1: int, param2: string }; + } + case ComplexResultValues.Tag.Coordinates: { + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + const f642 = f64Stack.pop(); + return { tag: ComplexResultValues.Tag.Coordinates, param0: f642, param1: f641, param2: f64 }; + } + case ComplexResultValues.Tag.Comprehensive: { + const string = strStack.pop(); + const string1 = strStack.pop(); + const string2 = strStack.pop(); + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + const int = i32Stack.pop(); + const int1 = i32Stack.pop(); + const bool = i32Stack.pop() !== 0; + const bool1 = i32Stack.pop() !== 0; + return { tag: ComplexResultValues.Tag.Comprehensive, param0: bool1, param1: bool, param2: int1, param3: int, param4: f641, param5: f64, param6: string2, param7: string1, param8: string }; + } + case ComplexResultValues.Tag.Info: return { tag: ComplexResultValues.Tag.Info }; + default: throw new Error("Unknown ComplexResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case ResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return ResultValues.Tag.Success; + } + case ResultValues.Tag.Failure: { + i32Stack.push((value.param1 | 0)); + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return ResultValues.Tag.Failure; + } + case ResultValues.Tag.Status: { + const bytes = textEncoder.encode(value.param2); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value.param1 | 0)); + i32Stack.push(value.param0 ? 1 : 0); + return ResultValues.Tag.Status; + } + default: throw new Error("Unknown ResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case ResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: ResultValues.Tag.Success, param0: string }; + } + case ResultValues.Tag.Failure: { + const int = i32Stack.pop(); + const string = strStack.pop(); + return { tag: ResultValues.Tag.Failure, param0: string, param1: int }; + } + case ResultValues.Tag.Status: { + const string = strStack.pop(); + const int = i32Stack.pop(); + const bool = i32Stack.pop() !== 0; + return { tag: ResultValues.Tag.Status, param0: bool, param1: int, param2: string }; + } + default: throw new Error("Unknown ResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createNetworkingResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case NetworkingResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return NetworkingResultValues.Tag.Success; + } + case NetworkingResultValues.Tag.Failure: { + i32Stack.push((value.param1 | 0)); + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return NetworkingResultValues.Tag.Failure; + } + default: throw new Error("Unknown NetworkingResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case NetworkingResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: NetworkingResultValues.Tag.Success, param0: string }; + } + case NetworkingResultValues.Tag.Failure: { + const int = i32Stack.pop(); + const string = strStack.pop(); + return { tag: NetworkingResultValues.Tag.Failure, param0: string, param1: int }; + } + default: throw new Error("Unknown NetworkingResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createAPIOptionalResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case APIOptionalResultValues.Tag.Success: { + const isSome = value.param0 != null; + if (isSome) { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + } else { + i32Stack.push(0); + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + return APIOptionalResultValues.Tag.Success; + } + case APIOptionalResultValues.Tag.Failure: { + const isSome = value.param1 != null; + i32Stack.push(isSome ? (value.param1 ? 1 : 0) : 0); + i32Stack.push(isSome ? 1 : 0); + const isSome1 = value.param0 != null; + i32Stack.push(isSome1 ? (value.param0 | 0) : 0); + i32Stack.push(isSome1 ? 1 : 0); + return APIOptionalResultValues.Tag.Failure; + } + case APIOptionalResultValues.Tag.Status: { + const isSome = value.param2 != null; + if (isSome) { + const bytes = textEncoder.encode(value.param2); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + } else { + i32Stack.push(0); + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + const isSome1 = value.param1 != null; + i32Stack.push(isSome1 ? (value.param1 | 0) : 0); + i32Stack.push(isSome1 ? 1 : 0); + const isSome2 = value.param0 != null; + i32Stack.push(isSome2 ? (value.param0 ? 1 : 0) : 0); + i32Stack.push(isSome2 ? 1 : 0); + return APIOptionalResultValues.Tag.Status; + } + default: throw new Error("Unknown APIOptionalResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case APIOptionalResultValues.Tag.Success: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const string = strStack.pop(); + optional = string; + } else { + optional = null; + } + return { tag: APIOptionalResultValues.Tag.Success, param0: optional }; + } + case APIOptionalResultValues.Tag.Failure: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const bool = i32Stack.pop() !== 0; + optional = bool; + } else { + optional = null; + } + const isSome1 = i32Stack.pop(); + let optional1; + if (isSome1) { + const int = i32Stack.pop(); + optional1 = int; + } else { + optional1 = null; + } + return { tag: APIOptionalResultValues.Tag.Failure, param0: optional1, param1: optional }; + } + case APIOptionalResultValues.Tag.Status: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const string = strStack.pop(); + optional = string; + } else { + optional = null; + } + const isSome1 = i32Stack.pop(); + let optional1; + if (isSome1) { + const int = i32Stack.pop(); + optional1 = int; + } else { + optional1 = null; + } + const isSome2 = i32Stack.pop(); + let optional2; + if (isSome2) { + const bool = i32Stack.pop() !== 0; + optional2 = bool; + } else { + optional2 = null; + } + return { tag: APIOptionalResultValues.Tag.Status, param0: optional2, param1: optional1, param2: optional }; + } + default: throw new Error("Unknown APIOptionalResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createTypedPayloadResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case TypedPayloadResultValues.Tag.Precision: { + f32Stack.push(Math.fround(value.param0)); + return TypedPayloadResultValues.Tag.Precision; + } + case TypedPayloadResultValues.Tag.Direction: { + i32Stack.push((value.param0 | 0)); + return TypedPayloadResultValues.Tag.Direction; + } + case TypedPayloadResultValues.Tag.OptPrecision: { + const isSome = value.param0 != null; + f32Stack.push(isSome ? Math.fround(value.param0) : 0.0); + i32Stack.push(isSome ? 1 : 0); + return TypedPayloadResultValues.Tag.OptPrecision; + } + case TypedPayloadResultValues.Tag.OptDirection: { + const isSome = value.param0 != null; + i32Stack.push(isSome ? (value.param0 | 0) : 0); + i32Stack.push(isSome ? 1 : 0); + return TypedPayloadResultValues.Tag.OptDirection; + } + case TypedPayloadResultValues.Tag.Empty: { + return TypedPayloadResultValues.Tag.Empty; + } + default: throw new Error("Unknown TypedPayloadResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case TypedPayloadResultValues.Tag.Precision: { + const rawValue = f32Stack.pop(); + return { tag: TypedPayloadResultValues.Tag.Precision, param0: rawValue }; + } + case TypedPayloadResultValues.Tag.Direction: { + const caseId = i32Stack.pop(); + return { tag: TypedPayloadResultValues.Tag.Direction, param0: caseId }; + } + case TypedPayloadResultValues.Tag.OptPrecision: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const rawValue = f32Stack.pop(); + optional = rawValue; + } else { + optional = null; + } + return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optional }; + } + case TypedPayloadResultValues.Tag.OptDirection: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const caseId = i32Stack.pop(); + optional = caseId; + } else { + optional = null; + } + return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optional }; + } + case TypedPayloadResultValues.Tag.Empty: return { tag: TypedPayloadResultValues.Tag.Empty }; + default: throw new Error("Unknown TypedPayloadResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createAllTypesResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case AllTypesResultValues.Tag.StructPayload: { + structHelpers.Point.lower(value.param0); + return AllTypesResultValues.Tag.StructPayload; + } + case AllTypesResultValues.Tag.ClassPayload: { + ptrStack.push(value.param0.pointer); + return AllTypesResultValues.Tag.ClassPayload; + } + case AllTypesResultValues.Tag.JsObjectPayload: { + const objId = swift.memory.retain(value.param0); + i32Stack.push(objId); + return AllTypesResultValues.Tag.JsObjectPayload; + } + case AllTypesResultValues.Tag.NestedEnum: { + const caseId = enumHelpers.APIResult.lower(value.param0); + i32Stack.push(caseId); + return AllTypesResultValues.Tag.NestedEnum; + } + case AllTypesResultValues.Tag.ArrayPayload: { + for (const elem of value.param0) { + i32Stack.push((elem | 0)); + } + i32Stack.push(value.param0.length); + return AllTypesResultValues.Tag.ArrayPayload; + } + case AllTypesResultValues.Tag.Empty: { + return AllTypesResultValues.Tag.Empty; + } + default: throw new Error("Unknown AllTypesResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case AllTypesResultValues.Tag.StructPayload: { + const struct = structHelpers.Point.lift(); + return { tag: AllTypesResultValues.Tag.StructPayload, param0: struct }; + } + case AllTypesResultValues.Tag.ClassPayload: { + const ptr = ptrStack.pop(); + const obj = _exports['User'].__construct(ptr); + return { tag: AllTypesResultValues.Tag.ClassPayload, param0: obj }; + } + case AllTypesResultValues.Tag.JsObjectPayload: { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return { tag: AllTypesResultValues.Tag.JsObjectPayload, param0: obj }; + } + case AllTypesResultValues.Tag.NestedEnum: { + const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); + return { tag: AllTypesResultValues.Tag.NestedEnum, param0: enumValue }; + } + case AllTypesResultValues.Tag.ArrayPayload: { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + return { tag: AllTypesResultValues.Tag.ArrayPayload, param0: arrayResult }; + } + case AllTypesResultValues.Tag.Empty: return { tag: AllTypesResultValues.Tag.Empty }; + default: throw new Error("Unknown AllTypesResultValues tag returned from Swift: " + String(tag)); + } + } + }); + const __bjs_createOptionalAllTypesResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case OptionalAllTypesResultValues.Tag.OptStruct: { + const isSome = value.param0 != null; + if (isSome) { + structHelpers.Point.lower(value.param0); + } + i32Stack.push(isSome ? 1 : 0); + return OptionalAllTypesResultValues.Tag.OptStruct; + } + case OptionalAllTypesResultValues.Tag.OptClass: { + const isSome = value.param0 != null; + if (isSome) { + ptrStack.push(value.param0.pointer); + } else { + ptrStack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + return OptionalAllTypesResultValues.Tag.OptClass; + } + case OptionalAllTypesResultValues.Tag.OptJSObject: { + const isSome = value.param0 != null; + if (isSome) { + const objId = swift.memory.retain(value.param0); + i32Stack.push(objId); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + return OptionalAllTypesResultValues.Tag.OptJSObject; + } + case OptionalAllTypesResultValues.Tag.OptNestedEnum: { + const isSome = value.param0 != null; + if (isSome) { + const caseId = enumHelpers.APIResult.lower(value.param0); + i32Stack.push(caseId); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + return OptionalAllTypesResultValues.Tag.OptNestedEnum; + } + case OptionalAllTypesResultValues.Tag.OptArray: { + const isSome = value.param0 != null; + if (isSome) { + for (const elem of value.param0) { + i32Stack.push((elem | 0)); + } + i32Stack.push(value.param0.length); + } + i32Stack.push(isSome ? 1 : 0); + return OptionalAllTypesResultValues.Tag.OptArray; + } + case OptionalAllTypesResultValues.Tag.Empty: { + return OptionalAllTypesResultValues.Tag.Empty; + } + default: throw new Error("Unknown OptionalAllTypesResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case OptionalAllTypesResultValues.Tag.OptStruct: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const struct = structHelpers.Point.lift(); + optional = struct; + } else { + optional = null; + } + return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optional }; + } + case OptionalAllTypesResultValues.Tag.OptClass: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const ptr = ptrStack.pop(); + const obj = _exports['User'].__construct(ptr); + optional = obj; + } else { + optional = null; + } + return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optional }; + } + case OptionalAllTypesResultValues.Tag.OptJSObject: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + optional = obj; + } else { + optional = null; + } + return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optional }; + } + case OptionalAllTypesResultValues.Tag.OptNestedEnum: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const caseId = i32Stack.pop(); + optional = enumHelpers.APIResult.lift(caseId); + } else { + optional = null; + } + return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optional }; + } + case OptionalAllTypesResultValues.Tag.OptArray: { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + optional = arrayResult; + } else { + optional = null; + } + return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optional }; + } + case OptionalAllTypesResultValues.Tag.Empty: return { tag: OptionalAllTypesResultValues.Tag.Empty }; + default: throw new Error("Unknown OptionalAllTypesResultValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + return swift.memory.retain(textDecoder.decode(bytes)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + const value = textDecoder.decode(bytes); + 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_struct_lower_Point"] = function(objectId) { + structHelpers.Point.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Point"] = function() { + const value = structHelpers.Point.lift(); + return swift.memory.retain(value); + } + 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 { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_User_wrap"] = function(pointer) { + const obj = _exports['User'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class User extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_User_deinit, User.prototype); + } + + } + const PointHelpers = __bjs_createPointHelpers(); + structHelpers.Point = PointHelpers; + + const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); + enumHelpers.APIResult = APIResultHelpers; + + const ComplexResultHelpers = __bjs_createComplexResultValuesHelpers(); + enumHelpers.ComplexResult = ComplexResultHelpers; + + const ResultHelpers = __bjs_createResultValuesHelpers(); + enumHelpers.Result = ResultHelpers; + + const NetworkingResultHelpers = __bjs_createNetworkingResultValuesHelpers(); + enumHelpers.NetworkingResult = NetworkingResultHelpers; + + const APIOptionalResultHelpers = __bjs_createAPIOptionalResultValuesHelpers(); + enumHelpers.APIOptionalResult = APIOptionalResultHelpers; + + const TypedPayloadResultHelpers = __bjs_createTypedPayloadResultValuesHelpers(); + enumHelpers.TypedPayloadResult = TypedPayloadResultHelpers; + + const AllTypesResultHelpers = __bjs_createAllTypesResultValuesHelpers(); + enumHelpers.AllTypesResult = AllTypesResultHelpers; + + const OptionalAllTypesResultHelpers = __bjs_createOptionalAllTypesResultValuesHelpers(); + enumHelpers.OptionalAllTypesResult = OptionalAllTypesResultHelpers; + + const exports = { + User, + handle: function bjs_handle(result) { + const resultCaseId = enumHelpers.APIResult.lower(result); + instance.exports.bjs_handle(resultCaseId); + }, + getResult: function bjs_getResult() { + instance.exports.bjs_getResult(); + const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + return ret; + }, + roundtripAPIResult: function bjs_roundtripAPIResult(result) { + const resultCaseId = enumHelpers.APIResult.lower(result); + instance.exports.bjs_roundtripAPIResult(resultCaseId); + const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + return ret; + }, + roundTripOptionalAPIResult: function bjs_roundTripOptionalAPIResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.APIResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalAPIResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.APIResult.lift(tag); + return optResult; + }, + handleComplex: function bjs_handleComplex(result) { + const resultCaseId = enumHelpers.ComplexResult.lower(result); + instance.exports.bjs_handleComplex(resultCaseId); + }, + getComplexResult: function bjs_getComplexResult() { + instance.exports.bjs_getComplexResult(); + const ret = enumHelpers.ComplexResult.lift(i32Stack.pop()); + return ret; + }, + roundtripComplexResult: function bjs_roundtripComplexResult(result) { + const resultCaseId = enumHelpers.ComplexResult.lower(result); + instance.exports.bjs_roundtripComplexResult(resultCaseId); + const ret = enumHelpers.ComplexResult.lift(i32Stack.pop()); + return ret; + }, + roundTripOptionalComplexResult: function bjs_roundTripOptionalComplexResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.ComplexResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalComplexResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.ComplexResult.lift(tag); + return optResult; + }, + roundTripOptionalUtilitiesResult: function bjs_roundTripOptionalUtilitiesResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.Result.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalUtilitiesResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.Result.lift(tag); + return optResult; + }, + roundTripOptionalNetworkingResult: function bjs_roundTripOptionalNetworkingResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.NetworkingResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalNetworkingResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.NetworkingResult.lift(tag); + return optResult; + }, + roundTripOptionalAPIOptionalResult: function bjs_roundTripOptionalAPIOptionalResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.APIOptionalResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalAPIOptionalResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.APIOptionalResult.lift(tag); + return optResult; + }, + compareAPIResults: function bjs_compareAPIResults(result1, result2) { + const isSome = result1 != null; + let result; + if (isSome) { + const result1CaseId = enumHelpers.APIOptionalResult.lower(result1); + result = result1CaseId; + } else { + result = 0; + } + const isSome1 = result2 != null; + let result3; + if (isSome1) { + const result2CaseId = enumHelpers.APIOptionalResult.lower(result2); + result3 = result2CaseId; + } else { + result3 = 0; + } + instance.exports.bjs_compareAPIResults(+isSome, result, +isSome1, result3); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.APIOptionalResult.lift(tag); + return optResult; + }, + roundTripTypedPayloadResult: function bjs_roundTripTypedPayloadResult(result) { + const resultCaseId = enumHelpers.TypedPayloadResult.lower(result); + instance.exports.bjs_roundTripTypedPayloadResult(resultCaseId); + const ret = enumHelpers.TypedPayloadResult.lift(i32Stack.pop()); + return ret; + }, + roundTripOptionalTypedPayloadResult: function bjs_roundTripOptionalTypedPayloadResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.TypedPayloadResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalTypedPayloadResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.TypedPayloadResult.lift(tag); + return optResult; + }, + roundTripAllTypesResult: function bjs_roundTripAllTypesResult(result) { + const resultCaseId = enumHelpers.AllTypesResult.lower(result); + instance.exports.bjs_roundTripAllTypesResult(resultCaseId); + const ret = enumHelpers.AllTypesResult.lift(i32Stack.pop()); + return ret; + }, + roundTripOptionalAllTypesResult: function bjs_roundTripOptionalAllTypesResult(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.AllTypesResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalAllTypesResult(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.AllTypesResult.lift(tag); + return optResult; + }, + roundTripOptionalPayloadResult: function bjs_roundTripOptionalPayloadResult(result) { + const resultCaseId = enumHelpers.OptionalAllTypesResult.lower(result); + instance.exports.bjs_roundTripOptionalPayloadResult(resultCaseId); + const ret = enumHelpers.OptionalAllTypesResult.lift(i32Stack.pop()); + return ret; + }, + roundTripOptionalPayloadResultOpt: function bjs_roundTripOptionalPayloadResultOpt(result) { + const isSome = result != null; + let result1; + if (isSome) { + const resultCaseId = enumHelpers.OptionalAllTypesResult.lower(result); + result1 = resultCaseId; + } else { + result1 = 0; + } + instance.exports.bjs_roundTripOptionalPayloadResultOpt(+isSome, result1); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.OptionalAllTypesResult.lift(tag); + return optResult; + }, + APIResult: APIResultValues, + ComplexResult: ComplexResultValues, + APIOptionalResult: APIOptionalResultValues, + Precision: PrecisionValues, + CardinalDirection: CardinalDirectionValues, + TypedPayloadResult: TypedPayloadResultValues, + AllTypesResult: AllTypesResultValues, + OptionalAllTypesResult: OptionalAllTypesResultValues, + API: { + NetworkingResult: NetworkingResultValues, + }, + Utilities: { + Result: ResultValues, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts similarity index 90% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts index 47fb52d94..5581df31e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts @@ -42,9 +42,9 @@ export type Exports = { getDirection(): DirectionTag; processDirection(input: DirectionTag): StatusTag; roundTripOptionalDirection(input: DirectionTag | null): DirectionTag | null; - setTSDirection(direction: TSDirectionTag): void; - getTSDirection(): TSDirectionTag; - roundTripOptionalTSDirection(input: TSDirectionTag | null): TSDirectionTag | null; + setTSDirection(direction: TSDirection): void; + getTSDirection(): TSDirection; + roundTripOptionalTSDirection(input: TSDirection | null): TSDirection | null; Direction: DirectionObject Status: StatusObject PublicStatus: PublicStatusObject diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js similarity index 87% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 89a0f0897..0ea2b0a53 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -42,20 +42,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -72,6 +66,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -93,47 +88,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -225,6 +207,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { instance = i; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts index 4261ca3bb..be77e759c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -58,6 +58,15 @@ declare global { } } } + namespace Services { + namespace Graph { + namespace GraphOperations { + function createGraph(rootId: number): number; + function nodeCount(graphId: number): number; + function validate(graphId: number): boolean; + } + } + } namespace Utils { class Converter { constructor(); @@ -103,6 +112,15 @@ export type Exports = { }, }, }, + Services: { + Graph: { + GraphOperations: { + createGraph(rootId: number): number; + nodeCount(graphId: number): number; + validate(graphId: number): boolean; + }, + }, + }, Utils: { Converter: { new(): Converter; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js similarity index 76% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 77c327e8d..a5f97641c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -62,20 +62,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -92,6 +86,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -113,47 +108,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -245,20 +227,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { - const obj = Converter.__construct(pointer); + const obj = _exports['Converter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_HTTPServer_wrap"] = function(pointer) { - const obj = HTTPServer.__construct(pointer); + const obj = _exports['HTTPServer'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_TestServer_wrap"] = function(pointer) { - const obj = TestServer.__construct(pointer); + const obj = _exports['TestServer'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -273,30 +256,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Converter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); } - + constructor() { const ret = instance.exports.bjs_Converter_init(); return Converter.__construct(ret); @@ -312,7 +305,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_HTTPServer_deinit, HTTPServer.prototype); } - + constructor() { const ret = instance.exports.bjs_HTTPServer_init(); return HTTPServer.__construct(ret); @@ -325,7 +318,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestServer_deinit, TestServer.prototype); } - + constructor() { const ret = instance.exports.bjs_TestServer_init(); return TestServer.__construct(ret); @@ -349,6 +342,15 @@ export async function createInstantiator(options, swift) { if (typeof globalThis.Networking.APIV2.Internal === 'undefined') { globalThis.Networking.APIV2.Internal = {}; } + if (typeof globalThis.Services === 'undefined') { + globalThis.Services = {}; + } + if (typeof globalThis.Services.Graph === 'undefined') { + globalThis.Services.Graph = {}; + } + if (typeof globalThis.Services.Graph.GraphOperations === 'undefined') { + globalThis.Services.Graph.GraphOperations = {}; + } if (typeof globalThis.Utils === 'undefined') { globalThis.Utils = {}; } @@ -369,6 +371,30 @@ export async function createInstantiator(options, swift) { }, }, }, + Services: { + Graph: { + GraphOperations: { + createGraph: function bjs_Services_Graph_GraphOperations_static_createGraph(rootId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_createGraph(rootId); + return ret; + }, + nodeCount: function bjs_Services_Graph_GraphOperations_static_nodeCount(graphId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_nodeCount(graphId); + return ret; + }, + validate: function bjs_Services_Graph_GraphOperations_static_validate(graphId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_validate(graphId); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret !== 0; + }, + }, + }, + }, Utils: { Converter, }, @@ -377,6 +403,9 @@ export async function createInstantiator(options, swift) { globalThis.Utils.Converter = exports.Utils.Converter; globalThis.Networking.API.HTTPServer = exports.Networking.API.HTTPServer; globalThis.Networking.APIV2.Internal.TestServer = exports.Networking.APIV2.Internal.TestServer; + globalThis.Services.Graph.GraphOperations.createGraph = exports.Services.Graph.GraphOperations.createGraph; + globalThis.Services.Graph.GraphOperations.nodeCount = exports.Services.Graph.GraphOperations.nodeCount; + globalThis.Services.Graph.GraphOperations.validate = exports.Services.Graph.GraphOperations.validate; return exports; }, } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts similarity index 92% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index b8b92d14e..a6934d6e7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -84,6 +84,15 @@ export type Exports = { }, }, }, + Services: { + Graph: { + GraphOperations: { + createGraph(rootId: number): number; + nodeCount(graphId: number): number; + validate(graphId: number): boolean; + }, + }, + }, Utils: { Converter: { new(): Converter; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js similarity index 77% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index b01148873..a30709cbb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -43,20 +43,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -73,6 +67,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -94,47 +89,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -226,20 +208,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { - const obj = Converter.__construct(pointer); + const obj = _exports['Converter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_HTTPServer_wrap"] = function(pointer) { - const obj = HTTPServer.__construct(pointer); + const obj = _exports['HTTPServer'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_TestServer_wrap"] = function(pointer) { - const obj = TestServer.__construct(pointer); + const obj = _exports['TestServer'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -254,30 +237,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Converter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); } - + constructor() { const ret = instance.exports.bjs_Converter_init(); return Converter.__construct(ret); @@ -293,7 +286,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_HTTPServer_deinit, HTTPServer.prototype); } - + constructor() { const ret = instance.exports.bjs_HTTPServer_init(); return HTTPServer.__construct(ret); @@ -306,7 +299,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestServer_deinit, TestServer.prototype); } - + constructor() { const ret = instance.exports.bjs_TestServer_init(); return TestServer.__construct(ret); @@ -332,6 +325,30 @@ export async function createInstantiator(options, swift) { }, }, }, + Services: { + Graph: { + GraphOperations: { + createGraph: function bjs_Services_Graph_GraphOperations_static_createGraph(rootId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_createGraph(rootId); + return ret; + }, + nodeCount: function bjs_Services_Graph_GraphOperations_static_nodeCount(graphId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_nodeCount(graphId); + return ret; + }, + validate: function bjs_Services_Graph_GraphOperations_static_validate(graphId) { + const ret = instance.exports.bjs_Services_Graph_GraphOperations_static_validate(graphId); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret !== 0; + }, + }, + }, + }, Utils: { Converter, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts similarity index 92% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts index d321b99fb..50a45a58d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts @@ -113,18 +113,18 @@ export type Exports = { setTheme(theme: ThemeTag): void; getTheme(): ThemeTag; roundTripOptionalTheme(input: ThemeTag | null): ThemeTag | null; - setTSTheme(theme: TSThemeTag): void; - getTSTheme(): TSThemeTag; - roundTripOptionalTSTheme(input: TSThemeTag | null): TSThemeTag | null; + setTSTheme(theme: TSTheme): void; + getTSTheme(): TSTheme; + roundTripOptionalTSTheme(input: TSTheme | null): TSTheme | null; setFeatureFlag(flag: FeatureFlagTag): void; getFeatureFlag(): FeatureFlagTag; roundTripOptionalFeatureFlag(input: FeatureFlagTag | null): FeatureFlagTag | null; setHttpStatus(status: HttpStatusTag): void; getHttpStatus(): HttpStatusTag; roundTripOptionalHttpStatus(input: HttpStatusTag | null): HttpStatusTag | null; - setTSHttpStatus(status: TSHttpStatusTag): void; - getTSHttpStatus(): TSHttpStatusTag; - roundTripOptionalHttpStatus(input: TSHttpStatusTag | null): TSHttpStatusTag | null; + setTSHttpStatus(status: TSHttpStatus): void; + getTSHttpStatus(): TSHttpStatus; + roundTripOptionalHttpStatus(input: TSHttpStatus | null): TSHttpStatus | null; setPriority(priority: PriorityTag): void; getPriority(): PriorityTag; roundTripOptionalPriority(input: PriorityTag | null): PriorityTag | null; @@ -161,6 +161,8 @@ export type Exports = { Ratio: RatioObject } export type Imports = { + takesFeatureFlag(flag: FeatureFlagTag): void; + returnsFeatureFlag(): FeatureFlagTag; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js similarity index 84% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index c1865adfc..efd75f1fa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -93,20 +93,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -117,12 +111,14 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); tmpRetString = textDecoder.decode(bytes); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -144,47 +140,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -276,6 +259,26 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flag) { + try { + const flagObject = swift.memory.getObject(flag); + swift.memory.release(flag); + imports.takesFeatureFlag(flagObject); + } catch (error) { + setException(error); + } + } + TestModule["bjs_returnsFeatureFlag"] = function bjs_returnsFeatureFlag() { + try { + let ret = imports.returnsFeatureFlag(); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; @@ -293,7 +296,6 @@ export async function createInstantiator(options, swift) { const themeBytes = textEncoder.encode(theme); const themeId = swift.memory.retain(themeBytes); instance.exports.bjs_setTheme(themeId, themeBytes.length); - swift.memory.release(themeId); }, getTheme: function bjs_getTheme() { instance.exports.bjs_getTheme(); @@ -303,24 +305,25 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalTheme: function bjs_roundTripOptionalTheme(input) { const isSome = input != null; - let inputId, inputBytes; + let result, result1; if (isSome) { - inputBytes = textEncoder.encode(input); - inputId = swift.memory.retain(inputBytes); + const inputBytes = textEncoder.encode(input); + const inputId = swift.memory.retain(inputBytes); + result = inputId; + result1 = inputBytes.length; + } else { + result = 0; + result1 = 0; } - instance.exports.bjs_roundTripOptionalTheme(+isSome, isSome ? inputId : 0, isSome ? inputBytes.length : 0); + instance.exports.bjs_roundTripOptionalTheme(+isSome, result, result1); const optResult = tmpRetString; tmpRetString = undefined; - if (inputId != undefined) { - swift.memory.release(inputId); - } return optResult; }, setTSTheme: function bjs_setTSTheme(theme) { const themeBytes = textEncoder.encode(theme); const themeId = swift.memory.retain(themeBytes); instance.exports.bjs_setTSTheme(themeId, themeBytes.length); - swift.memory.release(themeId); }, getTSTheme: function bjs_getTSTheme() { instance.exports.bjs_getTSTheme(); @@ -330,31 +333,47 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalTSTheme: function bjs_roundTripOptionalTSTheme(input) { const isSome = input != null; - let inputId, inputBytes; + let result, result1; if (isSome) { - inputBytes = textEncoder.encode(input); - inputId = swift.memory.retain(inputBytes); + const inputBytes = textEncoder.encode(input); + const inputId = swift.memory.retain(inputBytes); + result = inputId; + result1 = inputBytes.length; + } else { + result = 0; + result1 = 0; } - instance.exports.bjs_roundTripOptionalTSTheme(+isSome, isSome ? inputId : 0, isSome ? inputBytes.length : 0); + instance.exports.bjs_roundTripOptionalTSTheme(+isSome, result, result1); const optResult = tmpRetString; tmpRetString = undefined; - if (inputId != undefined) { - swift.memory.release(inputId); - } return optResult; }, setFeatureFlag: function bjs_setFeatureFlag(flag) { - instance.exports.bjs_setFeatureFlag(flag); + const flagBytes = textEncoder.encode(flag); + const flagId = swift.memory.retain(flagBytes); + instance.exports.bjs_setFeatureFlag(flagId, flagBytes.length); }, getFeatureFlag: function bjs_getFeatureFlag() { - const ret = instance.exports.bjs_getFeatureFlag(); - return ret !== 0; + instance.exports.bjs_getFeatureFlag(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; }, roundTripOptionalFeatureFlag: function bjs_roundTripOptionalFeatureFlag(input) { const isSome = input != null; - instance.exports.bjs_roundTripOptionalFeatureFlag(+isSome, isSome ? input : 0); - const optResult = tmpRetOptionalBool; - tmpRetOptionalBool = undefined; + let result, result1; + if (isSome) { + const inputBytes = textEncoder.encode(input); + const inputId = swift.memory.retain(inputBytes); + result = inputId; + result1 = inputBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripOptionalFeatureFlag(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; return optResult; }, setHttpStatus: function bjs_setHttpStatus(status) { @@ -464,7 +483,7 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalPrecision: function bjs_roundTripOptionalPrecision(input) { const isSome = input != null; - instance.exports.bjs_roundTripOptionalPrecision(+isSome, isSome ? input : 0); + instance.exports.bjs_roundTripOptionalPrecision(+isSome, isSome ? input : 0.0); const optResult = tmpRetOptionalFloat; tmpRetOptionalFloat = undefined; return optResult; @@ -478,7 +497,7 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalRatio: function bjs_roundTripOptionalRatio(input) { const isSome = input != null; - instance.exports.bjs_roundTripOptionalRatio(+isSome, isSome ? input : 0); + instance.exports.bjs_roundTripOptionalRatio(+isSome, isSome ? input : 0.0); const optResult = tmpRetOptionalDouble; tmpRetOptionalDouble = undefined; return optResult; @@ -487,7 +506,6 @@ export async function createInstantiator(options, swift) { const themeBytes = textEncoder.encode(theme); const themeId = swift.memory.retain(themeBytes); const ret = instance.exports.bjs_processTheme(themeId, themeBytes.length); - swift.memory.release(themeId); return ret; }, convertPriority: function bjs_convertPriority(status) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.ImportMacros.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.ImportMacros.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.ImportMacros.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.ImportMacros.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index b3b809476..21613733e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.ImportMacros.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +184,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_console_get"] = function bjs_console_get() { try { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.ImportMacros.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.ImportMacros.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.ImportMacros.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js similarity index 87% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.ImportMacros.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 35a3d76ec..21296b88a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.ImportMacros.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,6 +183,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_console_get"] = function bjs_console_get() { try { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts index 5442ebfa2..5d1e2c4dc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts @@ -7,7 +7,8 @@ export type Exports = { } export type Imports = { - check(a: number, b: boolean): void; + roundtrip(items: number[]): number[]; + logStrings(items: string[]): void; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js similarity index 81% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index e3263af05..2a2fd3d50 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,23 +184,38 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_checkNumber"] = function bjs_checkNumber() { + TestModule["bjs_roundtrip"] = function bjs_roundtrip() { try { - let ret = imports.checkNumber(); - return ret; + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + let ret = imports.roundtrip(arrayResult); + for (const elem of ret) { + i32Stack.push((elem | 0)); + } + i32Stack.push(ret.length); } catch (error) { setException(error); - return 0 } } - TestModule["bjs_checkBoolean"] = function bjs_checkBoolean() { + TestModule["bjs_logStrings"] = function bjs_logStrings() { try { - let ret = imports.checkBoolean(); - return ret ? 1 : 0; + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const string = strStack.pop(); + arrayResult.push(string); + } + arrayResult.reverse(); + imports.logStrings(arrayResult); } catch (error) { setException(error); - return 0 } } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts similarity index 70% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts index 654b4bc04..22b4e6a1c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts @@ -4,10 +4,17 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export interface FooContainer { + foo: Foo; + optionalFoo: Foo | null; +} export interface Foo { } export type Exports = { makeFoo(): Foo; + processFooArray(foos: Foo[]): Foo[]; + processOptionalFooArray(foos: (Foo | null)[]): (Foo | null)[]; + roundtripFooContainer(container: FooContainer): FooContainer; } export type Imports = { Foo: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js similarity index 60% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 094c2241d..c0c9704ef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -18,22 +18,66 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; + const __bjs_createFooContainerHelpers = () => ({ + lower: (value) => { + let id; + if (value.foo != null) { + id = swift.memory.retain(value.foo); + } else { + id = undefined; + } + i32Stack.push(id !== undefined ? id : 0); + const isSome = value.optionalFoo != null; + if (isSome) { + let id1; + if (value.optionalFoo != null) { + id1 = swift.memory.retain(value.optionalFoo); + } else { + id1 = undefined; + } + i32Stack.push(id1 !== undefined ? id1 : 0); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const objectId = i32Stack.pop(); + let value; + if (objectId !== 0) { + value = swift.memory.getObject(objectId); + swift.memory.release(objectId); + } else { + value = null; + } + optional = value; + } else { + optional = null; + } + const objectId1 = i32Stack.pop(); + let value1; + if (objectId1 !== 0) { + value1 = swift.memory.getObject(objectId1); + swift.memory.release(objectId1); + } else { + value1 = null; + } + return { foo: value1, optionalFoo: optional }; + } + }); return { /** @@ -49,6 +93,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +115,41 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); + } + bjs["swift_js_struct_lower_FooContainer"] = function(objectId) { + structHelpers.FooContainer.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_FooContainer"] = function() { + const value = structHelpers.FooContainer.lift(); + return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +241,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_Foo_init"] = function bjs_Foo_init() { try { @@ -223,6 +263,9 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const FooContainerHelpers = __bjs_createFooContainerHelpers(); + structHelpers.FooContainer = FooContainerHelpers; + const exports = { makeFoo: function bjs_makeFoo() { const ret = instance.exports.bjs_makeFoo(); @@ -236,6 +279,61 @@ export async function createInstantiator(options, swift) { } return ret1; }, + processFooArray: function bjs_processFooArray(foos) { + for (const elem of foos) { + const objId = swift.memory.retain(elem); + i32Stack.push(objId); + } + i32Stack.push(foos.length); + instance.exports.bjs_processFooArray(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const objId1 = i32Stack.pop(); + const obj = swift.memory.getObject(objId1); + swift.memory.release(objId1); + arrayResult.push(obj); + } + arrayResult.reverse(); + return arrayResult; + }, + processOptionalFooArray: function bjs_processOptionalFooArray(foos) { + for (const elem of foos) { + const isSome = elem != null ? 1 : 0; + if (isSome) { + const objId = swift.memory.retain(elem); + i32Stack.push(objId); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome); + } + i32Stack.push(foos.length); + instance.exports.bjs_processOptionalFooArray(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const isSome1 = i32Stack.pop(); + let optValue; + if (isSome1 === 0) { + optValue = null; + } else { + const objId1 = i32Stack.pop(); + const obj = swift.memory.getObject(objId1); + swift.memory.release(objId1); + optValue = obj; + } + arrayResult.push(optValue); + } + arrayResult.reverse(); + return arrayResult; + }, + roundtripFooContainer: function bjs_roundtripFooContainer(container) { + structHelpers.FooContainer.lower(container); + instance.exports.bjs_roundtripFooContainer(); + const structValue = structHelpers.FooContainer.lift(); + return structValue; + }, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.d.ts deleted file mode 100644 index ccd371b71..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// 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 Animatable { - animate(keyframes: any, options: any): any; - getAnimations(options: any): any; -} -export type Exports = { -} -export type Imports = { - returnAnimatable(): Animatable; -} -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/InvalidPropertyNames.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts index 2efd24317..ac0e05a91 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts @@ -4,10 +4,6 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -export interface ArrayBufferLike { - slice(begin: number, end: number): ArrayBufferLike; - readonly byteLength: number; -} export interface WeirdNaming { as(): void; try(): void; @@ -26,7 +22,6 @@ export interface _Weird { export type Exports = { } export type Imports = { - createArrayBuffer(): ArrayBufferLike; createWeirdObject(): WeirdNaming; createWeirdClass(): _Weird; _Weird: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 833436226..eabfe8c13 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,16 +184,8 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_createArrayBuffer"] = function bjs_createArrayBuffer() { - try { - let ret = imports.createArrayBuffer(); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } TestModule["bjs_createWeirdObject"] = function bjs_createWeirdObject() { try { let ret = imports.createWeirdObject(); @@ -230,24 +204,6 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_ArrayBufferLike_byteLength_get"] = function bjs_ArrayBufferLike_byteLength_get(self) { - try { - let ret = swift.memory.getObject(self).byteLength; - return ret; - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_ArrayBufferLike_slice"] = function bjs_ArrayBufferLike_slice(self, begin, end) { - try { - let ret = swift.memory.getObject(self).slice(begin, end); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } TestModule["bjs_WeirdNaming_normalProperty_get"] = function bjs_WeirdNaming_normalProperty_get(self) { try { let ret = swift.memory.getObject(self).normalProperty; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts similarity index 81% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts index 24d3d8fac..aaf227cf7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts @@ -10,9 +10,14 @@ export interface Greeter { name: string; readonly age: number; } +export interface Animatable { + animate(keyframes: any, options: any): any; + getAnimations(options: any): any; +} export type Exports = { } export type Imports = { + returnAnimatable(): Animatable; Greeter: { new(name: string): Greeter; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js similarity index 84% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index d83919051..d84c77d45 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeScriptClass.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,7 +184,17 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_returnAnimatable"] = function bjs_returnAnimatable() { + try { + let ret = imports.returnAnimatable(); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } TestModule["bjs_Greeter_init"] = function bjs_Greeter_init(name) { try { const nameObject = swift.memory.getObject(name); @@ -258,6 +250,24 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_Animatable_animate"] = function bjs_Animatable_animate(self, keyframes, options) { + try { + let ret = swift.memory.getObject(self).animate(swift.memory.getObject(keyframes), swift.memory.getObject(options)); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_Animatable_getAnimations"] = function bjs_Animatable_getAnimations(self, options) { + try { + let ret = swift.memory.getObject(self).getAnimations(swift.memory.getObject(options)); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } }, setInstance: (i) => { instance = i; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts similarity index 60% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts index db6d2be05..3b2b5de99 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts @@ -4,15 +4,23 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -export interface JsGreeter { - greet(): string; +export interface StaticBox { + value(): number; +} +export interface WithCtor { } export type Exports = { } export type Imports = { - jsRoundTripNumber(v: number): number; - JsGreeter: { - new(name: string): JsGreeter; + StaticBox: { + create(value: number): StaticBox; + value(): number; + makeDefault(): StaticBox; + "with-dashes"(): StaticBox; + } + WithCtor: { + new(value: number): WithCtor; + create(value: number): WithCtor; } } export function createInstantiator(options: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js similarity index 76% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index 1d25a2954..6912af0f3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Interface.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,28 +184,64 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_returnAnimatable"] = function bjs_returnAnimatable() { + TestModule["bjs_StaticBox_create_static"] = function bjs_StaticBox_create_static(value) { + try { + let ret = imports.StaticBox.create(value); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_StaticBox_value_static"] = function bjs_StaticBox_value_static() { + try { + let ret = imports.StaticBox.value(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_StaticBox_makeDefault_static"] = function bjs_StaticBox_makeDefault_static() { try { - let ret = imports.returnAnimatable(); + let ret = imports.StaticBox.makeDefault(); return swift.memory.retain(ret); } catch (error) { setException(error); return 0 } } - TestModule["bjs_Animatable_animate"] = function bjs_Animatable_animate(self, keyframes, options) { + TestModule["bjs_StaticBox_dashed_static"] = function bjs_StaticBox_dashed_static() { try { - let ret = swift.memory.getObject(self).animate(swift.memory.getObject(keyframes), swift.memory.getObject(options)); + let ret = imports.StaticBox["with-dashes"](); return swift.memory.retain(ret); } catch (error) { setException(error); return 0 } } - TestModule["bjs_Animatable_getAnimations"] = function bjs_Animatable_getAnimations(self, options) { + TestModule["bjs_StaticBox_value"] = function bjs_StaticBox_value(self) { + try { + let ret = swift.memory.getObject(self).value(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_WithCtor_init"] = function bjs_WithCtor_init(value) { + try { + return swift.memory.retain(new imports.WithCtor(value)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_WithCtor_create_static"] = function bjs_WithCtor_create_static(value) { try { - let ret = swift.memory.getObject(self).getAnimations(swift.memory.getObject(options)); + let ret = imports.WithCtor.create(value); return swift.memory.retain(ret); } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts new file mode 100644 index 000000000..f4c13c610 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts @@ -0,0 +1,40 @@ +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +/// 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 JSValueHolder extends SwiftHeapObject { + update(value: any, optionalValue: any | null): void; + echo(value: any): any; + echoOptional(value: any | null): any | null; + value: any; + optionalValue: any | null; +} +export type Exports = { + JSValueHolder: { + new(value: any, optionalValue: any | null): JSValueHolder; + } + roundTripJSValue(value: any): any; + roundTripOptionalJSValue(value: any | null): any | null; + roundTripJSValueArray(values: any[]): any[]; + roundTripOptionalJSValueArray(values: any[] | null): any[] | null; +} +export type Imports = { + jsEchoJSValue(value: any): any; + jsEchoJSValueArray(values: any[]): any[]; +} +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/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js new file mode 100644 index 000000000..8571bbd6c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -0,0 +1,576 @@ +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); + bjs["swift_js_return_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + return swift.memory.retain(textDecoder.decode(bytes)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + const value = textDecoder.decode(bytes); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_JSValueHolder_wrap"] = function(pointer) { + const obj = _exports['JSValueHolder'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_jsEchoJSValue"] = function bjs_jsEchoJSValue(valueKind, valuePayload1, valuePayload2) { + try { + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + let ret = imports.jsEchoJSValue(jsValue); + const [retKind, retPayload1, retPayload2] = __bjs_jsValueLower(ret); + i32Stack.push(retKind); + i32Stack.push(retPayload1); + f64Stack.push(retPayload2); + } catch (error) { + setException(error); + } + } + TestModule["bjs_jsEchoJSValueArray"] = function bjs_jsEchoJSValueArray() { + try { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + arrayResult.push(jsValue); + } + arrayResult.reverse(); + let ret = imports.jsEchoJSValueArray(arrayResult); + for (const elem of ret) { + const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); + i32Stack.push(elemKind); + i32Stack.push(elemPayload1); + f64Stack.push(elemPayload2); + } + i32Stack.push(ret.length); + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class JSValueHolder extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_JSValueHolder_deinit, JSValueHolder.prototype); + } + + constructor(value, optionalValue) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + const isSome = optionalValue != null; + let result, result1, result2; + if (isSome) { + const [optionalValueKind, optionalValuePayload1, optionalValuePayload2] = __bjs_jsValueLower(optionalValue); + result = optionalValueKind; + result1 = optionalValuePayload1; + result2 = optionalValuePayload2; + } else { + result = 0; + result1 = 0; + result2 = 0.0; + } + const ret = instance.exports.bjs_JSValueHolder_init(valueKind, valuePayload1, valuePayload2, +isSome, result, result1, result2); + return JSValueHolder.__construct(ret); + } + update(value, optionalValue) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + const isSome = optionalValue != null; + let result, result1, result2; + if (isSome) { + const [optionalValueKind, optionalValuePayload1, optionalValuePayload2] = __bjs_jsValueLower(optionalValue); + result = optionalValueKind; + result1 = optionalValuePayload1; + result2 = optionalValuePayload2; + } else { + result = 0; + result1 = 0; + result2 = 0.0; + } + instance.exports.bjs_JSValueHolder_update(this.pointer, valueKind, valuePayload1, valuePayload2, +isSome, result, result1, result2); + } + echo(value) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + instance.exports.bjs_JSValueHolder_echo(this.pointer, valueKind, valuePayload1, valuePayload2); + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + } + echoOptional(value) { + const isSome = value != null; + let result, result1, result2; + if (isSome) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + result = valueKind; + result1 = valuePayload1; + result2 = valuePayload2; + } else { + result = 0; + result1 = 0; + result2 = 0.0; + } + instance.exports.bjs_JSValueHolder_echoOptional(this.pointer, +isSome, result, result1, result2); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + optResult = jsValue; + } else { + optResult = null; + } + return optResult; + } + get value() { + instance.exports.bjs_JSValueHolder_value_get(this.pointer); + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + } + set value(value) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + instance.exports.bjs_JSValueHolder_value_set(this.pointer, valueKind, valuePayload1, valuePayload2); + } + get optionalValue() { + instance.exports.bjs_JSValueHolder_optionalValue_get(this.pointer); + const isSome = i32Stack.pop(); + let optResult; + if (isSome) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + optResult = jsValue; + } else { + optResult = null; + } + return optResult; + } + set optionalValue(value) { + const isSome = value != null; + let result, result1, result2; + if (isSome) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + result = valueKind; + result1 = valuePayload1; + result2 = valuePayload2; + } else { + result = 0; + result1 = 0; + result2 = 0.0; + } + instance.exports.bjs_JSValueHolder_optionalValue_set(this.pointer, +isSome, result, result1, result2); + } + } + const exports = { + JSValueHolder, + roundTripJSValue: function bjs_roundTripJSValue(value) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + instance.exports.bjs_roundTripJSValue(valueKind, valuePayload1, valuePayload2); + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + roundTripOptionalJSValue: function bjs_roundTripOptionalJSValue(value) { + const isSome = value != null; + let result, result1, result2; + if (isSome) { + const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); + result = valueKind; + result1 = valuePayload1; + result2 = valuePayload2; + } else { + result = 0; + result1 = 0; + result2 = 0.0; + } + instance.exports.bjs_roundTripOptionalJSValue(+isSome, result, result1, result2); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + optResult = jsValue; + } else { + optResult = null; + } + return optResult; + }, + roundTripJSValueArray: function bjs_roundTripJSValueArray(values) { + for (const elem of values) { + const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); + i32Stack.push(elemKind); + i32Stack.push(elemPayload1); + f64Stack.push(elemPayload2); + } + i32Stack.push(values.length); + instance.exports.bjs_roundTripJSValueArray(); + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + arrayResult.push(jsValue); + } + arrayResult.reverse(); + return arrayResult; + }, + roundTripOptionalJSValueArray: function bjs_roundTripOptionalJSValueArray(values) { + const isSome = values != null; + if (isSome) { + for (const elem of values) { + const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); + i32Stack.push(elemKind); + i32Stack.push(elemPayload1); + f64Stack.push(elemPayload2); + } + i32Stack.push(values.length); + } + i32Stack.push(+isSome); + instance.exports.bjs_roundTripOptionalJSValueArray(); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const arrayLen = i32Stack.pop(); + const arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + arrayResult.push(jsValue); + } + arrayResult.reverse(); + optResult = arrayResult; + } else { + optResult = null; + } + return optResult; + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js similarity index 83% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index f079de1da..457661b6c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,12 +183,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_GlobalClass_wrap"] = function(pointer) { - const obj = GlobalClass.__construct(pointer); + const obj = _exports['GlobalClass'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -221,30 +204,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalClass_deinit, GlobalClass.prototype); } - + constructor() { const ret = instance.exports.bjs_GlobalClass_init(); return GlobalClass.__construct(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts similarity index 96% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts index 67a6eebcf..6f18e53ed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts @@ -12,7 +12,7 @@ declare global { constructor(); greet(): string; } - globalFunction(): string; + function globalFunction(): string; } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 2c43b91e8..6c0c5ad9c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,12 +183,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: GlobalModule if (!importObject["GlobalModule"]) { importObject["GlobalModule"] = {}; } importObject["GlobalModule"]["bjs_GlobalClass_wrap"] = function(pointer) { - const obj = GlobalClass.__construct(pointer); + const obj = _exports['GlobalClass'].__construct(pointer); return swift.memory.retain(obj); }; // Wrapper functions for module: PrivateModule @@ -214,7 +197,7 @@ export async function createInstantiator(options, swift) { importObject["PrivateModule"] = {}; } importObject["PrivateModule"]["bjs_PrivateClass_wrap"] = function(pointer) { - const obj = PrivateClass.__construct(pointer); + const obj = _exports['PrivateClass'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -229,30 +212,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class GlobalClass extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GlobalClass_deinit, GlobalClass.prototype); } - + constructor() { const ret = instance.exports.bjs_GlobalClass_init(); return GlobalClass.__construct(ret); @@ -268,7 +261,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateClass_deinit, PrivateClass.prototype); } - + constructor() { const ret = instance.exports.bjs_PrivateClass_init(); return PrivateClass.__construct(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js similarity index 83% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 4b8ce8a66..a576e82b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,12 +183,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_PrivateClass_wrap"] = function(pointer) { - const obj = PrivateClass.__construct(pointer); + const obj = _exports['PrivateClass'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -221,30 +204,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class PrivateClass extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PrivateClass_deinit, PrivateClass.prototype); } - + constructor() { const ret = instance.exports.bjs_PrivateClass_init(); return PrivateClass.__construct(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MultipleImportedTypes.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MultipleImportedTypes.Import.d.ts deleted file mode 100644 index 83fe3c141..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MultipleImportedTypes.Import.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// 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 DatabaseConnection { - connect(url: string): void; - execute(query: string): any; - readonly isConnected: boolean; - connectionTimeout: number; -} -export interface Logger { - log(message: string): void; - error(message: string, error: any): void; - readonly level: string; -} -export interface ConfigManager { - get(key: string): any; - set(key: string, value: any): void; - readonly configPath: string; -} -export type Exports = { -} -export type Imports = { - createDatabaseConnection(config: any): DatabaseConnection; - createLogger(level: string): Logger; - getConfigManager(): ConfigManager; -} -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/MultipleImportedTypes.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MultipleImportedTypes.Import.js deleted file mode 100644 index f8cfd7366..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MultipleImportedTypes.Import.js +++ /dev/null @@ -1,354 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_createDatabaseConnection"] = function bjs_createDatabaseConnection(config) { - try { - let ret = imports.createDatabaseConnection(swift.memory.getObject(config)); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_createLogger"] = function bjs_createLogger(level) { - try { - const levelObject = swift.memory.getObject(level); - swift.memory.release(level); - let ret = imports.createLogger(levelObject); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_getConfigManager"] = function bjs_getConfigManager() { - try { - let ret = imports.getConfigManager(); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_DatabaseConnection_isConnected_get"] = function bjs_DatabaseConnection_isConnected_get(self) { - try { - let ret = swift.memory.getObject(self).isConnected; - return ret ? 1 : 0; - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_DatabaseConnection_connectionTimeout_get"] = function bjs_DatabaseConnection_connectionTimeout_get(self) { - try { - let ret = swift.memory.getObject(self).connectionTimeout; - return ret; - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_DatabaseConnection_connectionTimeout_set"] = function bjs_DatabaseConnection_connectionTimeout_set(self, newValue) { - try { - swift.memory.getObject(self).connectionTimeout = newValue; - } catch (error) { - setException(error); - } - } - TestModule["bjs_DatabaseConnection_connect"] = function bjs_DatabaseConnection_connect(self, url) { - try { - const urlObject = swift.memory.getObject(url); - swift.memory.release(url); - swift.memory.getObject(self).connect(urlObject); - } catch (error) { - setException(error); - } - } - TestModule["bjs_DatabaseConnection_execute"] = function bjs_DatabaseConnection_execute(self, query) { - try { - const queryObject = swift.memory.getObject(query); - swift.memory.release(query); - let ret = swift.memory.getObject(self).execute(queryObject); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_Logger_level_get"] = function bjs_Logger_level_get(self) { - try { - let ret = swift.memory.getObject(self).level; - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - TestModule["bjs_Logger_log"] = function bjs_Logger_log(self, message) { - try { - const messageObject = swift.memory.getObject(message); - swift.memory.release(message); - swift.memory.getObject(self).log(messageObject); - } catch (error) { - setException(error); - } - } - TestModule["bjs_Logger_error"] = function bjs_Logger_error(self, message, error) { - try { - const messageObject = swift.memory.getObject(message); - swift.memory.release(message); - swift.memory.getObject(self).error(messageObject, swift.memory.getObject(error)); - } catch (error) { - setException(error); - } - } - TestModule["bjs_ConfigManager_configPath_get"] = function bjs_ConfigManager_configPath_get(self) { - try { - let ret = swift.memory.getObject(self).configPath; - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - TestModule["bjs_ConfigManager_get"] = function bjs_ConfigManager_get(self, key) { - try { - const keyObject = swift.memory.getObject(key); - swift.memory.release(key); - let ret = swift.memory.getObject(self).get(keyObject); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_ConfigManager_set"] = function bjs_ConfigManager_set(self, key, value) { - try { - const keyObject = swift.memory.getObject(key); - swift.memory.release(key); - swift.memory.getObject(self).set(keyObject, swift.memory.getObject(value)); - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts similarity index 97% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index cdf83f36d..77d9cc0e9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -9,7 +9,7 @@ export {}; declare global { namespace MyModule { namespace Utils { - namespacedFunction(): string; + function namespacedFunction(): string; } } namespace Utils { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 671868eab..806697af2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,20 +183,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { - const obj = Converter.__construct(pointer); + const obj = _exports['Converter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { - const obj = Greeter.__construct(pointer); + const obj = _exports['Greeter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_UUID_wrap"] = function(pointer) { - const obj = UUID.__construct(pointer); + const obj = _exports['UUID'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -229,35 +212,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Greeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); } - + constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); - swift.memory.release(nameId); return Greeter.__construct(ret); } greet() { @@ -271,7 +263,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); } - + constructor() { const ret = instance.exports.bjs_Converter_init(); return Converter.__construct(ret); @@ -287,7 +279,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UUID_deinit, UUID.prototype); } - + uuidString() { instance.exports.bjs_UUID_uuidString(this.pointer); const ret = tmpRetString; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index ae7bf7451..1f5366828 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,20 +183,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Converter_wrap"] = function(pointer) { - const obj = Converter.__construct(pointer); + const obj = _exports['Converter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { - const obj = Greeter.__construct(pointer); + const obj = _exports['Greeter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_UUID_wrap"] = function(pointer) { - const obj = UUID.__construct(pointer); + const obj = _exports['UUID'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -229,35 +212,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Greeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); } - + constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); - swift.memory.release(nameId); return Greeter.__construct(ret); } greet() { @@ -271,7 +263,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Converter_deinit, Converter.prototype); } - + constructor() { const ret = instance.exports.bjs_Converter_init(); return Converter.__construct(ret); @@ -287,7 +279,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_UUID_deinit, UUID.prototype); } - + uuidString() { instance.exports.bjs_UUID_uuidString(this.pointer); const ret = tmpRetString; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.js deleted file mode 100644 index 2c08e3d9f..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.js +++ /dev/null @@ -1,532 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - // Wrapper functions for module: TestModule - if (!importObject["TestModule"]) { - importObject["TestModule"] = {}; - } - importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { - const obj = Greeter.__construct(pointer); - return swift.memory.retain(obj); - }; - importObject["TestModule"]["bjs_OptionalPropertyHolder_wrap"] = function(pointer) { - const obj = OptionalPropertyHolder.__construct(pointer); - return swift.memory.retain(obj); - }; - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - /// Represents a Swift heap object like a class instance or an actor instance. - class SwiftHeapObject { - static __wrap(pointer, deinit, prototype) { - const obj = Object.create(prototype); - obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); - return obj; - } - - release() { - this.registry.unregister(this); - this.deinit(this.pointer); - } - } - class Greeter extends SwiftHeapObject { - static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); - } - - constructor(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - const ret = instance.exports.bjs_Greeter_init(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - if (nameId != undefined) { - swift.memory.release(nameId); - } - return Greeter.__construct(ret); - } - greet() { - instance.exports.bjs_Greeter_greet(this.pointer); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - changeName(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_Greeter_changeName(this.pointer, +isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - if (nameId != undefined) { - swift.memory.release(nameId); - } - } - get name() { - instance.exports.bjs_Greeter_name_get(this.pointer); - const optResult = tmpRetString; - tmpRetString = undefined; - return optResult; - } - set name(value) { - const isSome = value != null; - let valueId, valueBytes; - if (isSome) { - valueBytes = textEncoder.encode(value); - valueId = swift.memory.retain(valueBytes); - } - instance.exports.bjs_Greeter_name_set(this.pointer, +isSome, isSome ? valueId : 0, isSome ? valueBytes.length : 0); - if (valueId != undefined) { - swift.memory.release(valueId); - } - } - } - class OptionalPropertyHolder extends SwiftHeapObject { - static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_OptionalPropertyHolder_deinit, OptionalPropertyHolder.prototype); - } - - constructor() { - const ret = instance.exports.bjs_OptionalPropertyHolder_init(); - return OptionalPropertyHolder.__construct(ret); - } - get optionalName() { - instance.exports.bjs_OptionalPropertyHolder_optionalName_get(this.pointer); - const optResult = tmpRetString; - tmpRetString = undefined; - return optResult; - } - set optionalName(value) { - const isSome = value != null; - let valueId, valueBytes; - if (isSome) { - valueBytes = textEncoder.encode(value); - valueId = swift.memory.retain(valueBytes); - } - instance.exports.bjs_OptionalPropertyHolder_optionalName_set(this.pointer, +isSome, isSome ? valueId : 0, isSome ? valueBytes.length : 0); - if (valueId != undefined) { - swift.memory.release(valueId); - } - } - get optionalAge() { - instance.exports.bjs_OptionalPropertyHolder_optionalAge_get(this.pointer); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; - return optResult; - } - set optionalAge(value) { - const isSome = value != null; - instance.exports.bjs_OptionalPropertyHolder_optionalAge_set(this.pointer, +isSome, isSome ? value : 0); - } - get optionalGreeter() { - instance.exports.bjs_OptionalPropertyHolder_optionalGreeter_get(this.pointer); - const pointer = tmpRetOptionalHeapObject; - tmpRetOptionalHeapObject = undefined; - const optResult = pointer === null ? null : Greeter.__construct(pointer); - return optResult; - } - set optionalGreeter(value) { - const isSome = value != null; - instance.exports.bjs_OptionalPropertyHolder_optionalGreeter_set(this.pointer, +isSome, isSome ? value.pointer : 0); - } - } - const exports = { - Greeter, - OptionalPropertyHolder, - roundTripOptionalClass: function bjs_roundTripOptionalClass(value) { - const isSome = value != null; - instance.exports.bjs_roundTripOptionalClass(+isSome, isSome ? value.pointer : 0); - const pointer = tmpRetOptionalHeapObject; - tmpRetOptionalHeapObject = undefined; - const optResult = pointer === null ? null : Greeter.__construct(pointer); - return optResult; - }, - testOptionalPropertyRoundtrip: function bjs_testOptionalPropertyRoundtrip(holder) { - const isSome = holder != null; - instance.exports.bjs_testOptionalPropertyRoundtrip(+isSome, isSome ? holder.pointer : 0); - const pointer = tmpRetOptionalHeapObject; - tmpRetOptionalHeapObject = undefined; - const optResult = pointer === null ? null : OptionalPropertyHolder.__construct(pointer); - return optResult; - }, - roundTripString: function bjs_roundTripString(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripString(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - roundTripInt: function bjs_roundTripInt(value) { - const isSome = value != null; - instance.exports.bjs_roundTripInt(+isSome, isSome ? value : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; - return optResult; - }, - roundTripBool: function bjs_roundTripBool(flag) { - const isSome = flag != null; - instance.exports.bjs_roundTripBool(+isSome, isSome ? flag : 0); - const optResult = tmpRetOptionalBool; - tmpRetOptionalBool = undefined; - return optResult; - }, - roundTripFloat: function bjs_roundTripFloat(number) { - const isSome = number != null; - instance.exports.bjs_roundTripFloat(+isSome, isSome ? number : 0); - const optResult = tmpRetOptionalFloat; - tmpRetOptionalFloat = undefined; - return optResult; - }, - roundTripDouble: function bjs_roundTripDouble(precision) { - const isSome = precision != null; - instance.exports.bjs_roundTripDouble(+isSome, isSome ? precision : 0); - const optResult = tmpRetOptionalDouble; - tmpRetOptionalDouble = undefined; - return optResult; - }, - roundTripSyntax: function bjs_roundTripSyntax(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripSyntax(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - roundTripMixSyntax: function bjs_roundTripMixSyntax(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripMixSyntax(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - roundTripSwiftSyntax: function bjs_roundTripSwiftSyntax(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripSwiftSyntax(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - roundTripMixedSwiftSyntax: function bjs_roundTripMixedSwiftSyntax(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripMixedSwiftSyntax(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - roundTripWithSpaces: function bjs_roundTripWithSpaces(value) { - const isSome = value != null; - instance.exports.bjs_roundTripWithSpaces(+isSome, isSome ? value : 0); - const optResult = tmpRetOptionalDouble; - tmpRetOptionalDouble = undefined; - return optResult; - }, - roundTripAlias: function bjs_roundTripAlias(age) { - const isSome = age != null; - instance.exports.bjs_roundTripAlias(+isSome, isSome ? age : 0); - const optResult = tmpRetOptionalInt; - tmpRetOptionalInt = undefined; - return optResult; - }, - roundTripOptionalAlias: function bjs_roundTripOptionalAlias(name) { - const isSome = name != null; - let nameId, nameBytes; - if (isSome) { - nameBytes = textEncoder.encode(name); - nameId = swift.memory.retain(nameBytes); - } - instance.exports.bjs_roundTripOptionalAlias(+isSome, isSome ? nameId : 0, isSome ? nameBytes.length : 0); - const optResult = tmpRetString; - tmpRetString = undefined; - if (nameId != undefined) { - swift.memory.release(nameId); - } - return optResult; - }, - testMixedOptionals: function bjs_testMixedOptionals(firstName, lastName, age, active) { - const isSome = firstName != null; - let firstNameId, firstNameBytes; - if (isSome) { - firstNameBytes = textEncoder.encode(firstName); - firstNameId = swift.memory.retain(firstNameBytes); - } - const isSome1 = lastName != null; - let lastNameId, lastNameBytes; - if (isSome1) { - lastNameBytes = textEncoder.encode(lastName); - lastNameId = swift.memory.retain(lastNameBytes); - } - const isSome2 = age != null; - instance.exports.bjs_testMixedOptionals(+isSome, isSome ? firstNameId : 0, isSome ? firstNameBytes.length : 0, +isSome1, isSome1 ? lastNameId : 0, isSome1 ? lastNameBytes.length : 0, +isSome2, isSome2 ? age : 0, active); - const optResult = tmpRetString; - tmpRetString = undefined; - if (firstNameId != undefined) { - swift.memory.release(firstNameId); - } - if (lastNameId != undefined) { - swift.memory.release(lastNameId); - } - return optResult; - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts similarity index 68% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index 5f63e9db5..b1a67ccde 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -21,6 +21,24 @@ export interface OptionalPropertyHolder extends SwiftHeapObject { optionalAge: number | null; optionalGreeter: Greeter | null; } +export interface WithOptionalJSClass { + roundTripStringOrNull(value: string | null): string | null; + roundTripStringOrUndefined(value: string | undefined): string | undefined; + roundTripDoubleOrNull(value: number | null): number | null; + roundTripDoubleOrUndefined(value: number | undefined): number | undefined; + roundTripBoolOrNull(value: boolean | null): boolean | null; + roundTripBoolOrUndefined(value: boolean | undefined): boolean | undefined; + roundTripIntOrNull(value: number | null): number | null; + roundTripIntOrUndefined(value: number | undefined): number | undefined; + stringOrNull: string | null; + stringOrUndefined: string | undefined; + doubleOrNull: number | null; + doubleOrUndefined: number | undefined; + boolOrNull: boolean | null; + boolOrUndefined: boolean | undefined; + intOrNull: number | null; + intOrUndefined: number | undefined; +} export type Exports = { Greeter: { new(name: string | null): Greeter; @@ -45,6 +63,9 @@ export type Exports = { testMixedOptionals(firstName: string | null, lastName: string | null, age: number | null, active: boolean): string | null; } export type Imports = { + WithOptionalJSClass: { + new(valueOrNull: string | null, valueOrUndefined: string | undefined): WithOptionalJSClass; + } } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js new file mode 100644 index 000000000..941d66ea9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -0,0 +1,825 @@ +// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, +// DO NOT EDIT. +// +// To update this file, just rebuild your project or run +// `swift package bridge-js`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); + bjs["swift_js_return_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + return swift.memory.retain(textDecoder.decode(bytes)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + const value = textDecoder.decode(bytes); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { + const obj = _exports['Greeter'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_OptionalPropertyHolder_wrap"] = function(pointer) { + const obj = _exports['OptionalPropertyHolder'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_WithOptionalJSClass_init"] = function bjs_WithOptionalJSClass_init(valueOrNullIsSome, valueOrNullObjectId, valueOrUndefinedIsSome, valueOrUndefinedObjectId) { + try { + let optResult; + if (valueOrNullIsSome) { + const valueOrNullObjectIdObject = swift.memory.getObject(valueOrNullObjectId); + swift.memory.release(valueOrNullObjectId); + optResult = valueOrNullObjectIdObject; + } else { + optResult = null; + } + let optResult1; + if (valueOrUndefinedIsSome) { + const valueOrUndefinedObjectIdObject = swift.memory.getObject(valueOrUndefinedObjectId); + swift.memory.release(valueOrUndefinedObjectId); + optResult1 = valueOrUndefinedObjectIdObject; + } else { + optResult1 = undefined; + } + return swift.memory.retain(new imports.WithOptionalJSClass(optResult, optResult1)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_WithOptionalJSClass_stringOrNull_get"] = function bjs_WithOptionalJSClass_stringOrNull_get(self) { + try { + let ret = swift.memory.getObject(self).stringOrNull; + const isSome = ret != null; + tmpRetString = isSome ? ret : null; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_stringOrUndefined_get"] = function bjs_WithOptionalJSClass_stringOrUndefined_get(self) { + try { + let ret = swift.memory.getObject(self).stringOrUndefined; + const isSome = ret !== undefined; + tmpRetString = isSome ? ret : undefined; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_doubleOrNull_get"] = function bjs_WithOptionalJSClass_doubleOrNull_get(self) { + try { + let ret = swift.memory.getObject(self).doubleOrNull; + const isSome = ret != null; + bjs["swift_js_return_optional_double"](isSome ? 1 : 0, isSome ? ret : 0.0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_doubleOrUndefined_get"] = function bjs_WithOptionalJSClass_doubleOrUndefined_get(self) { + try { + let ret = swift.memory.getObject(self).doubleOrUndefined; + const isSome = ret !== undefined; + bjs["swift_js_return_optional_double"](isSome ? 1 : 0, isSome ? ret : 0.0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_boolOrNull_get"] = function bjs_WithOptionalJSClass_boolOrNull_get(self) { + try { + let ret = swift.memory.getObject(self).boolOrNull; + const isSome = ret != null; + bjs["swift_js_return_optional_bool"](isSome ? 1 : 0, isSome ? (ret ? 1 : 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_boolOrUndefined_get"] = function bjs_WithOptionalJSClass_boolOrUndefined_get(self) { + try { + let ret = swift.memory.getObject(self).boolOrUndefined; + const isSome = ret !== undefined; + bjs["swift_js_return_optional_bool"](isSome ? 1 : 0, isSome ? (ret ? 1 : 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_intOrNull_get"] = function bjs_WithOptionalJSClass_intOrNull_get(self) { + try { + let ret = swift.memory.getObject(self).intOrNull; + const isSome = ret != null; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_intOrUndefined_get"] = function bjs_WithOptionalJSClass_intOrUndefined_get(self) { + try { + let ret = swift.memory.getObject(self).intOrUndefined; + const isSome = ret !== undefined; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_stringOrNull_set"] = function bjs_WithOptionalJSClass_stringOrNull_set(self, newValueIsSome, newValueObjectId) { + try { + let optResult; + if (newValueIsSome) { + const newValueObjectIdObject = swift.memory.getObject(newValueObjectId); + swift.memory.release(newValueObjectId); + optResult = newValueObjectIdObject; + } else { + optResult = null; + } + swift.memory.getObject(self).stringOrNull = optResult; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_stringOrUndefined_set"] = function bjs_WithOptionalJSClass_stringOrUndefined_set(self, newValueIsSome, newValueObjectId) { + try { + let optResult; + if (newValueIsSome) { + const newValueObjectIdObject = swift.memory.getObject(newValueObjectId); + swift.memory.release(newValueObjectId); + optResult = newValueObjectIdObject; + } else { + optResult = undefined; + } + swift.memory.getObject(self).stringOrUndefined = optResult; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_doubleOrNull_set"] = function bjs_WithOptionalJSClass_doubleOrNull_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).doubleOrNull = newValueIsSome ? newValueWrappedValue : null; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_doubleOrUndefined_set"] = function bjs_WithOptionalJSClass_doubleOrUndefined_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).doubleOrUndefined = newValueIsSome ? newValueWrappedValue : undefined; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_boolOrNull_set"] = function bjs_WithOptionalJSClass_boolOrNull_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).boolOrNull = newValueIsSome ? newValueWrappedValue !== 0 : null; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_boolOrUndefined_set"] = function bjs_WithOptionalJSClass_boolOrUndefined_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).boolOrUndefined = newValueIsSome ? newValueWrappedValue !== 0 : undefined; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_intOrNull_set"] = function bjs_WithOptionalJSClass_intOrNull_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).intOrNull = newValueIsSome ? newValueWrappedValue : null; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_intOrUndefined_set"] = function bjs_WithOptionalJSClass_intOrUndefined_set(self, newValueIsSome, newValueWrappedValue) { + try { + swift.memory.getObject(self).intOrUndefined = newValueIsSome ? newValueWrappedValue : undefined; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripStringOrNull"] = function bjs_WithOptionalJSClass_roundTripStringOrNull(self, valueIsSome, valueObjectId) { + try { + let optResult; + if (valueIsSome) { + const valueObjectIdObject = swift.memory.getObject(valueObjectId); + swift.memory.release(valueObjectId); + optResult = valueObjectIdObject; + } else { + optResult = null; + } + let ret = swift.memory.getObject(self).roundTripStringOrNull(optResult); + const isSome = ret != null; + tmpRetString = isSome ? ret : null; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripStringOrUndefined"] = function bjs_WithOptionalJSClass_roundTripStringOrUndefined(self, valueIsSome, valueObjectId) { + try { + let optResult; + if (valueIsSome) { + const valueObjectIdObject = swift.memory.getObject(valueObjectId); + swift.memory.release(valueObjectId); + optResult = valueObjectIdObject; + } else { + optResult = undefined; + } + let ret = swift.memory.getObject(self).roundTripStringOrUndefined(optResult); + const isSome = ret !== undefined; + tmpRetString = isSome ? ret : undefined; + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripDoubleOrNull"] = function bjs_WithOptionalJSClass_roundTripDoubleOrNull(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripDoubleOrNull(valueIsSome ? valueWrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_double"](isSome ? 1 : 0, isSome ? ret : 0.0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripDoubleOrUndefined"] = function bjs_WithOptionalJSClass_roundTripDoubleOrUndefined(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripDoubleOrUndefined(valueIsSome ? valueWrappedValue : undefined); + const isSome = ret !== undefined; + bjs["swift_js_return_optional_double"](isSome ? 1 : 0, isSome ? ret : 0.0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripBoolOrNull"] = function bjs_WithOptionalJSClass_roundTripBoolOrNull(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripBoolOrNull(valueIsSome ? valueWrappedValue !== 0 : null); + const isSome = ret != null; + bjs["swift_js_return_optional_bool"](isSome ? 1 : 0, isSome ? (ret ? 1 : 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripBoolOrUndefined"] = function bjs_WithOptionalJSClass_roundTripBoolOrUndefined(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripBoolOrUndefined(valueIsSome ? valueWrappedValue !== 0 : undefined); + const isSome = ret !== undefined; + bjs["swift_js_return_optional_bool"](isSome ? 1 : 0, isSome ? (ret ? 1 : 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripIntOrNull"] = function bjs_WithOptionalJSClass_roundTripIntOrNull(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripIntOrNull(valueIsSome ? valueWrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_WithOptionalJSClass_roundTripIntOrUndefined"] = function bjs_WithOptionalJSClass_roundTripIntOrUndefined(self, valueIsSome, valueWrappedValue) { + try { + let ret = swift.memory.getObject(self).roundTripIntOrUndefined(valueIsSome ? valueWrappedValue : undefined); + const isSome = ret !== undefined; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class Greeter extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); + } + + constructor(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + const ret = instance.exports.bjs_Greeter_init(+isSome, result, result1); + return Greeter.__construct(ret); + } + greet() { + instance.exports.bjs_Greeter_greet(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + changeName(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_Greeter_changeName(this.pointer, +isSome, result, result1); + } + get name() { + instance.exports.bjs_Greeter_name_get(this.pointer); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + } + set name(value) { + const isSome = value != null; + let result, result1; + if (isSome) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + result = valueId; + result1 = valueBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_Greeter_name_set(this.pointer, +isSome, result, result1); + } + } + class OptionalPropertyHolder extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_OptionalPropertyHolder_deinit, OptionalPropertyHolder.prototype); + } + + constructor() { + const ret = instance.exports.bjs_OptionalPropertyHolder_init(); + return OptionalPropertyHolder.__construct(ret); + } + get optionalName() { + instance.exports.bjs_OptionalPropertyHolder_optionalName_get(this.pointer); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + } + set optionalName(value) { + const isSome = value != null; + let result, result1; + if (isSome) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + result = valueId; + result1 = valueBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_OptionalPropertyHolder_optionalName_set(this.pointer, +isSome, result, result1); + } + get optionalAge() { + instance.exports.bjs_OptionalPropertyHolder_optionalAge_get(this.pointer); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + } + set optionalAge(value) { + const isSome = value != null; + instance.exports.bjs_OptionalPropertyHolder_optionalAge_set(this.pointer, +isSome, isSome ? value : 0); + } + get optionalGreeter() { + instance.exports.bjs_OptionalPropertyHolder_optionalGreeter_get(this.pointer); + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + const optResult = pointer === null ? null : Greeter.__construct(pointer); + return optResult; + } + set optionalGreeter(value) { + const isSome = value != null; + let result; + if (isSome) { + result = value.pointer; + } else { + result = 0; + } + instance.exports.bjs_OptionalPropertyHolder_optionalGreeter_set(this.pointer, +isSome, result); + } + } + const exports = { + Greeter, + OptionalPropertyHolder, + roundTripOptionalClass: function bjs_roundTripOptionalClass(value) { + const isSome = value != null; + let result; + if (isSome) { + result = value.pointer; + } else { + result = 0; + } + instance.exports.bjs_roundTripOptionalClass(+isSome, result); + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + const optResult = pointer === null ? null : Greeter.__construct(pointer); + return optResult; + }, + testOptionalPropertyRoundtrip: function bjs_testOptionalPropertyRoundtrip(holder) { + const isSome = holder != null; + let result; + if (isSome) { + result = holder.pointer; + } else { + result = 0; + } + instance.exports.bjs_testOptionalPropertyRoundtrip(+isSome, result); + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + const optResult = pointer === null ? null : OptionalPropertyHolder.__construct(pointer); + return optResult; + }, + roundTripString: function bjs_roundTripString(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripString(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + roundTripInt: function bjs_roundTripInt(value) { + const isSome = value != null; + instance.exports.bjs_roundTripInt(+isSome, isSome ? value : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripBool: function bjs_roundTripBool(flag) { + const isSome = flag != null; + instance.exports.bjs_roundTripBool(+isSome, isSome ? flag ? 1 : 0 : 0); + const optResult = tmpRetOptionalBool; + tmpRetOptionalBool = undefined; + return optResult; + }, + roundTripFloat: function bjs_roundTripFloat(number) { + const isSome = number != null; + instance.exports.bjs_roundTripFloat(+isSome, isSome ? number : 0.0); + const optResult = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return optResult; + }, + roundTripDouble: function bjs_roundTripDouble(precision) { + const isSome = precision != null; + instance.exports.bjs_roundTripDouble(+isSome, isSome ? precision : 0.0); + const optResult = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return optResult; + }, + roundTripSyntax: function bjs_roundTripSyntax(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripSyntax(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + roundTripMixSyntax: function bjs_roundTripMixSyntax(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripMixSyntax(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + roundTripSwiftSyntax: function bjs_roundTripSwiftSyntax(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripSwiftSyntax(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + roundTripMixedSwiftSyntax: function bjs_roundTripMixedSwiftSyntax(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripMixedSwiftSyntax(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + roundTripWithSpaces: function bjs_roundTripWithSpaces(value) { + const isSome = value != null; + instance.exports.bjs_roundTripWithSpaces(+isSome, isSome ? value : 0.0); + const optResult = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return optResult; + }, + roundTripAlias: function bjs_roundTripAlias(age) { + const isSome = age != null; + instance.exports.bjs_roundTripAlias(+isSome, isSome ? age : 0); + const optResult = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return optResult; + }, + roundTripOptionalAlias: function bjs_roundTripOptionalAlias(name) { + const isSome = name != null; + let result, result1; + if (isSome) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + result = nameId; + result1 = nameBytes.length; + } else { + result = 0; + result1 = 0; + } + instance.exports.bjs_roundTripOptionalAlias(+isSome, result, result1); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + testMixedOptionals: function bjs_testMixedOptionals(firstName, lastName, age, active) { + const isSome = firstName != null; + let result, result1; + if (isSome) { + const firstNameBytes = textEncoder.encode(firstName); + const firstNameId = swift.memory.retain(firstNameBytes); + result = firstNameId; + result1 = firstNameBytes.length; + } else { + result = 0; + result1 = 0; + } + const isSome1 = lastName != null; + let result2, result3; + if (isSome1) { + const lastNameBytes = textEncoder.encode(lastName); + const lastNameId = swift.memory.retain(lastNameBytes); + result2 = lastNameId; + result3 = lastNameBytes.length; + } else { + result2 = 0; + result3 = 0; + } + const isSome2 = age != null; + instance.exports.bjs_testMixedOptionals(+isSome, result, result1, +isSome1, result2, result3, +isSome2, isSome2 ? age : 0, active); + const optResult = tmpRetString; + tmpRetString = undefined; + return optResult; + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.js deleted file mode 100644 index 0a92510f7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.js +++ /dev/null @@ -1,225 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - check: function bjs_check(a, b, c, d, e) { - instance.exports.bjs_check(a, b, c, d, e); - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts similarity index 93% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts index 9bf0e1e35..961f97635 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts @@ -8,6 +8,7 @@ export type Exports = { check(a: number, b: number, c: number, d: number, e: boolean): void; } export type Imports = { + check(a: number, b: boolean): void; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index fe6c3ae04..8999ae8b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +184,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_check"] = function bjs_check(a, b) { try { @@ -223,6 +206,9 @@ export async function createInstantiator(options, swift) { createExports: (instance) => { const js = swift.memory.heap; const exports = { + check: function bjs_check(a, b, c, d, e) { + instance.exports.bjs_check(a, b, c, d, e); + }, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.d.ts deleted file mode 100644 index ad63bd7d0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Import.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - checkNumber(): number; - checkBoolean(): boolean; -} -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/PrimitiveReturn.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts similarity index 91% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts index c726e1f5a..77e269d16 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts @@ -12,6 +12,8 @@ export type Exports = { checkBool(): boolean; } export type Imports = { + checkNumber(): number; + checkBoolean(): boolean; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index 836a82f21..c8372362d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -42,12 +36,14 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); tmpRetString = textDecoder.decode(bytes); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,6 +184,26 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_checkNumber"] = function bjs_checkNumber() { + try { + let ret = imports.checkNumber(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_checkBoolean"] = function bjs_checkBoolean() { + try { + let ret = imports.checkBoolean(); + return ret ? 1 : 0; + } catch (error) { + setException(error); + return 0 + } + } }, setInstance: (i) => { instance = i; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js similarity index 88% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index fc13a471a..dbdd030b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,12 +183,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_PropertyHolder_wrap"] = function(pointer) { - const obj = PropertyHolder.__construct(pointer); + const obj = _exports['PropertyHolder'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -221,35 +204,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class PropertyHolder extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyHolder_deinit, PropertyHolder.prototype); } - + constructor(intValue, floatValue, doubleValue, boolValue, stringValue, jsObject) { const stringValueBytes = textEncoder.encode(stringValue); const stringValueId = swift.memory.retain(stringValueBytes); const ret = instance.exports.bjs_PropertyHolder_init(intValue, floatValue, doubleValue, boolValue, stringValueId, stringValueBytes.length, swift.memory.retain(jsObject)); - swift.memory.release(stringValueId); return PropertyHolder.__construct(ret); } getAllValues() { @@ -296,7 +288,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyHolder_stringValue_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } get readonlyInt() { const ret = instance.exports.bjs_PropertyHolder_readonlyInt_get(this.pointer); @@ -346,7 +337,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyHolder_lazyValue_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } get computedReadonly() { const ret = instance.exports.bjs_PropertyHolder_computedReadonly_get(this.pointer); @@ -362,7 +352,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyHolder_computedReadWrite_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } get observedProperty() { const ret = instance.exports.bjs_PropertyHolder_observedProperty_get(this.pointer); @@ -378,7 +367,6 @@ export async function createInstantiator(options, swift) { const stringValueBytes = textEncoder.encode(stringValue); const stringValueId = swift.memory.retain(stringValueBytes); const ret = instance.exports.bjs_createPropertyHolder(intValue, floatValue, doubleValue, boolValue, stringValueId, stringValueBytes.length, swift.memory.retain(jsObject)); - swift.memory.release(stringValueId); return PropertyHolder.__construct(ret); }, testPropertyHolder: function bjs_testPropertyHolder(holder) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js similarity index 84% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 24c02750f..6e95d2ddf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -22,46 +22,6 @@ export const ResultValues = { Failure: 1, }, }; - -const __bjs_createResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case ResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: ResultValues.Tag.Success, cleanup }; - } - case ResultValues.Tag.Failure: { - tmpParamInts.push((value.param0 | 0)); - const cleanup = undefined; - return { caseId: ResultValues.Tag.Failure, cleanup }; - } - default: throw new Error("Unknown ResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case ResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: ResultValues.Tag.Success, param0: string }; - } - case ResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); - return { tag: ResultValues.Tag.Failure, param0: int }; - } - default: throw new Error("Unknown ResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; export const PriorityValues = { Low: -1, Medium: 0, @@ -82,22 +42,49 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; + const __bjs_createResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case ResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return ResultValues.Tag.Success; + } + case ResultValues.Tag.Failure: { + i32Stack.push((value.param0 | 0)); + return ResultValues.Tag.Failure; + } + default: throw new Error("Unknown ResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case ResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: ResultValues.Tag.Success, param0: string }; + } + case ResultValues.Tag.Failure: { + const int = i32Stack.pop(); + return { tag: ResultValues.Tag.Failure, param0: int }; + } + default: throw new Error("Unknown ResultValues tag returned from Swift: " + String(tag)); + } + } + }); return { /** @@ -112,6 +99,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -133,47 +121,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -265,20 +240,21 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_DelegateManager_wrap"] = function(pointer) { - const obj = DelegateManager.__construct(pointer); + const obj = _exports['DelegateManager'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_Helper_wrap"] = function(pointer) { - const obj = Helper.__construct(pointer); + const obj = _exports['Helper'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_MyViewController_wrap"] = function(pointer) { - const obj = MyViewController.__construct(pointer); + const obj = _exports['MyViewController'].__construct(pointer); return swift.memory.retain(obj); }; const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; @@ -315,14 +291,17 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueWrappedValue) { + TestModule["bjs_MyViewControllerDelegate_optionalName_set"] = function bjs_MyViewControllerDelegate_optionalName_set(self, valueIsSome, valueObjectId) { try { - let obj; + let optResult; if (valueIsSome) { - obj = swift.memory.getObject(valueWrappedValue); - swift.memory.release(valueWrappedValue); + const valueObjectIdObject = swift.memory.getObject(valueObjectId); + swift.memory.release(valueObjectId); + optResult = valueObjectIdObject; + } else { + optResult = null; } - swift.memory.getObject(self).optionalName = valueIsSome ? obj : null; + swift.memory.getObject(self).optionalName = optResult; } catch (error) { setException(error); } @@ -335,14 +314,17 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueWrappedValue) { + TestModule["bjs_MyViewControllerDelegate_optionalRawEnum_set"] = function bjs_MyViewControllerDelegate_optionalRawEnum_set(self, valueIsSome, valueObjectId) { try { - let obj; + let optResult; if (valueIsSome) { - obj = swift.memory.getObject(valueWrappedValue); - swift.memory.release(valueWrappedValue); + const valueObjectIdObject = swift.memory.getObject(valueObjectId); + swift.memory.release(valueObjectId); + optResult = valueObjectIdObject; + } else { + optResult = null; } - swift.memory.getObject(self).optionalRawEnum = valueIsSome ? obj : null; + swift.memory.getObject(self).optionalRawEnum = optResult; } catch (error) { setException(error); } @@ -368,7 +350,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_MyViewControllerDelegate_result_get"] = function bjs_MyViewControllerDelegate_result_get(self) { try { let ret = swift.memory.getObject(self).result; - const { caseId: caseId, cleanup: cleanup } = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.Result.lower(ret); return caseId; } catch (error) { setException(error); @@ -376,7 +358,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_MyViewControllerDelegate_result_set"] = function bjs_MyViewControllerDelegate_result_set(self, value) { try { - const enumValue = enumHelpers.Result.lift(value, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); + const enumValue = enumHelpers.Result.lift(value); swift.memory.getObject(self).result = enumValue; } catch (error) { setException(error); @@ -387,7 +369,7 @@ export async function createInstantiator(options, swift) { let ret = swift.memory.getObject(self).optionalResult; const isSome = ret != null; if (isSome) { - const { caseId: caseId, cleanup: cleanup } = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.Result.lower(ret); return caseId; } else { return -1; @@ -396,13 +378,16 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_MyViewControllerDelegate_optionalResult_set"] = function bjs_MyViewControllerDelegate_optionalResult_set(self, valueIsSome, valueWrappedValue) { + TestModule["bjs_MyViewControllerDelegate_optionalResult_set"] = function bjs_MyViewControllerDelegate_optionalResult_set(self, valueIsSome, valueCaseId) { try { - let enumValue; + let optResult; if (valueIsSome) { - enumValue = enumHelpers.Result.lift(valueWrappedValue, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); + const enumValue = enumHelpers.Result.lift(valueCaseId); + optResult = enumValue; + } else { + optResult = null; } - swift.memory.getObject(self).optionalResult = valueIsSome ? enumValue : null; + swift.memory.getObject(self).optionalResult = optResult; } catch (error) { setException(error); } @@ -427,7 +412,7 @@ export async function createInstantiator(options, swift) { try { let ret = swift.memory.getObject(self).directionOptional; const isSome = ret != null; - return isSome ? (ret | 0) : -1; + return isSome ? ret : -1; } catch (error) { setException(error); } @@ -517,7 +502,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_MyViewControllerDelegate_onHelperUpdated"] = function bjs_MyViewControllerDelegate_onHelperUpdated(self, helper) { try { - swift.memory.getObject(self).onHelperUpdated(Helper.__construct(helper)); + swift.memory.getObject(self).onHelperUpdated(_exports['Helper'].__construct(helper)); } catch (error) { setException(error); } @@ -531,9 +516,9 @@ export async function createInstantiator(options, swift) { return 0 } } - TestModule["bjs_MyViewControllerDelegate_onOptionalHelperUpdated"] = function bjs_MyViewControllerDelegate_onOptionalHelperUpdated(self, helperIsSome, helperWrappedValue) { + TestModule["bjs_MyViewControllerDelegate_onOptionalHelperUpdated"] = function bjs_MyViewControllerDelegate_onOptionalHelperUpdated(self, helperIsSome, helperPointer) { try { - swift.memory.getObject(self).onOptionalHelperUpdated(helperIsSome ? Helper.__construct(helperWrappedValue) : null); + swift.memory.getObject(self).onOptionalHelperUpdated(helperIsSome ? _exports['Helper'].__construct(helperPointer) : null); } catch (error) { setException(error); } @@ -542,6 +527,7 @@ export async function createInstantiator(options, swift) { try { let ret = swift.memory.getObject(self).createOptionalHelper(); const isSome = ret != null; + return isSome ? ret.pointer : 0; } catch (error) { setException(error); } @@ -557,7 +543,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_MyViewControllerDelegate_handleResult"] = function bjs_MyViewControllerDelegate_handleResult(self, result) { try { - const enumValue = enumHelpers.Result.lift(result, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); + const enumValue = enumHelpers.Result.lift(result); swift.memory.getObject(self).handleResult(enumValue); } catch (error) { setException(error); @@ -566,7 +552,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_MyViewControllerDelegate_getResult"] = function bjs_MyViewControllerDelegate_getResult(self) { try { let ret = swift.memory.getObject(self).getResult(); - const { caseId: caseId, cleanup: cleanup } = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.Result.lower(ret); return caseId; } catch (error) { setException(error); @@ -577,9 +563,6 @@ export async function createInstantiator(options, swift) { instance = i; memory = instance.exports.memory; - const ResultHelpers = __bjs_createResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.Result = ResultHelpers; - setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) } @@ -587,30 +570,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Helper extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Helper_deinit, Helper.prototype); } - + constructor(value) { const ret = instance.exports.bjs_Helper_init(value); return Helper.__construct(ret); @@ -630,7 +623,7 @@ export async function createInstantiator(options, swift) { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MyViewController_deinit, MyViewController.prototype); } - + constructor(delegate) { const ret = instance.exports.bjs_MyViewController_init(swift.memory.retain(delegate)); return MyViewController.__construct(ret); @@ -642,7 +635,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_MyViewController_updateValue(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } updateCount(count) { const ret = instance.exports.bjs_MyViewController_updateCount(this.pointer, count); @@ -654,8 +646,6 @@ export async function createInstantiator(options, swift) { const suffixBytes = textEncoder.encode(suffix); const suffixId = swift.memory.retain(suffixBytes); instance.exports.bjs_MyViewController_updateLabel(this.pointer, prefixId, prefixBytes.length, suffixId, suffixBytes.length); - swift.memory.release(prefixId); - swift.memory.release(suffixId); } checkEvenCount() { const ret = instance.exports.bjs_MyViewController_checkEvenCount(this.pointer); @@ -681,23 +671,27 @@ export async function createInstantiator(options, swift) { } set secondDelegate(value) { const isSome = value != null; - instance.exports.bjs_MyViewController_secondDelegate_set(this.pointer, +isSome, isSome ? swift.memory.retain(value) : 0); + let result; + if (isSome) { + result = swift.memory.retain(value); + } else { + result = 0; + } + instance.exports.bjs_MyViewController_secondDelegate_set(this.pointer, +isSome, result); } } class DelegateManager extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_DelegateManager_deinit, DelegateManager.prototype); } - + constructor(delegates) { - const arrayCleanups = []; for (const elem of delegates) { const objId = swift.memory.retain(elem); - tmpParamInts.push(objId); + i32Stack.push(objId); } - tmpParamInts.push(delegates.length); + i32Stack.push(delegates.length); const ret = instance.exports.bjs_DelegateManager_init(); - for (const cleanup of arrayCleanups) { cleanup(); } return DelegateManager.__construct(ret); } notifyAll() { @@ -705,10 +699,10 @@ export async function createInstantiator(options, swift) { } get delegates() { instance.exports.bjs_DelegateManager_delegates_get(this.pointer); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const objId = tmpRetInts.pop(); + const objId = i32Stack.pop(); const obj = swift.memory.getObject(objId); swift.memory.release(objId); arrayResult.push(obj); @@ -717,38 +711,37 @@ export async function createInstantiator(options, swift) { return arrayResult; } set delegates(value) { - const arrayCleanups = []; for (const elem of value) { const objId = swift.memory.retain(elem); - tmpParamInts.push(objId); + i32Stack.push(objId); } - tmpParamInts.push(value.length); + i32Stack.push(value.length); instance.exports.bjs_DelegateManager_delegates_set(this.pointer); - for (const cleanup of arrayCleanups) { cleanup(); } } } + const ResultHelpers = __bjs_createResultValuesHelpers(); + enumHelpers.Result = ResultHelpers; + const exports = { Helper, MyViewController, DelegateManager, processDelegates: function bjs_processDelegates(delegates) { - const arrayCleanups = []; for (const elem of delegates) { const objId = swift.memory.retain(elem); - tmpParamInts.push(objId); + i32Stack.push(objId); } - tmpParamInts.push(delegates.length); + i32Stack.push(delegates.length); instance.exports.bjs_processDelegates(); - const arrayLen = tmpRetInts.pop(); + const arrayLen = i32Stack.pop(); const arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const objId1 = tmpRetInts.pop(); + const objId1 = i32Stack.pop(); const obj = swift.memory.getObject(objId1); swift.memory.release(objId1); arrayResult.push(obj); } arrayResult.reverse(); - for (const cleanup of arrayCleanups) { cleanup(); } return arrayResult; }, Direction: DirectionValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.js deleted file mode 100644 index 94e22ffc4..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ReExportFrom.Import.js +++ /dev/null @@ -1,252 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_jsRoundTripNumber"] = function bjs_jsRoundTripNumber(v) { - try { - let ret = imports.jsRoundTripNumber(v); - return ret; - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_JsGreeter_init"] = function bjs_JsGreeter_init(name) { - try { - const nameObject = swift.memory.getObject(name); - swift.memory.release(name); - return swift.memory.retain(new imports.JsGreeter(nameObject)); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_JsGreeter_greet"] = function bjs_JsGreeter_greet(self) { - try { - let ret = swift.memory.getObject(self).greet(); - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts similarity index 97% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts index 069c1628c..a2f1c7d6d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -33,7 +33,7 @@ export {}; declare global { namespace Utils { namespace String { - uppercase(text: string): string; + function uppercase(text: string): string; } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js similarity index 79% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index e7bebfe6c..0e8a5a7bb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -15,76 +15,63 @@ export const APIResultValues = { Failure: 1, }, }; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; -const __bjs_createAPIResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ + let _exports = null; + let bjs = null; + const __bjs_createAPIResultValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { case APIResultValues.Tag.Success: { const bytes = textEncoder.encode(value.param0); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: APIResultValues.Tag.Success, cleanup }; + i32Stack.push(bytes.length); + i32Stack.push(id); + return APIResultValues.Tag.Success; } case APIResultValues.Tag.Failure: { - tmpParamInts.push((value.param0 | 0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Failure, cleanup }; + i32Stack.push((value.param0 | 0)); + return APIResultValues.Tag.Failure; } default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); } }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; + lift: (tag) => { + tag = tag | 0; switch (tag) { case APIResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); return { tag: APIResultValues.Tag.Success, param0: string }; } case APIResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); return { tag: APIResultValues.Tag.Failure, param0: int }; } default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); } } }); -}; -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; return { /** @@ -99,6 +86,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -120,47 +108,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -252,12 +227,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_MathUtils_wrap"] = function(pointer) { - const obj = MathUtils.__construct(pointer); + const obj = _exports['MathUtils'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -265,9 +241,6 @@ export async function createInstantiator(options, swift) { instance = i; memory = instance.exports.memory; - const APIResultHelpers = __bjs_createAPIResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.APIResult = APIResultHelpers; - setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) } @@ -275,30 +248,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class MathUtils extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype); } - + constructor() { const ret = instance.exports.bjs_MathUtils_init(); return MathUtils.__construct(ret); @@ -316,6 +299,9 @@ export async function createInstantiator(options, swift) { return ret; } } + const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); + enumHelpers.APIResult = APIResultHelpers; + if (typeof globalThis.Utils === 'undefined') { globalThis.Utils = {}; } @@ -334,10 +320,9 @@ export async function createInstantiator(options, swift) { APIResult: { ...APIResultValues, roundtrip: function(value) { - const { caseId: valueCaseId, cleanup: valueCleanup } = enumHelpers.APIResult.lower(value); + const valueCaseId = enumHelpers.APIResult.lower(value); instance.exports.bjs_APIResult_static_roundtrip(valueCaseId); - const ret = enumHelpers.APIResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - if (valueCleanup) { valueCleanup(); } + const ret = enumHelpers.APIResult.lift(i32Stack.pop()); return ret; } }, @@ -349,7 +334,6 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_Utils_String_static_uppercase(textId, textBytes.length); const ret = tmpRetString; tmpRetString = undefined; - swift.memory.release(textId); return ret; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js similarity index 78% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 8b5a54315..2eea1f12f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -15,76 +15,63 @@ export const APIResultValues = { Failure: 1, }, }; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; -const __bjs_createAPIResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ + let _exports = null; + let bjs = null; + const __bjs_createAPIResultValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { case APIResultValues.Tag.Success: { const bytes = textEncoder.encode(value.param0); const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: APIResultValues.Tag.Success, cleanup }; + i32Stack.push(bytes.length); + i32Stack.push(id); + return APIResultValues.Tag.Success; } case APIResultValues.Tag.Failure: { - tmpParamInts.push((value.param0 | 0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Failure, cleanup }; + i32Stack.push((value.param0 | 0)); + return APIResultValues.Tag.Failure; } default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); } }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; + lift: (tag) => { + tag = tag | 0; switch (tag) { case APIResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); + const string = strStack.pop(); return { tag: APIResultValues.Tag.Success, param0: string }; } case APIResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); + const int = i32Stack.pop(); return { tag: APIResultValues.Tag.Failure, param0: int }; } default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); } } }); -}; -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; return { /** @@ -99,6 +86,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -120,47 +108,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -252,12 +227,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_MathUtils_wrap"] = function(pointer) { - const obj = MathUtils.__construct(pointer); + const obj = _exports['MathUtils'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -265,9 +241,6 @@ export async function createInstantiator(options, swift) { instance = i; memory = instance.exports.memory; - const APIResultHelpers = __bjs_createAPIResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.APIResult = APIResultHelpers; - setException = (error) => { instance.exports._swift_js_exception.value = swift.memory.retain(error) } @@ -275,30 +248,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class MathUtils extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_MathUtils_deinit, MathUtils.prototype); } - + constructor() { const ret = instance.exports.bjs_MathUtils_init(); return MathUtils.__construct(ret); @@ -316,6 +299,9 @@ export async function createInstantiator(options, swift) { return ret; } } + const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); + enumHelpers.APIResult = APIResultHelpers; + const exports = { MathUtils, Calculator: { @@ -328,10 +314,9 @@ export async function createInstantiator(options, swift) { APIResult: { ...APIResultValues, roundtrip: function(value) { - const { caseId: valueCaseId, cleanup: valueCleanup } = enumHelpers.APIResult.lower(value); + const valueCaseId = enumHelpers.APIResult.lower(value); instance.exports.bjs_APIResult_static_roundtrip(valueCaseId); - const ret = enumHelpers.APIResult.lift(tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - if (valueCleanup) { valueCleanup(); } + const ret = enumHelpers.APIResult.lift(i32Stack.pop()); return ret; } }, @@ -343,7 +328,6 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_Utils_String_static_uppercase(textId, textBytes.length); const ret = tmpRetString; tmpRetString = undefined; - swift.memory.release(textId); return ret; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js similarity index 87% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 9806fc631..16bf8ba0c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -23,20 +23,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -53,6 +47,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -74,47 +69,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -206,12 +188,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_PropertyClass_wrap"] = function(pointer) { - const obj = PropertyClass.__construct(pointer); + const obj = _exports['PropertyClass'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -226,30 +209,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class PropertyClass extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype); } - + constructor() { const ret = instance.exports.bjs_PropertyClass_init(); return PropertyClass.__construct(ret); @@ -286,7 +279,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyClass_static_classVariable_set(valueId, valueBytes.length); - swift.memory.release(valueId); } static get computedProperty() { instance.exports.bjs_PropertyClass_static_computedProperty_get(); @@ -298,7 +290,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyClass_static_computedProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); } static get readOnlyComputed() { const ret = instance.exports.bjs_PropertyClass_static_readOnlyComputed_get(); @@ -312,15 +303,17 @@ export async function createInstantiator(options, swift) { } static set optionalProperty(value) { const isSome = value != null; - let valueId, valueBytes; + let result, result1; if (isSome) { - valueBytes = textEncoder.encode(value); - valueId = swift.memory.retain(valueBytes); - } - instance.exports.bjs_PropertyClass_static_optionalProperty_set(+isSome, isSome ? valueId : 0, isSome ? valueBytes.length : 0); - if (valueId != undefined) { - swift.memory.release(valueId); + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + result = valueId; + result1 = valueBytes.length; + } else { + result = 0; + result1 = 0; } + instance.exports.bjs_PropertyClass_static_optionalProperty_set(+isSome, result, result1); } } if (typeof globalThis.PropertyNamespace === 'undefined') { @@ -343,7 +336,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyEnum_static_enumProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); }, get enumConstant() { const ret = instance.exports.bjs_PropertyEnum_static_enumConstant_get(); @@ -359,7 +351,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyEnum_static_computedEnum_set(valueId, valueBytes.length); - swift.memory.release(valueId); } }, PropertyNamespace: { @@ -373,7 +364,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyNamespace_static_namespaceProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); }, get namespaceConstant() { instance.exports.bjs_PropertyNamespace_static_namespaceConstant_get(); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index ee127ed07..ea6c448ed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -23,20 +23,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -53,6 +47,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -74,47 +69,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -206,12 +188,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_PropertyClass_wrap"] = function(pointer) { - const obj = PropertyClass.__construct(pointer); + const obj = _exports['PropertyClass'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -226,30 +209,40 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class PropertyClass extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PropertyClass_deinit, PropertyClass.prototype); } - + constructor() { const ret = instance.exports.bjs_PropertyClass_init(); return PropertyClass.__construct(ret); @@ -286,7 +279,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyClass_static_classVariable_set(valueId, valueBytes.length); - swift.memory.release(valueId); } static get computedProperty() { instance.exports.bjs_PropertyClass_static_computedProperty_get(); @@ -298,7 +290,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyClass_static_computedProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); } static get readOnlyComputed() { const ret = instance.exports.bjs_PropertyClass_static_readOnlyComputed_get(); @@ -312,15 +303,17 @@ export async function createInstantiator(options, swift) { } static set optionalProperty(value) { const isSome = value != null; - let valueId, valueBytes; + let result, result1; if (isSome) { - valueBytes = textEncoder.encode(value); - valueId = swift.memory.retain(valueBytes); - } - instance.exports.bjs_PropertyClass_static_optionalProperty_set(+isSome, isSome ? valueId : 0, isSome ? valueBytes.length : 0); - if (valueId != undefined) { - swift.memory.release(valueId); + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + result = valueId; + result1 = valueBytes.length; + } else { + result = 0; + result1 = 0; } + instance.exports.bjs_PropertyClass_static_optionalProperty_set(+isSome, result, result1); } } const exports = { @@ -337,7 +330,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyEnum_static_enumProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); }, get enumConstant() { const ret = instance.exports.bjs_PropertyEnum_static_enumConstant_get(); @@ -353,7 +345,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyEnum_static_computedEnum_set(valueId, valueBytes.length); - swift.memory.release(valueId); } }, PropertyNamespace: { @@ -367,7 +358,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_PropertyNamespace_static_namespaceProperty_set(valueId, valueBytes.length); - swift.memory.release(valueId); }, get namespaceConstant() { instance.exports.bjs_PropertyNamespace_static_namespaceConstant_get(); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringEnum.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringEnum.Import.d.ts deleted file mode 100644 index bb9f163cc..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringEnum.Import.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - takesFeatureFlag(flag: FeatureFlagTag): void; - returnsFeatureFlag(): FeatureFlagTag; -} -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/StringEnum.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringEnum.Import.js deleted file mode 100644 index 373b433b6..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringEnum.Import.js +++ /dev/null @@ -1,242 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_takesFeatureFlag"] = function bjs_takesFeatureFlag(flag) { - try { - const flagObject = swift.memory.getObject(flag); - swift.memory.release(flag); - imports.takesFeatureFlag(flagObject); - } catch (error) { - setException(error); - } - } - TestModule["bjs_returnsFeatureFlag"] = function bjs_returnsFeatureFlag() { - try { - let ret = imports.returnsFeatureFlag(); - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.d.ts deleted file mode 100644 index 229436712..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { - checkString(a: string): void; - roundtripString(a: string): string; -} -export type Imports = { -} -export function createInstantiator(options: { - imports: Imports; -}, swift: any): Promise<{ - addImports: (importObject: WebAssembly.Imports) => void; - setInstance: (instance: WebAssembly.Instance) => void; - createExports: (instance: WebAssembly.Instance) => Exports; -}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.js deleted file mode 100644 index 021adcba3..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Export.js +++ /dev/null @@ -1,237 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - checkString: function bjs_checkString(a) { - const aBytes = textEncoder.encode(a); - const aId = swift.memory.retain(aBytes); - instance.exports.bjs_checkString(aId, aBytes.length); - swift.memory.release(aId); - }, - roundtripString: function bjs_roundtripString(a) { - const aBytes = textEncoder.encode(a); - const aId = swift.memory.retain(aBytes); - instance.exports.bjs_roundtripString(aId, aBytes.length); - const ret = tmpRetString; - tmpRetString = undefined; - swift.memory.release(aId); - return ret; - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts similarity index 89% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts index 09fd7b638..5e45162a1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts @@ -5,6 +5,8 @@ // `swift package bridge-js`. export type Exports = { + checkString(a: string): void; + roundtripString(a: string): string; } export type Imports = { checkString(a: string): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js similarity index 86% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 718f776c7..480f40f92 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +184,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_checkString"] = function bjs_checkString(a) { try { @@ -234,6 +217,19 @@ export async function createInstantiator(options, swift) { createExports: (instance) => { const js = swift.memory.heap; const exports = { + checkString: function bjs_checkString(a) { + const aBytes = textEncoder.encode(a); + const aId = swift.memory.retain(aBytes); + instance.exports.bjs_checkString(aId, aBytes.length); + }, + roundtripString: function bjs_roundtripString(a) { + const aBytes = textEncoder.encode(a); + const aId = swift.memory.retain(aBytes); + instance.exports.bjs_roundtripString(aId, aBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Export.js deleted file mode 100644 index 479b313dd..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Export.js +++ /dev/null @@ -1,228 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - checkString: function bjs_checkString() { - instance.exports.bjs_checkString(); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.d.ts deleted file mode 100644 index cb7783667..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - checkString(): string; -} -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/StringReturn.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts similarity index 95% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts index c6a9f65a4..b43ff062c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts @@ -8,6 +8,7 @@ export type Exports = { checkString(): string; } export type Imports = { + checkString(): string; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index bb5278068..49f07b5ef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +184,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_checkString"] = function bjs_checkString() { try { @@ -225,6 +208,12 @@ export async function createInstantiator(options, swift) { createExports: (instance) => { const js = swift.memory.heap; const exports = { + checkString: function bjs_checkString() { + instance.exports.bjs_checkString(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts similarity index 90% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 8718463a9..05fc97fee 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -31,6 +31,8 @@ export type Exports = { takeGreeter(greeter: Greeter): void; } export type Imports = { + jsRoundTripGreeter(greeter: Greeter): Greeter; + jsRoundTripOptionalGreeter(greeter: Greeter | null): Greeter | null; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js similarity index 79% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index d04cd6507..a74d49327 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -42,12 +36,14 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); tmpRetString = textDecoder.decode(bytes); } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,22 +184,42 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { - const obj = Greeter.__construct(pointer); + const obj = _exports['Greeter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_PackageGreeter_wrap"] = function(pointer) { - const obj = PackageGreeter.__construct(pointer); + const obj = _exports['PackageGreeter'].__construct(pointer); return swift.memory.retain(obj); }; importObject["TestModule"]["bjs_PublicGreeter_wrap"] = function(pointer) { - const obj = PublicGreeter.__construct(pointer); + const obj = _exports['PublicGreeter'].__construct(pointer); return swift.memory.retain(obj); }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_jsRoundTripGreeter"] = function bjs_jsRoundTripGreeter(greeter) { + try { + let ret = imports.jsRoundTripGreeter(_exports['Greeter'].__construct(greeter)); + return ret.pointer; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_jsRoundTripOptionalGreeter"] = function bjs_jsRoundTripOptionalGreeter(greeterIsSome, greeterPointer) { + try { + let ret = imports.jsRoundTripOptionalGreeter(greeterIsSome ? _exports['Greeter'].__construct(greeterPointer) : null); + const isSome = ret != null; + return isSome ? ret.pointer : 0; + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; @@ -229,35 +232,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Greeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); } - + constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); - swift.memory.release(nameId); return Greeter.__construct(ret); } greet() { @@ -270,7 +282,6 @@ export async function createInstantiator(options, swift) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); instance.exports.bjs_Greeter_changeName(this.pointer, nameId, nameBytes.length); - swift.memory.release(nameId); } get name() { instance.exports.bjs_Greeter_name_get(this.pointer); @@ -282,20 +293,19 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } } class PublicGreeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PublicGreeter_deinit, PublicGreeter.prototype); } - + } class PackageGreeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PackageGreeter_deinit, PackageGreeter.prototype); } - + } const exports = { Greeter, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.js deleted file mode 100644 index 40378d042..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.js +++ /dev/null @@ -1,945 +0,0 @@ -// 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 DirectionValues = { - North: 0, - South: 1, - East: 2, - West: 3, -}; - -export const ThemeValues = { - Light: "light", - Dark: "dark", - Auto: "auto", -}; - -export const HttpStatusValues = { - Ok: 200, - NotFound: 404, - ServerError: 500, - Unknown: -1, -}; - -export const APIResultValues = { - Tag: { - Success: 0, - Failure: 1, - Flag: 2, - Rate: 3, - Precise: 4, - Info: 5, - }, -}; - -const __bjs_createAPIResultValuesHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift) => ({ - lower: (value) => { - const enumTag = value.tag; - switch (enumTag) { - case APIResultValues.Tag.Success: { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const cleanup = () => { - swift.memory.release(id); - }; - return { caseId: APIResultValues.Tag.Success, cleanup }; - } - case APIResultValues.Tag.Failure: { - tmpParamInts.push((value.param0 | 0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Failure, cleanup }; - } - case APIResultValues.Tag.Flag: { - tmpParamInts.push(value.param0 ? 1 : 0); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Flag, cleanup }; - } - case APIResultValues.Tag.Rate: { - tmpParamF32s.push(Math.fround(value.param0)); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Rate, cleanup }; - } - case APIResultValues.Tag.Precise: { - tmpParamF64s.push(value.param0); - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Precise, cleanup }; - } - case APIResultValues.Tag.Info: { - const cleanup = undefined; - return { caseId: APIResultValues.Tag.Info, cleanup }; - } - default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); - } - }, - lift: (tmpRetTag, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s) => { - const tag = tmpRetTag | 0; - switch (tag) { - case APIResultValues.Tag.Success: { - const string = tmpRetStrings.pop(); - return { tag: APIResultValues.Tag.Success, param0: string }; - } - case APIResultValues.Tag.Failure: { - const int = tmpRetInts.pop(); - return { tag: APIResultValues.Tag.Failure, param0: int }; - } - case APIResultValues.Tag.Flag: { - const bool = tmpRetInts.pop(); - return { tag: APIResultValues.Tag.Flag, param0: bool }; - } - case APIResultValues.Tag.Rate: { - const f32 = tmpRetF32s.pop(); - return { tag: APIResultValues.Tag.Rate, param0: f32 }; - } - case APIResultValues.Tag.Precise: { - const f64 = tmpRetF64s.pop(); - return { tag: APIResultValues.Tag.Precise, param0: f64 }; - } - case APIResultValues.Tag.Info: return { tag: APIResultValues.Tag.Info }; - default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); - } - } - }); -}; -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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["invoke_js_callback_TestModule_10TestModule10HttpStatusO_Si"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - let param0 = param0Id; - const result = callback(param0); - return result | 0; - } catch (error) { - setException?.(error); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule10HttpStatusO_Si"] = function(closurePtr) { - return function(param0) { - try { - return instance.exports.invoke_swift_closure_TestModule_10TestModule10HttpStatusO_Si(closurePtr, param0) | 0; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_SS"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - const param0IdObject = swift.memory.getObject(param0Id); - swift.memory.release(param0Id); - let param0 = String(param0IdObject); - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule5ThemeO_SS"] = function(closurePtr) { - return function(param0) { - try { - const param0Bytes = textEncoder.encode(param0); - const param0Id = swift.memory.retain(param0Bytes); - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModule5ThemeO_SS(closurePtr, param0Id, param0Bytes.length); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_Sb"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - const param0IdObject = swift.memory.getObject(param0Id); - swift.memory.release(param0Id); - let param0 = String(param0IdObject); - const result = callback(param0); - return result ? 1 : 0; - } catch (error) { - setException?.(error); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule5ThemeO_Sb"] = function(closurePtr) { - return function(param0) { - try { - const param0Bytes = textEncoder.encode(param0); - const param0Id = swift.memory.retain(param0Bytes); - return instance.exports.invoke_swift_closure_TestModule_10TestModule5ThemeO_Sb(closurePtr, param0Id, param0Bytes.length) !== 0; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule6PersonC_SS"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - let param0 = _exports['Person'].__construct(param0Id); - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule6PersonC_SS"] = function(closurePtr) { - return function(param0) { - try { - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModule6PersonC_SS(closurePtr, param0.pointer); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule9APIResultO_SS"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - let param0 = enumHelpers.APIResult.lift(param0Id, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule9APIResultO_SS"] = function(closurePtr) { - return function(param0) { - try { - const { caseId: param0CaseId, cleanup: param0Cleanup } = enumHelpers.APIResult.lower(param0); - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModule9APIResultO_SS(closurePtr, param0CaseId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule9DirectionO_SS"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - let param0 = param0Id; - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule9DirectionO_SS"] = function(closurePtr) { - return function(param0) { - try { - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModule9DirectionO_SS(closurePtr, param0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModule9DirectionO_Sb"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - let param0 = param0Id; - const result = callback(param0); - return result ? 1 : 0; - } catch (error) { - setException?.(error); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModule9DirectionO_Sb"] = function(closurePtr) { - return function(param0) { - try { - return instance.exports.invoke_swift_closure_TestModule_10TestModule9DirectionO_Sb(closurePtr, param0) !== 0; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0Id) { - try { - const callback = swift.memory.getObject(callbackId); - const param0IdObject = swift.memory.getObject(param0Id); - swift.memory.release(param0Id); - let param0 = String(param0IdObject); - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSS_SS"] = function(closurePtr) { - return function(param0) { - try { - const param0Bytes = textEncoder.encode(param0); - const param0Id = swift.memory.retain(param0Bytes); - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSS_SS(closurePtr, param0Id, param0Bytes.length); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_SS"] = function(callbackId, param0IsSome, param0Value) { - try { - const callback = swift.memory.getObject(callbackId); - let param0; - if (param0IsSome) { - const param0Object = swift.memory.getObject(param0Value); - swift.memory.release(param0Value); - param0 = String(param0Object); - } else { - param0 = null; - } - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSq5ThemeO_SS"] = function(closurePtr) { - return function(param0) { - try { - const isSome = param0 != null; - let param0Id, param0Bytes; - if (isSome) { - param0Bytes = textEncoder.encode(param0); - param0Id = swift.memory.retain(param0Bytes); - } - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_SS(closurePtr, +isSome, isSome ? param0Id : 0, isSome ? param0Bytes.length : 0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS"] = function(callbackId, param0IsSome, param0Value, param1IsSome, param1Value, param2IsSome, param2Value) { - try { - const callback = swift.memory.getObject(callbackId); - let param0; - if (param0IsSome) { - param0 = _exports['Person'].__construct(param0Value); - } else { - param0 = null; - } - let param1; - if (param1IsSome) { - const param1Object = swift.memory.getObject(param1Value); - swift.memory.release(param1Value); - param1 = String(param1Object); - } else { - param1 = null; - } - let param2; - if (param2IsSome) { - param2 = param2Value; - } else { - param2 = null; - } - const result = callback(param0, param1, param2); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS"] = function(closurePtr) { - return function(param0, param1, param2) { - try { - const isSome = param0 != null; - const isSome1 = param1 != null; - let param1Id, param1Bytes; - if (isSome1) { - param1Bytes = textEncoder.encode(param1); - param1Id = swift.memory.retain(param1Bytes); - } - const isSome2 = param2 != null; - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS(closurePtr, +isSome, isSome ? param0.pointer : 0, +isSome1, isSome1 ? param1Id : 0, isSome1 ? param1Bytes.length : 0, +isSome2, isSome2 ? param2 : 0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSq6PersonC_SS"] = function(callbackId, param0IsSome, param0Value) { - try { - const callback = swift.memory.getObject(callbackId); - let param0; - if (param0IsSome) { - param0 = _exports['Person'].__construct(param0Value); - } else { - param0 = null; - } - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSq6PersonC_SS"] = function(closurePtr) { - return function(param0) { - try { - const isSome = param0 != null; - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6PersonC_SS(closurePtr, +isSome, isSome ? param0.pointer : 0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSq9APIResultO_SS"] = function(callbackId, param0IsSome, param0Value) { - try { - const callback = swift.memory.getObject(callbackId); - let param0; - if (param0IsSome) { - param0 = enumHelpers.APIResult.lift(param0Value, tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s); - } else { - param0 = null; - } - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSq9APIResultO_SS"] = function(closurePtr) { - return function(param0) { - try { - const isSome = param0 != null; - let param0CaseId, param0Cleanup; - if (isSome) { - const enumResult = enumHelpers.APIResult.lower(param0); - param0CaseId = enumResult.caseId; - param0Cleanup = enumResult.cleanup; - } - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_SS(closurePtr, +isSome, isSome ? param0CaseId : 0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - - bjs["invoke_js_callback_TestModule_10TestModuleSq9DirectionO_SS"] = function(callbackId, param0IsSome, param0Value) { - try { - const callback = swift.memory.getObject(callbackId); - let param0; - if (param0IsSome) { - param0 = param0Value; - } else { - param0 = null; - } - const result = callback(param0); - if (typeof result !== "string") { - throw new TypeError("Callback must return a string"); - } - tmpRetBytes = textEncoder.encode(result); - return tmpRetBytes.length; - } catch (error) { - setException?.(error); - tmpRetBytes = new Uint8Array(0); - return 0; - } - }; - - bjs["lower_closure_TestModule_10TestModuleSq9DirectionO_SS"] = function(closurePtr) { - return function(param0) { - try { - const isSome = param0 != null; - const resultLen = instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_SS(closurePtr, +isSome, isSome ? param0 : 0); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } catch (error) { - setException?.(error); - throw error; - } - }; - }; - // Wrapper functions for module: TestModule - if (!importObject["TestModule"]) { - importObject["TestModule"] = {}; - } - importObject["TestModule"]["bjs_Person_wrap"] = function(pointer) { - const obj = Person.__construct(pointer); - return swift.memory.retain(obj); - }; - importObject["TestModule"]["bjs_TestProcessor_wrap"] = function(pointer) { - const obj = TestProcessor.__construct(pointer); - return swift.memory.retain(obj); - }; - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - const APIResultHelpers = __bjs_createAPIResultValuesHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, textEncoder, swift); - enumHelpers.APIResult = APIResultHelpers; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - /// Represents a Swift heap object like a class instance or an actor instance. - class SwiftHeapObject { - static __wrap(pointer, deinit, prototype) { - const obj = Object.create(prototype); - obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); - return obj; - } - - release() { - this.registry.unregister(this); - this.deinit(this.pointer); - } - } - class Person extends SwiftHeapObject { - static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Person_deinit, Person.prototype); - } - - constructor(name) { - const nameBytes = textEncoder.encode(name); - const nameId = swift.memory.retain(nameBytes); - const ret = instance.exports.bjs_Person_init(nameId, nameBytes.length); - swift.memory.release(nameId); - return Person.__construct(ret); - } - } - class TestProcessor extends SwiftHeapObject { - static __construct(ptr) { - return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestProcessor_deinit, TestProcessor.prototype); - } - - constructor(transform) { - const callbackId = swift.memory.retain(transform); - const ret = instance.exports.bjs_TestProcessor_init(callbackId); - return TestProcessor.__construct(ret); - } - getTransform() { - const ret = instance.exports.bjs_TestProcessor_getTransform(this.pointer); - return bjs["lower_closure_TestModule_10TestModuleSS_SS"](ret); - } - processWithCustom(text, customTransform) { - const textBytes = textEncoder.encode(text); - const textId = swift.memory.retain(textBytes); - const callbackId = swift.memory.retain(customTransform); - instance.exports.bjs_TestProcessor_processWithCustom(this.pointer, textId, textBytes.length, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - swift.memory.release(textId); - return ret; - } - printTogether(person, name, ratio, customTransform) { - const nameBytes = textEncoder.encode(name); - const nameId = swift.memory.retain(nameBytes); - const callbackId = swift.memory.retain(customTransform); - instance.exports.bjs_TestProcessor_printTogether(this.pointer, person.pointer, nameId, nameBytes.length, ratio, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - swift.memory.release(nameId); - return ret; - } - roundtrip(personClosure) { - const callbackId = swift.memory.retain(personClosure); - const ret = instance.exports.bjs_TestProcessor_roundtrip(this.pointer, callbackId); - return bjs["lower_closure_TestModule_10TestModule6PersonC_SS"](ret); - } - roundtripOptional(personClosure) { - const callbackId = swift.memory.retain(personClosure); - const ret = instance.exports.bjs_TestProcessor_roundtripOptional(this.pointer, callbackId); - return bjs["lower_closure_TestModule_10TestModuleSq6PersonC_SS"](ret); - } - processDirection(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processDirection(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - processTheme(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processTheme(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - processHttpStatus(callback) { - const callbackId = swift.memory.retain(callback); - const ret = instance.exports.bjs_TestProcessor_processHttpStatus(this.pointer, callbackId); - return ret; - } - processAPIResult(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processAPIResult(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - makeDirectionChecker() { - const ret = instance.exports.bjs_TestProcessor_makeDirectionChecker(this.pointer); - return bjs["lower_closure_TestModule_10TestModule9DirectionO_Sb"](ret); - } - makeThemeValidator() { - const ret = instance.exports.bjs_TestProcessor_makeThemeValidator(this.pointer); - return bjs["lower_closure_TestModule_10TestModule5ThemeO_Sb"](ret); - } - makeStatusCodeExtractor() { - const ret = instance.exports.bjs_TestProcessor_makeStatusCodeExtractor(this.pointer); - return bjs["lower_closure_TestModule_10TestModule10HttpStatusO_Si"](ret); - } - makeAPIResultHandler() { - const ret = instance.exports.bjs_TestProcessor_makeAPIResultHandler(this.pointer); - return bjs["lower_closure_TestModule_10TestModule9APIResultO_SS"](ret); - } - processOptionalDirection(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processOptionalDirection(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - processOptionalTheme(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processOptionalTheme(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - processOptionalAPIResult(callback) { - const callbackId = swift.memory.retain(callback); - instance.exports.bjs_TestProcessor_processOptionalAPIResult(this.pointer, callbackId); - const ret = tmpRetString; - tmpRetString = undefined; - return ret; - } - makeOptionalDirectionFormatter() { - const ret = instance.exports.bjs_TestProcessor_makeOptionalDirectionFormatter(this.pointer); - return bjs["lower_closure_TestModule_10TestModuleSq9DirectionO_SS"](ret); - } - } - const exports = { - Person, - TestProcessor, - Direction: DirectionValues, - Theme: ThemeValues, - HttpStatus: HttpStatusValues, - APIResult: APIResultValues, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts similarity index 52% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index 942b18269..ccc95eb3b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -59,23 +59,6 @@ export interface SwiftHeapObject { export interface Person extends SwiftHeapObject { } export interface TestProcessor extends SwiftHeapObject { - getTransform(): (arg0: string) => string; - processWithCustom(text: string, customTransform: (arg0: string) => string): string; - printTogether(person: Person, name: string, ratio: number, customTransform: (arg0: Person | null, arg1: string | null, arg2: number | null) => string): string; - roundtrip(personClosure: (arg0: Person) => string): (arg0: Person) => string; - roundtripOptional(personClosure: (arg0: Person | null) => string): (arg0: Person | null) => string; - processDirection(callback: (arg0: DirectionTag) => string): string; - processTheme(callback: (arg0: ThemeTag) => string): string; - processHttpStatus(callback: (arg0: HttpStatusTag) => number): number; - processAPIResult(callback: (arg0: APIResultTag) => string): string; - makeDirectionChecker(): (arg0: DirectionTag) => boolean; - makeThemeValidator(): (arg0: ThemeTag) => boolean; - makeStatusCodeExtractor(): (arg0: HttpStatusTag) => number; - makeAPIResultHandler(): (arg0: APIResultTag) => string; - processOptionalDirection(callback: (arg0: DirectionTag | null) => string): string; - processOptionalTheme(callback: (arg0: ThemeTag | null) => string): string; - processOptionalAPIResult(callback: (arg0: APIResultTag | null) => string): string; - makeOptionalDirectionFormatter(): (arg0: DirectionTag | null) => string; } export type Exports = { Person: { @@ -84,6 +67,27 @@ export type Exports = { TestProcessor: { new(transform: (arg0: string) => string): TestProcessor; } + roundtripString(stringClosure: (arg0: string) => string): (arg0: string) => string; + roundtripInt(intClosure: (arg0: number) => number): (arg0: number) => number; + roundtripBool(boolClosure: (arg0: boolean) => boolean): (arg0: boolean) => boolean; + roundtripFloat(floatClosure: (arg0: number) => number): (arg0: number) => number; + roundtripDouble(doubleClosure: (arg0: number) => number): (arg0: number) => number; + roundtripOptionalString(stringClosure: (arg0: string | null) => string | null): (arg0: string | null) => string | null; + roundtripOptionalInt(intClosure: (arg0: number | null) => number | null): (arg0: number | null) => number | null; + roundtripOptionalBool(boolClosure: (arg0: boolean | null) => boolean | null): (arg0: boolean | null) => boolean | null; + roundtripOptionalFloat(floatClosure: (arg0: number | null) => number | null): (arg0: number | null) => number | null; + roundtripOptionalDouble(doubleClosure: (arg0: number | null) => number | null): (arg0: number | null) => number | null; + roundtripPerson(personClosure: (arg0: Person) => Person): (arg0: Person) => Person; + roundtripOptionalPerson(personClosure: (arg0: Person | null) => Person | null): (arg0: Person | null) => Person | null; + roundtripDirection(callback: (arg0: DirectionTag) => DirectionTag): (arg0: DirectionTag) => DirectionTag; + roundtripTheme(callback: (arg0: ThemeTag) => ThemeTag): (arg0: ThemeTag) => ThemeTag; + roundtripHttpStatus(callback: (arg0: HttpStatusTag) => HttpStatusTag): (arg0: HttpStatusTag) => HttpStatusTag; + roundtripAPIResult(callback: (arg0: APIResultTag) => APIResultTag): (arg0: APIResultTag) => APIResultTag; + roundtripOptionalDirection(callback: (arg0: DirectionTag | null) => DirectionTag | null): (arg0: DirectionTag | null) => DirectionTag | null; + roundtripOptionalTheme(callback: (arg0: ThemeTag | null) => ThemeTag | null): (arg0: ThemeTag | null) => ThemeTag | null; + roundtripOptionalHttpStatus(callback: (arg0: HttpStatusTag | null) => HttpStatusTag | null): (arg0: HttpStatusTag | null) => HttpStatusTag | null; + roundtripOptionalAPIResult(callback: (arg0: APIResultTag | null) => APIResultTag | null): (arg0: APIResultTag | null) => APIResultTag | null; + roundtripOptionalDirection(callback: (arg0: DirectionTag | null) => DirectionTag | null): (arg0: DirectionTag | null) => DirectionTag | null; Direction: DirectionObject Theme: ThemeObject HttpStatus: HttpStatusObject diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js new file mode 100644 index 000000000..023a2fab0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -0,0 +1,1070 @@ +// 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 DirectionValues = { + North: 0, + South: 1, + East: 2, + West: 3, +}; + +export const ThemeValues = { + Light: "light", + Dark: "dark", + Auto: "auto", +}; + +export const HttpStatusValues = { + Ok: 200, + NotFound: 404, + ServerError: 500, + Unknown: -1, +}; + +export const APIResultValues = { + Tag: { + Success: 0, + Failure: 1, + Flag: 2, + Rate: 3, + Precise: 4, + Info: 5, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.unregistered) { return; } + instance?.exports?.bjs_release_swift_closure(state.pointer); + }); + const makeClosure = (pointer, file, line, func) => { + const state = { pointer, file, line, unregistered: false }; + const real = (...args) => { + if (state.unregistered) { + const bytes = new Uint8Array(memory.buffer, state.file); + let length = 0; + while (bytes[length] !== 0) { length += 1; } + const fileID = textDecoder.decode(bytes.subarray(0, 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_createAPIResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case APIResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return APIResultValues.Tag.Success; + } + case APIResultValues.Tag.Failure: { + i32Stack.push((value.param0 | 0)); + return APIResultValues.Tag.Failure; + } + case APIResultValues.Tag.Flag: { + i32Stack.push(value.param0 ? 1 : 0); + return APIResultValues.Tag.Flag; + } + case APIResultValues.Tag.Rate: { + f32Stack.push(Math.fround(value.param0)); + return APIResultValues.Tag.Rate; + } + case APIResultValues.Tag.Precise: { + f64Stack.push(value.param0); + return APIResultValues.Tag.Precise; + } + case APIResultValues.Tag.Info: { + return APIResultValues.Tag.Info; + } + default: throw new Error("Unknown APIResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case APIResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: APIResultValues.Tag.Success, param0: string }; + } + case APIResultValues.Tag.Failure: { + const int = i32Stack.pop(); + return { tag: APIResultValues.Tag.Failure, param0: int }; + } + case APIResultValues.Tag.Flag: { + const bool = i32Stack.pop() !== 0; + return { tag: APIResultValues.Tag.Flag, param0: bool }; + } + case APIResultValues.Tag.Rate: { + const f32 = f32Stack.pop(); + return { tag: APIResultValues.Tag.Rate, param0: f32 }; + } + case APIResultValues.Tag.Precise: { + const f64 = f64Stack.pop(); + return { tag: APIResultValues.Tag.Precise, param0: f64 }; + } + case APIResultValues.Tag.Info: return { tag: APIResultValues.Tag.Info }; + default: throw new Error("Unknown APIResultValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + return swift.memory.retain(textDecoder.decode(bytes)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const bytes = new Uint8Array(memory.buffer, ptr, len); + const value = textDecoder.decode(bytes); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + const bytes = new Uint8Array(memory.buffer, ptr, len); + tmpRetString = textDecoder.decode(bytes); + } + } + 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_10TestModule10HttpStatusO_10HttpStatusO"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule10HttpStatusO_10HttpStatusO); + } + bjs["invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + const param0Object = swift.memory.getObject(param0); + swift.memory.release(param0); + let ret = callback(param0Object); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule5ThemeO_5ThemeO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule5ThemeO_5ThemeO = function(param0) { + 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; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule5ThemeO_5ThemeO); + } + bjs["invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(_exports['Person'].__construct(param0)); + return ret.pointer; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModule6PersonC_6PersonC"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule6PersonC_6PersonC = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule6PersonC_6PersonC(boxPtr, param0.pointer); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return _exports['Person'].__construct(ret); + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule6PersonC_6PersonC); + } + bjs["invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + const enumValue = enumHelpers.APIResult.lift(param0); + let ret = callback(enumValue); + const caseId = enumHelpers.APIResult.lower(ret); + return caseId; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule9APIResultO_9APIResultO = function(param0) { + const param0CaseId = enumHelpers.APIResult.lower(param0); + instance.exports.invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(boxPtr, param0CaseId); + const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule9APIResultO_9APIResultO); + } + bjs["invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule9DirectionO_9DirectionO = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule9DirectionO_9DirectionO); + } + bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + const param0Object = swift.memory.getObject(param0); + swift.memory.release(param0); + let ret = callback(param0Object); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSS_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSS_SS = function(param0) { + 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; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSS_SS); + } + bjs["invoke_js_callback_TestModule_10TestModuleSb_Sb"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0 !== 0); + return ret ? 1 : 0; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleSb_Sb"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSb_Sb = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleSb_Sb(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret !== 0; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSb_Sb); + } + bjs["invoke_js_callback_TestModule_10TestModuleSd_Sd"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleSd_Sd"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSd_Sd = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleSd_Sd(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSd_Sd); + } + bjs["invoke_js_callback_TestModule_10TestModuleSf_Sf"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleSf_Sf"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSf_Sf = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleSf_Sf(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSf_Sf); + } + bjs["invoke_js_callback_TestModule_10TestModuleSi_Si"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleSi_Si"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSi_Si = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleSi_Si(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSi_Si); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(callbackId, param0IsSome, param0ObjectId) { + try { + const callback = swift.memory.getObject(callbackId); + let optResult; + if (param0IsSome) { + const param0ObjectIdObject = swift.memory.getObject(param0ObjectId); + swift.memory.release(param0ObjectId); + optResult = param0ObjectIdObject; + } else { + optResult = null; + } + let ret = callback(optResult); + const isSome = ret != null; + tmpRetString = isSome ? ret : null; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO = function(param0) { + const isSome = param0 != null; + let result, result1; + if (isSome) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + result = param0Id; + result1 = param0Bytes.length; + } else { + result = 0; + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC"] = function(callbackId, param0IsSome, param0Pointer) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? _exports['Person'].__construct(param0Pointer) : null); + const isSome = ret != null; + return isSome ? ret.pointer : 0; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC = function(param0) { + const isSome = param0 != null; + let result; + if (isSome) { + result = param0.pointer; + } else { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq6PersonC_Sq6PersonC); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO"] = function(callbackId, param0IsSome, param0CaseId) { + try { + const callback = swift.memory.getObject(callbackId); + let optResult; + if (param0IsSome) { + const enumValue = enumHelpers.APIResult.lift(param0CaseId); + optResult = enumValue; + } else { + optResult = null; + } + let ret = callback(optResult); + const isSome = ret != null; + if (isSome) { + const caseId = enumHelpers.APIResult.lower(ret); + return caseId; + } else { + return -1; + } + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO = function(param0) { + const isSome = param0 != null; + let result; + if (isSome) { + const param0CaseId = enumHelpers.APIResult.lower(param0); + result = param0CaseId; + } else { + result = 0; + } + instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(boxPtr, +isSome, result); + const tag = i32Stack.pop(); + const optResult = tag === -1 ? null : enumHelpers.APIResult.lift(tag); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO); + } + bjs["invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue : null); + const isSome = ret != null; + return isSome ? ret : -1; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO); + } + bjs["invoke_js_callback_TestModule_10TestModuleSqSS_SqSS"] = function(callbackId, param0IsSome, param0ObjectId) { + try { + const callback = swift.memory.getObject(callbackId); + let optResult; + if (param0IsSome) { + const param0ObjectIdObject = swift.memory.getObject(param0ObjectId); + swift.memory.release(param0ObjectId); + optResult = param0ObjectIdObject; + } else { + optResult = null; + } + let ret = callback(optResult); + const isSome = ret != null; + tmpRetString = isSome ? ret : null; + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSqSS_SqSS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSqSS_SqSS = function(param0) { + const isSome = param0 != null; + let result, result1; + if (isSome) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + result = param0Id; + result1 = param0Bytes.length; + } else { + result = 0; + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSS_SqSS); + } + bjs["invoke_js_callback_TestModule_10TestModuleSqSb_SqSb"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue !== 0 : null); + const isSome = ret != null; + bjs["swift_js_return_optional_bool"](isSome ? 1 : 0, isSome ? (ret ? 1 : 0) : 0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSqSb_SqSb"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSb_SqSb); + } + bjs["invoke_js_callback_TestModule_10TestModuleSqSd_SqSd"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_double"](isSome ? 1 : 0, isSome ? ret : 0.0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSqSd_SqSd"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSd_SqSd); + } + bjs["invoke_js_callback_TestModule_10TestModuleSqSf_SqSf"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_float"](isSome ? 1 : 0, isSome ? Math.fround(ret) : 0.0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSqSf_SqSf"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSf_SqSf); + } + bjs["invoke_js_callback_TestModule_10TestModuleSqSi_SqSi"] = function(callbackId, param0IsSome, param0WrappedValue) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(param0IsSome ? param0WrappedValue : null); + const isSome = ret != null; + bjs["swift_js_return_optional_int"](isSome ? 1 : 0, isSome ? (ret | 0) : 0); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModuleSqSi_SqSi"] = function(boxPtr, file, line) { + 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; + } + return optResult; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSi_SqSi); + } + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Person_wrap"] = function(pointer) { + const obj = _exports['Person'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_TestProcessor_wrap"] = function(pointer) { + const obj = _exports['TestProcessor'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype) { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + return obj; + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); + } + } + class Person extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Person_deinit, Person.prototype); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_Person_init(nameId, nameBytes.length); + return Person.__construct(ret); + } + } + class TestProcessor extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TestProcessor_deinit, TestProcessor.prototype); + } + + constructor(transform) { + const callbackId = swift.memory.retain(transform); + const ret = instance.exports.bjs_TestProcessor_init(callbackId); + return TestProcessor.__construct(ret); + } + } + const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); + enumHelpers.APIResult = APIResultHelpers; + + const exports = { + Person, + TestProcessor, + roundtripString: function bjs_roundtripString(stringClosure) { + const callbackId = swift.memory.retain(stringClosure); + const ret = instance.exports.bjs_roundtripString(callbackId); + return swift.memory.getObject(ret); + }, + roundtripInt: function bjs_roundtripInt(intClosure) { + const callbackId = swift.memory.retain(intClosure); + const ret = instance.exports.bjs_roundtripInt(callbackId); + return swift.memory.getObject(ret); + }, + roundtripBool: function bjs_roundtripBool(boolClosure) { + const callbackId = swift.memory.retain(boolClosure); + const ret = instance.exports.bjs_roundtripBool(callbackId); + return swift.memory.getObject(ret); + }, + roundtripFloat: function bjs_roundtripFloat(floatClosure) { + const callbackId = swift.memory.retain(floatClosure); + const ret = instance.exports.bjs_roundtripFloat(callbackId); + return swift.memory.getObject(ret); + }, + roundtripDouble: function bjs_roundtripDouble(doubleClosure) { + const callbackId = swift.memory.retain(doubleClosure); + const ret = instance.exports.bjs_roundtripDouble(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalString: function bjs_roundtripOptionalString(stringClosure) { + const callbackId = swift.memory.retain(stringClosure); + const ret = instance.exports.bjs_roundtripOptionalString(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalInt: function bjs_roundtripOptionalInt(intClosure) { + const callbackId = swift.memory.retain(intClosure); + const ret = instance.exports.bjs_roundtripOptionalInt(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalBool: function bjs_roundtripOptionalBool(boolClosure) { + const callbackId = swift.memory.retain(boolClosure); + const ret = instance.exports.bjs_roundtripOptionalBool(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalFloat: function bjs_roundtripOptionalFloat(floatClosure) { + const callbackId = swift.memory.retain(floatClosure); + const ret = instance.exports.bjs_roundtripOptionalFloat(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalDouble: function bjs_roundtripOptionalDouble(doubleClosure) { + const callbackId = swift.memory.retain(doubleClosure); + const ret = instance.exports.bjs_roundtripOptionalDouble(callbackId); + return swift.memory.getObject(ret); + }, + roundtripPerson: function bjs_roundtripPerson(personClosure) { + const callbackId = swift.memory.retain(personClosure); + const ret = instance.exports.bjs_roundtripPerson(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalPerson: function bjs_roundtripOptionalPerson(personClosure) { + const callbackId = swift.memory.retain(personClosure); + const ret = instance.exports.bjs_roundtripOptionalPerson(callbackId); + return swift.memory.getObject(ret); + }, + roundtripDirection: function bjs_roundtripDirection(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripDirection(callbackId); + return swift.memory.getObject(ret); + }, + roundtripTheme: function bjs_roundtripTheme(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripTheme(callbackId); + return swift.memory.getObject(ret); + }, + roundtripHttpStatus: function bjs_roundtripHttpStatus(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripHttpStatus(callbackId); + return swift.memory.getObject(ret); + }, + roundtripAPIResult: function bjs_roundtripAPIResult(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripAPIResult(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalDirection: function bjs_roundtripOptionalDirection(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripOptionalDirection(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalTheme: function bjs_roundtripOptionalTheme(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripOptionalTheme(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalHttpStatus: function bjs_roundtripOptionalHttpStatus(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripOptionalHttpStatus(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalAPIResult: function bjs_roundtripOptionalAPIResult(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripOptionalAPIResult(callbackId); + return swift.memory.getObject(ret); + }, + roundtripOptionalDirection: function bjs_roundtripOptionalDirection(callback) { + const callbackId = swift.memory.retain(callback); + const ret = instance.exports.bjs_roundtripOptionalDirection(callbackId); + return swift.memory.getObject(ret); + }, + Direction: DirectionValues, + Theme: ThemeValues, + HttpStatus: HttpStatusValues, + APIResult: APIResultValues, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.ImportMacros.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.ImportMacros.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.ImportMacros.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js similarity index 74% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.ImportMacros.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 9ab218df1..b5efd2150 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.ImportMacros.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -18,22 +18,41 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.unregistered) { return; } + instance?.exports?.bjs_release_swift_closure(state.pointer); + }); + const makeClosure = (pointer, file, line, func) => { + const state = { pointer, file, line, unregistered: false }; + const real = (...args) => { + if (state.unregistered) { + const bytes = new Uint8Array(memory.buffer, state.file); + let length = 0; + while (bytes[length] !== 0) { length += 1; } + const fileID = textDecoder.decode(bytes.subarray(0, length)); + throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); + } + return func(...args); + }; + real.__unregister = () => { + if (state.unregistered) { return; } + state.unregistered = true; + swiftClosureRegistry.unregister(state); + }; + swiftClosureRegistry.register(real, state, state); + return swift.memory.retain(real); + }; + return { /** @@ -49,6 +68,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +90,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,33 +209,38 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } - - bjs["invoke_js_callback_TestModule_10TestModuleSi_Si"] = function(callbackId, param0Id) { + 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_10TestModuleSi_Si"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); - let param0 = param0Id; - const result = callback(param0); - return result | 0; + let ret = callback(param0); + return ret; } catch (error) { - setException?.(error); - return 0; + setException(error); + return 0 } - }; - - bjs["lower_closure_TestModule_10TestModuleSi_Si"] = function(closurePtr) { - return function(param0) { - try { - return instance.exports.invoke_swift_closure_TestModule_10TestModuleSi_Si(closurePtr, param0) | 0; - } catch (error) { - setException?.(error); + } + bjs["make_swift_closure_TestModule_10TestModuleSi_Si"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleSi_Si = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleSi_Si(boxPtr, param0); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; throw error; } + return ret; }; - }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSi_Si); + } const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_applyInt"] = function bjs_applyInt(value, transform) { try { - let ret = imports.applyInt(value, bjs["lower_closure_TestModule_10TestModuleSi_Si"](transform)); + let ret = imports.applyInt(value, swift.memory.getObject(transform)); return ret; } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts similarity index 93% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 7769ebcbe..4a61a26e3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -39,6 +39,10 @@ export interface Measurement { } export interface ConfigStruct { } +export interface Container { + object: any; + optionalObject: any | null; +} export type PrecisionObject = typeof PrecisionValues; /// Represents a Swift heap object like a class instance or an actor instance. @@ -57,6 +61,7 @@ export type Exports = { new(name: string): Greeter; } roundtrip(session: Person): Person; + roundtripContainer(container: Container): Container; Precision: PrecisionObject DataPoint: { init(x: number, y: number, label: string, optCount: number | null, optFlag: boolean | null): DataPoint; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js similarity index 50% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index a3d60d0bd..cc973e379 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -23,211 +23,224 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; - const __bjs_createDataPointHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamF64s.push(value.x); - tmpParamF64s.push(value.y); - const bytes = textEncoder.encode(value.label); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const isSome = value.optCount != null; - if (isSome) { - tmpParamInts.push(value.optCount | 0); - } else { - tmpParamInts.push(0); - } - tmpParamInts.push(isSome ? 1 : 0); - const isSome1 = value.optFlag != null; - if (isSome1) { - tmpParamInts.push(value.optFlag ? 1 : 0); - } else { - tmpParamInts.push(0); - } - tmpParamInts.push(isSome1 ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - }; - return { cleanup }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const bool = tmpRetInts.pop() !== 0; - optional = bool; - } else { - optional = null; - } - const isSome1 = tmpRetInts.pop(); - let optional1; - if (isSome1) { - const int = tmpRetInts.pop(); - optional1 = int; - } else { - optional1 = null; - } - const string = tmpRetStrings.pop(); - const f64 = tmpRetF64s.pop(); - const f641 = tmpRetF64s.pop(); - return { x: f641, y: f64, label: string, optCount: optional1, optFlag: optional }; - } - }); - }; - const __bjs_createAddressHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - const bytes = textEncoder.encode(value.street); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - const bytes1 = textEncoder.encode(value.city); + const __bjs_createDataPointHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.x); + f64Stack.push(value.y); + const bytes = textEncoder.encode(value.label); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + const isSome = value.optCount != null; + if (isSome) { + i32Stack.push((value.optCount | 0)); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + const isSome1 = value.optFlag != null; + if (isSome1) { + i32Stack.push(value.optFlag ? 1 : 0); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome1 ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const bool = i32Stack.pop() !== 0; + optional = bool; + } else { + optional = null; + } + const isSome1 = i32Stack.pop(); + let optional1; + if (isSome1) { + const int = i32Stack.pop(); + optional1 = int; + } else { + optional1 = null; + } + const string = strStack.pop(); + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + return { x: f641, y: f64, label: string, optCount: optional1, optFlag: optional }; + } + }); + const __bjs_createAddressHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.street); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + const bytes1 = textEncoder.encode(value.city); + const id1 = swift.memory.retain(bytes1); + i32Stack.push(bytes1.length); + i32Stack.push(id1); + const isSome = value.zipCode != null; + if (isSome) { + i32Stack.push((value.zipCode | 0)); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const int = i32Stack.pop(); + optional = int; + } else { + optional = null; + } + const string = strStack.pop(); + const string1 = strStack.pop(); + return { street: string1, city: string, zipCode: optional }; + } + }); + const __bjs_createPersonHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.name); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value.age | 0)); + structHelpers.Address.lower(value.address); + const isSome = value.email != null; + if (isSome) { + const bytes1 = textEncoder.encode(value.email); const id1 = swift.memory.retain(bytes1); - tmpParamInts.push(bytes1.length); - tmpParamInts.push(id1); - const isSome = value.zipCode != null; - if (isSome) { - tmpParamInts.push(value.zipCode | 0); - } else { - tmpParamInts.push(0); - } - tmpParamInts.push(isSome ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - swift.memory.release(id1); - }; - return { cleanup }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const int = tmpRetInts.pop(); - optional = int; - } else { - optional = null; - } - const string = tmpRetStrings.pop(); - const string1 = tmpRetStrings.pop(); - return { street: string1, city: string, zipCode: optional }; - } - }); - }; - const __bjs_createPersonHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - const bytes = textEncoder.encode(value.name); - const id = swift.memory.retain(bytes); - tmpParamInts.push(bytes.length); - tmpParamInts.push(id); - tmpParamInts.push((value.age | 0)); - const structResult = structHelpers.Address.lower(value.address); - const isSome = value.email != null; + i32Stack.push(bytes1.length); + i32Stack.push(id1); + } else { + i32Stack.push(0); + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const string = strStack.pop(); + optional = string; + } else { + optional = null; + } + const struct = structHelpers.Address.lift(); + const int = i32Stack.pop(); + const string1 = strStack.pop(); + return { name: string1, age: int, address: struct, email: optional }; + } + }); + const __bjs_createSessionHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.id | 0)); + ptrStack.push(value.owner.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['Greeter'].__construct(ptr); + const int = i32Stack.pop(); + return { id: int, owner: obj }; + } + }); + const __bjs_createMeasurementHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.value); + f32Stack.push(Math.fround(value.precision)); + const isSome = value.optionalPrecision != null; + if (isSome) { + f32Stack.push(Math.fround(value.optionalPrecision)); + } else { + f32Stack.push(0.0); + } + i32Stack.push(isSome ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const rawValue = f32Stack.pop(); + optional = rawValue; + } else { + optional = null; + } + const rawValue1 = f32Stack.pop(); + const f64 = f64Stack.pop(); + return { value: f64, precision: rawValue1, optionalPrecision: optional }; + } + }); + const __bjs_createConfigStructHelpers = () => ({ + lower: (value) => { + }, + lift: () => { + return { }; + } + }); + const __bjs_createContainerHelpers = () => ({ + lower: (value) => { + let id; + if (value.object != null) { + id = swift.memory.retain(value.object); + } else { + id = undefined; + } + i32Stack.push(id !== undefined ? id : 0); + const isSome = value.optionalObject != null; + if (isSome) { let id1; - if (isSome) { - const bytes1 = textEncoder.encode(value.email); - id1 = swift.memory.retain(bytes1); - tmpParamInts.push(bytes1.length); - tmpParamInts.push(id1); + if (value.optionalObject != null) { + id1 = swift.memory.retain(value.optionalObject); } else { - tmpParamInts.push(0); - tmpParamInts.push(0); + id1 = undefined; } - tmpParamInts.push(isSome ? 1 : 0); - const cleanup = () => { - swift.memory.release(id); - if (structResult.cleanup) { structResult.cleanup(); } - if(id1 !== undefined) { swift.memory.release(id1); } - }; - return { cleanup }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const string = tmpRetStrings.pop(); - optional = string; - } else { - optional = null; - } - const struct = structHelpers.Address.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - const int = tmpRetInts.pop(); - const string1 = tmpRetStrings.pop(); - return { name: string1, age: int, address: struct, email: optional }; - } - }); - }; - const __bjs_createSessionHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamInts.push((value.id | 0)); - tmpParamPointers.push(value.owner.pointer); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const ptr = tmpRetPointers.pop(); - const value = _exports['Greeter'].__construct(ptr); - const int = tmpRetInts.pop(); - return { id: int, owner: value }; - } - }); - }; - const __bjs_createMeasurementHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamF64s.push(value.value); - tmpParamF32s.push(Math.fround(value.precision)); - const isSome = value.optionalPrecision != null; - if (isSome) { - tmpParamF32s.push(Math.fround(value.optionalPrecision)); - } else { - tmpParamF32s.push(0.0); - } - tmpParamInts.push(isSome ? 1 : 0); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const isSome = tmpRetInts.pop(); - let optional; - if (isSome) { - const value = tmpRetF32s.pop(); - optional = value; + i32Stack.push(id1 !== undefined ? id1 : 0); + } else { + i32Stack.push(0); + } + i32Stack.push(isSome ? 1 : 0); + }, + lift: () => { + const isSome = i32Stack.pop(); + let optional; + if (isSome) { + const objectId = i32Stack.pop(); + let value; + if (objectId !== 0) { + value = swift.memory.getObject(objectId); + swift.memory.release(objectId); } else { - optional = null; - } - const value1 = tmpRetF32s.pop(); - const f64 = tmpRetF64s.pop(); - return { value: f64, precision: value1, optionalPrecision: optional }; - } - }); - }; - const __bjs_createConfigStructHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - return { }; - } - }); - }; + value = null; + } + optional = value; + } else { + optional = null; + } + const objectId1 = i32Stack.pop(); + let value1; + if (objectId1 !== 0) { + value1 = swift.memory.getObject(objectId1); + swift.memory.release(objectId1); + } else { + value1 = null; + } + return { object: value1, optionalObject: optional }; + } + }); return { /** @@ -242,6 +255,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -263,112 +277,82 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_struct_lower_DataPoint"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.DataPoint.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.DataPoint.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_DataPoint"] = function() { - const value = structHelpers.DataPoint.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.DataPoint.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Address"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Address.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Address.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Address"] = function() { - const value = structHelpers.Address.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Address.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Person"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Person.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Person.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Person"] = function() { - const value = structHelpers.Person.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Person.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Session"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Session.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Session.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Session"] = function() { - const value = structHelpers.Session.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Session.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Measurement"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Measurement.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.Measurement.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Measurement"] = function() { - const value = structHelpers.Measurement.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.Measurement.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_ConfigStruct"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.ConfigStruct.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.ConfigStruct.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_ConfigStruct"] = function() { - const value = structHelpers.ConfigStruct.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.ConfigStruct.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Container"] = function(objectId) { + structHelpers.Container.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Container"] = function() { + const value = structHelpers.Container.lift(); return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { @@ -461,12 +445,13 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; } importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { - const obj = Greeter.__construct(pointer); + const obj = _exports['Greeter'].__construct(pointer); return swift.memory.retain(obj); }; }, @@ -481,35 +466,44 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.deinit(state.pointer); + }); + /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype) { const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false }; obj.pointer = pointer; - obj.hasReleased = false; - obj.deinit = deinit; - obj.registry = new FinalizationRegistry((pointer) => { - deinit(pointer); - }); - obj.registry.register(this, obj.pointer); + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); return obj; } - + release() { - this.registry.unregister(this); - this.deinit(this.pointer); + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.deinit(state.pointer); } } class Greeter extends SwiftHeapObject { static __construct(ptr) { return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype); } - + constructor(name) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); - swift.memory.release(nameId); return Greeter.__construct(ret); } greet() { @@ -528,34 +522,41 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); - swift.memory.release(valueId); } } - const DataPointHelpers = __bjs_createDataPointHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + const DataPointHelpers = __bjs_createDataPointHelpers(); structHelpers.DataPoint = DataPointHelpers; - - const AddressHelpers = __bjs_createAddressHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const AddressHelpers = __bjs_createAddressHelpers(); structHelpers.Address = AddressHelpers; - - const PersonHelpers = __bjs_createPersonHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const PersonHelpers = __bjs_createPersonHelpers(); structHelpers.Person = PersonHelpers; - - const SessionHelpers = __bjs_createSessionHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const SessionHelpers = __bjs_createSessionHelpers(); structHelpers.Session = SessionHelpers; - - const MeasurementHelpers = __bjs_createMeasurementHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const MeasurementHelpers = __bjs_createMeasurementHelpers(); structHelpers.Measurement = MeasurementHelpers; - - const ConfigStructHelpers = __bjs_createConfigStructHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + + const ConfigStructHelpers = __bjs_createConfigStructHelpers(); structHelpers.ConfigStruct = ConfigStructHelpers; - + + const ContainerHelpers = __bjs_createContainerHelpers(); + structHelpers.Container = ContainerHelpers; + const exports = { Greeter, roundtrip: function bjs_roundtrip(session) { - const { cleanup: cleanup } = structHelpers.Person.lower(session); + structHelpers.Person.lower(session); instance.exports.bjs_roundtrip(); - const structValue = structHelpers.Person.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - if (cleanup) { cleanup(); } + const structValue = structHelpers.Person.lift(); + return structValue; + }, + roundtripContainer: function bjs_roundtripContainer(container) { + structHelpers.Container.lower(container); + instance.exports.bjs_roundtripContainer(); + const structValue = structHelpers.Container.lift(); return structValue; }, Precision: PrecisionValues, @@ -565,9 +566,8 @@ export async function createInstantiator(options, swift) { const labelId = swift.memory.retain(labelBytes); const isSome = optCount != null; const isSome1 = optFlag != null; - instance.exports.bjs_DataPoint_init(x, y, labelId, labelBytes.length, +isSome, isSome ? optCount : 0, +isSome1, isSome1 ? optFlag : 0); - const structValue = structHelpers.DataPoint.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - swift.memory.release(labelId); + instance.exports.bjs_DataPoint_init(x, y, labelId, labelBytes.length, +isSome, isSome ? optCount : 0, +isSome1, isSome1 ? optFlag ? 1 : 0 : 0); + const structValue = structHelpers.DataPoint.lift(); return structValue; }, }, @@ -586,7 +586,6 @@ export async function createInstantiator(options, swift) { const valueBytes = textEncoder.encode(value); const valueId = swift.memory.retain(valueBytes); instance.exports.bjs_ConfigStruct_static_defaultConfig_set(valueId, valueBytes.length); - swift.memory.release(valueId); }, get timeout() { const ret = instance.exports.bjs_ConfigStruct_static_timeout_get(); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.ImportMacros.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.ImportMacros.js deleted file mode 100644 index f4e7e61e9..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.ImportMacros.js +++ /dev/null @@ -1,262 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - const __bjs_createPointHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamInts.push((value.x | 0)); - tmpParamInts.push((value.y | 0)); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const int = tmpRetInts.pop(); - const int1 = tmpRetInts.pop(); - return { x: int1, y: int }; - } - }); - }; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_struct_lower_Point"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.Point.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; - } - bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - return swift.memory.retain(value); - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_translate"] = function bjs_translate(point, dx, dy) { - try { - const value = swift.memory.getObject(point); - swift.memory.release(point); - let ret = imports.translate(value, dx, dy); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const PointHelpers = __bjs_createPointHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); - structHelpers.Point = PointHelpers; - - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.ImportMacros.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.ImportMacros.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js similarity index 81% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 406d7f0f3..d00b7450d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -18,22 +18,27 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; + const __bjs_createPointHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.x | 0)); + i32Stack.push((value.y | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + const int1 = i32Stack.pop(); + return { x: int1, y: int }; + } + }); return { /** @@ -49,6 +54,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +76,41 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); + } + bjs["swift_js_struct_lower_Point"] = function(objectId) { + structHelpers.Point.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Point"] = function() { + const value = structHelpers.Point.lift(); + return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,10 +202,14 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_checkSimple"] = function bjs_checkSimple(a) { + TestModule["bjs_translate"] = function bjs_translate(point, dx, dy) { try { - imports.checkSimple(a); + const value = swift.memory.getObject(point); + swift.memory.release(point); + let ret = imports.translate(value, dx, dy); + return swift.memory.retain(ret); } catch (error) { setException(error); } @@ -222,6 +226,9 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const PointHelpers = __bjs_createPointHelpers(); + structHelpers.Point = PointHelpers; + const exports = { }; _exports = exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TS2SkeletonLike.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TS2SkeletonLike.Import.d.ts deleted file mode 100644 index 26d56fb6c..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TS2SkeletonLike.Import.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -// 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 TypeScriptProcessor { - convert(ts: string): string; - validate(ts: string): boolean; - readonly version: string; -} -export interface CodeGenerator { - generate(input: any): string; - readonly outputFormat: string; -} -export type Exports = { -} -export type Imports = { - createTS2Skeleton(): TypeScriptProcessor; - createCodeGenerator(format: string): CodeGenerator; -} -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/TS2SkeletonLike.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TS2SkeletonLike.Import.js deleted file mode 100644 index 45c273115..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TS2SkeletonLike.Import.js +++ /dev/null @@ -1,293 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - const imports = options.getImports(importsContext); - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_createTS2Skeleton"] = function bjs_createTS2Skeleton() { - try { - let ret = imports.createTS2Skeleton(); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_createCodeGenerator"] = function bjs_createCodeGenerator(format) { - try { - const formatObject = swift.memory.getObject(format); - swift.memory.release(format); - let ret = imports.createCodeGenerator(formatObject); - return swift.memory.retain(ret); - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_TypeScriptProcessor_version_get"] = function bjs_TypeScriptProcessor_version_get(self) { - try { - let ret = swift.memory.getObject(self).version; - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - TestModule["bjs_TypeScriptProcessor_convert"] = function bjs_TypeScriptProcessor_convert(self, ts) { - try { - const tsObject = swift.memory.getObject(ts); - swift.memory.release(ts); - let ret = swift.memory.getObject(self).convert(tsObject); - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - TestModule["bjs_TypeScriptProcessor_validate"] = function bjs_TypeScriptProcessor_validate(self, ts) { - try { - const tsObject = swift.memory.getObject(ts); - swift.memory.release(ts); - let ret = swift.memory.getObject(self).validate(tsObject); - return ret ? 1 : 0; - } catch (error) { - setException(error); - return 0 - } - } - TestModule["bjs_CodeGenerator_outputFormat_get"] = function bjs_CodeGenerator_outputFormat_get(self) { - try { - let ret = swift.memory.getObject(self).outputFormat; - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - TestModule["bjs_CodeGenerator_generate"] = function bjs_CodeGenerator_generate(self, input) { - try { - let ret = swift.memory.getObject(self).generate(swift.memory.getObject(input)); - tmpRetBytes = textEncoder.encode(ret); - return tmpRetBytes.length; - } catch (error) { - setException(error); - } - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 5a492295a..2c415fc31 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -48,6 +42,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -69,47 +64,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -201,6 +183,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { instance = i; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.d.ts deleted file mode 100644 index da5dfb076..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/TypeAlias.Import.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { -} -export type Imports = { - checkSimple(a: number): void; -} -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/UnsafePointer.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts similarity index 100% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.Export.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js similarity index 75% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.Export.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 2ac28b7e9..c141a7926 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.Export.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -18,42 +18,33 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; - const __bjs_createPointerFieldsHelpers = () => { - return (tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers) => ({ - lower: (value) => { - tmpParamPointers.push((value.raw | 0)); - tmpParamPointers.push((value.mutRaw | 0)); - tmpParamPointers.push((value.opaque | 0)); - tmpParamPointers.push((value.ptr | 0)); - tmpParamPointers.push((value.mutPtr | 0)); - return { cleanup: undefined }; - }, - lift: (tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers) => { - const pointer = tmpRetPointers.pop(); - const pointer1 = tmpRetPointers.pop(); - const pointer2 = tmpRetPointers.pop(); - const pointer3 = tmpRetPointers.pop(); - const pointer4 = tmpRetPointers.pop(); - return { raw: pointer4, mutRaw: pointer3, opaque: pointer2, ptr: pointer1, mutPtr: pointer }; - } - }); - }; + const __bjs_createPointerFieldsHelpers = () => ({ + lower: (value) => { + ptrStack.push((value.raw | 0)); + ptrStack.push((value.mutRaw | 0)); + ptrStack.push((value.opaque | 0)); + ptrStack.push((value.ptr | 0)); + ptrStack.push((value.mutPtr | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + const pointer1 = ptrStack.pop(); + const pointer2 = ptrStack.pop(); + const pointer3 = ptrStack.pop(); + const pointer4 = ptrStack.pop(); + return { raw: pointer4, mutRaw: pointer3, opaque: pointer2, ptr: pointer1, mutPtr: pointer }; + } + }); return { /** @@ -68,6 +59,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -89,57 +81,40 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_struct_lower_PointerFields"] = function(objectId) { - const { cleanup: cleanup } = structHelpers.PointerFields.lower(swift.memory.getObject(objectId)); - if (cleanup) { - return tmpStructCleanups.push(cleanup); - } - return 0; + structHelpers.PointerFields.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_PointerFields"] = function() { - const value = structHelpers.PointerFields.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const value = structHelpers.PointerFields.lift(); return swift.memory.retain(value); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { @@ -232,6 +207,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} }, setInstance: (i) => { instance = i; @@ -244,9 +220,9 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const PointerFieldsHelpers = __bjs_createPointerFieldsHelpers()(tmpParamInts, tmpParamF32s, tmpParamF64s, tmpParamPointers, tmpRetPointers, textEncoder, swift, enumHelpers); + const PointerFieldsHelpers = __bjs_createPointerFieldsHelpers(); structHelpers.PointerFields = PointerFieldsHelpers; - + const exports = { takeUnsafeRawPointer: function bjs_takeUnsafeRawPointer(p) { instance.exports.bjs_takeUnsafeRawPointer(p); @@ -284,16 +260,15 @@ export async function createInstantiator(options, swift) { return ret; }, roundTripPointerFields: function bjs_roundTripPointerFields(value) { - const { cleanup: cleanup } = structHelpers.PointerFields.lower(value); + structHelpers.PointerFields.lower(value); instance.exports.bjs_roundTripPointerFields(); - const structValue = structHelpers.PointerFields.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); - if (cleanup) { cleanup(); } + const structValue = structHelpers.PointerFields.lift(); return structValue; }, PointerFields: { init: function(raw, mutRaw, opaque, ptr, mutPtr) { instance.exports.bjs_PointerFields_init(raw, mutRaw, opaque, ptr, mutPtr); - const structValue = structHelpers.PointerFields.lift(tmpRetStrings, tmpRetInts, tmpRetF32s, tmpRetF64s, tmpRetPointers); + const structValue = structHelpers.PointerFields.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.d.ts deleted file mode 100644 index be85a00fd..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export type Exports = { - check(): void; -} -export type Imports = { -} -export function createInstantiator(options: { - imports: Imports; -}, swift: any): Promise<{ - addImports: (importObject: WebAssembly.Imports) => void; - setInstance: (instance: WebAssembly.Instance) => void; - createExports: (instance: WebAssembly.Instance) => Exports; -}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.js deleted file mode 100644 index 8a2fabca9..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Export.js +++ /dev/null @@ -1,225 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -export async function createInstantiator(options, swift) { - let instance; - let memory; - let setException; - 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 tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; - const enumHelpers = {}; - const structHelpers = {}; - - let _exports = null; - let bjs = null; - - return { - /** - * @param {WebAssembly.Imports} importObject - */ - addImports: (importObject, importsContext) => { - bjs = {}; - importObject["bjs"] = bjs; - bjs["swift_js_return_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { - const source = swift.memory.getObject(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); - bytes.set(source); - } - bjs["swift_js_make_js_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - return swift.memory.retain(textDecoder.decode(bytes)); - } - bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); - target.set(tmpRetBytes); - tmpRetBytes = undefined; - } - bjs["swift_js_throw"] = function(id) { - tmpRetException = swift.memory.retainByRef(id); - } - bjs["swift_js_retain"] = function(id) { - return swift.memory.retainByRef(id); - } - bjs["swift_js_release"] = function(id) { - swift.memory.release(id); - } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } - bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); - } - bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); - } - bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); - } - bjs["swift_js_push_string"] = function(ptr, len) { - const bytes = new Uint8Array(memory.buffer, ptr, len); - const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); - } - bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); - } - bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); - } - bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); - } - bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); - } - bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } - } - bjs["swift_js_return_optional_bool"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalBool = null; - } else { - tmpRetOptionalBool = value !== 0; - } - } - bjs["swift_js_return_optional_int"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalInt = null; - } else { - tmpRetOptionalInt = value | 0; - } - } - bjs["swift_js_return_optional_float"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalFloat = null; - } else { - tmpRetOptionalFloat = Math.fround(value); - } - } - bjs["swift_js_return_optional_double"] = function(isSome, value) { - if (isSome === 0) { - tmpRetOptionalDouble = null; - } else { - tmpRetOptionalDouble = value; - } - } - bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { - if (isSome === 0) { - tmpRetString = null; - } else { - const bytes = new Uint8Array(memory.buffer, ptr, len); - tmpRetString = textDecoder.decode(bytes); - } - } - 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; - } - }, - setInstance: (i) => { - instance = i; - memory = instance.exports.memory; - - setException = (error) => { - instance.exports._swift_js_exception.value = swift.memory.retain(error) - } - }, - /** @param {WebAssembly.Instance} instance */ - createExports: (instance) => { - const js = swift.memory.heap; - const exports = { - check: function bjs_check() { - instance.exports.bjs_check(); - }, - }; - _exports = exports; - return exports; - }, - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts similarity index 96% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.d.ts rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts index 8cd1e806e..7acba67a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts @@ -5,6 +5,7 @@ // `swift package bridge-js`. export type Exports = { + check(): void; } export type Imports = { check(): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js similarity index 85% rename from Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.js rename to Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 2944bcf5a..f8737237e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.Import.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -18,20 +18,14 @@ export async function createInstantiator(options, swift) { let tmpRetOptionalFloat; let tmpRetOptionalDouble; let tmpRetOptionalHeapObject; - let tmpRetTag; - let tmpRetStrings = []; - let tmpRetInts = []; - let tmpRetF32s = []; - let tmpRetF64s = []; - let tmpParamInts = []; - let tmpParamF32s = []; - let tmpParamF64s = []; - let tmpRetPointers = []; - let tmpParamPointers = []; - let tmpStructCleanups = []; + let strStack = []; + let i32Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; const enumHelpers = {}; const structHelpers = {}; - + let _exports = null; let bjs = null; @@ -49,6 +43,7 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); const bytes = new Uint8Array(memory.buffer, bytesPtr); bytes.set(source); } @@ -70,47 +65,34 @@ export async function createInstantiator(options, swift) { bjs["swift_js_release"] = function(id) { swift.memory.release(id); } - bjs["swift_js_push_tag"] = function(tag) { - tmpRetTag = tag; - } bjs["swift_js_push_i32"] = function(v) { - tmpRetInts.push(v | 0); + i32Stack.push(v | 0); } bjs["swift_js_push_f32"] = function(v) { - tmpRetF32s.push(Math.fround(v)); + f32Stack.push(Math.fround(v)); } bjs["swift_js_push_f64"] = function(v) { - tmpRetF64s.push(v); + f64Stack.push(v); } bjs["swift_js_push_string"] = function(ptr, len) { const bytes = new Uint8Array(memory.buffer, ptr, len); const value = textDecoder.decode(bytes); - tmpRetStrings.push(value); + strStack.push(value); } bjs["swift_js_pop_i32"] = function() { - return tmpParamInts.pop(); + return i32Stack.pop(); } bjs["swift_js_pop_f32"] = function() { - return tmpParamF32s.pop(); + return f32Stack.pop(); } bjs["swift_js_pop_f64"] = function() { - return tmpParamF64s.pop(); + return f64Stack.pop(); } bjs["swift_js_push_pointer"] = function(pointer) { - tmpRetPointers.push(pointer); + ptrStack.push(pointer); } bjs["swift_js_pop_pointer"] = function() { - return tmpParamPointers.pop(); - } - bjs["swift_js_struct_cleanup"] = function(cleanupId) { - if (cleanupId === 0) { return; } - const index = (cleanupId | 0) - 1; - const cleanup = tmpStructCleanups[index]; - tmpStructCleanups[index] = null; - if (cleanup) { cleanup(); } - while (tmpStructCleanups.length > 0 && tmpStructCleanups[tmpStructCleanups.length - 1] == null) { - tmpStructCleanups.pop(); - } + return ptrStack.pop(); } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { @@ -202,6 +184,7 @@ export async function createInstantiator(options, swift) { tmpRetOptionalHeapObject = undefined; return pointer || 0; } + bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_check"] = function bjs_check() { try { @@ -223,6 +206,9 @@ export async function createInstantiator(options, swift) { createExports: (instance) => { const js = swift.memory.heap; const exports = { + check: function bjs_check() { + instance.exports.bjs_check(); + }, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json new file mode 100644 index 000000000..277b2c578 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": false, + "target": "ES2020", + "module": "ES2020", + "moduleResolution": "node", + "lib": ["ES2020", "DOM"] + }, + "include": ["*.d.ts"] +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.json deleted file mode 100644 index c796433dd..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.json +++ /dev/null @@ -1,983 +0,0 @@ -{ - "classes" : [ - { - "methods" : [ - - ], - "name" : "Item", - "properties" : [ - - ], - "swiftCallName" : "Item" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "const", - "name" : "Direction", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "pending", - "rawValue" : "0" - }, - { - "associatedValues" : [ - - ], - "name" : "active", - "rawValue" : "1" - }, - { - "associatedValues" : [ - - ], - "name" : "completed", - "rawValue" : "2" - } - ], - "emitStyle" : "const", - "name" : "Status", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Status", - "tsFullPath" : "Status" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_processIntArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processIntArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "abiName" : "bjs_processStringArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processStringArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_processDoubleArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processDoubleArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "double" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "double" : { - - } - } - } - } - }, - { - "abiName" : "bjs_processBoolArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processBoolArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "bool" : { - - } - } - } - } - }, - { - "abiName" : "bjs_processPointArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processPointArray", - "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - }, - { - "abiName" : "bjs_processDirectionArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processDirectionArray", - "parameters" : [ - { - "label" : "_", - "name" : "directions", - "type" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - }, - { - "abiName" : "bjs_processStatusArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processStatusArray", - "parameters" : [ - { - "label" : "_", - "name" : "statuses", - "type" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Status", - "_1" : "Int" - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Status", - "_1" : "Int" - } - } - } - } - }, - { - "abiName" : "bjs_sumIntArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "sumIntArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_findFirstPoint", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "findFirstPoint", - "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - }, - { - "label" : "matching", - "name" : "matching", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "Point" - } - } - }, - { - "abiName" : "bjs_processUnsafeRawPointerArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processUnsafeRawPointerArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - } - } - }, - { - "abiName" : "bjs_processUnsafeMutableRawPointerArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processUnsafeMutableRawPointerArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - } - } - }, - { - "abiName" : "bjs_processOpaquePointerArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOpaquePointerArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalIntArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalIntArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalStringArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalStringArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "optional" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalPointArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalPointArray", - "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalDirectionArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalDirectionArray", - "parameters" : [ - { - "label" : "_", - "name" : "directions", - "type" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processOptionalStatusArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalStatusArray", - "parameters" : [ - { - "label" : "_", - "name" : "statuses", - "type" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Status", - "_1" : "Int" - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Status", - "_1" : "Int" - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processNestedIntArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processNestedIntArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processNestedStringArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processNestedStringArray", - "parameters" : [ - { - "label" : "_", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processNestedPointArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processNestedPointArray", - "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - } - } - } - } - } - }, - { - "abiName" : "bjs_processItemArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processItemArray", - "parameters" : [ - { - "label" : "_", - "name" : "items", - "type" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Item" - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Item" - } - } - } - } - }, - { - "abiName" : "bjs_processNestedItemArray", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processNestedItemArray", - "parameters" : [ - { - "label" : "_", - "name" : "items", - "type" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Item" - } - } - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Item" - } - } - } - } - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - { - "methods" : [ - - ], - "name" : "Point", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "y", - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "Point" - } - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.swift deleted file mode 100644 index 711694c9d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ArrayTypes.swift +++ /dev/null @@ -1,694 +0,0 @@ -extension Direction: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { - return Direction(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } - - private init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .north - case 1: - self = .south - case 2: - self = .east - case 3: - self = .west - default: - return nil - } - } - - private var bridgeJSRawValue: Int32 { - switch self { - case .north: - return 0 - case .south: - return 1 - case .east: - return 2 - case .west: - return 3 - } - } -} - -extension Status: _BridgedSwiftEnumNoPayload { -} - -extension Point: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Point { - let y = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let x = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - return Point(x: x, y: y) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.x) - _swift_js_push_f64(self.y) - } - - init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 -#else -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") -fileprivate func _bjs_struct_lift_Point() -> Int32 -#else -fileprivate func _bjs_struct_lift_Point() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -@_expose(wasm, "bjs_processIntArray") -@_cdecl("bjs_processIntArray") -public func _bjs_processIntArray() -> Void { - #if arch(wasm32) - let ret = processIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processStringArray") -@_cdecl("bjs_processStringArray") -public func _bjs_processStringArray() -> Void { - #if arch(wasm32) - let ret = processStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processDoubleArray") -@_cdecl("bjs_processDoubleArray") -public func _bjs_processDoubleArray() -> Void { - #if arch(wasm32) - let ret = processDoubleArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_f64(__bjs_elem_ret)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processBoolArray") -@_cdecl("bjs_processBoolArray") -public func _bjs_processBoolArray() -> Void { - #if arch(wasm32) - let ret = processBoolArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Bool] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(__bjs_elem_ret ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processPointArray") -@_cdecl("bjs_processPointArray") -public func _bjs_processPointArray() -> Void { - #if arch(wasm32) - let ret = processPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processDirectionArray") -@_cdecl("bjs_processDirectionArray") -public func _bjs_processDirectionArray() -> Void { - #if arch(wasm32) - let ret = processDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Direction] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Direction.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processStatusArray") -@_cdecl("bjs_processStatusArray") -public func _bjs_processStatusArray() -> Void { - #if arch(wasm32) - let ret = processStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Status] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Status.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_sumIntArray") -@_cdecl("bjs_sumIntArray") -public func _bjs_sumIntArray() -> Int32 { - #if arch(wasm32) - let ret = sumIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_findFirstPoint") -@_cdecl("bjs_findFirstPoint") -public func _bjs_findFirstPoint(_ matchingBytes: Int32, _ matchingLength: Int32) -> Void { - #if arch(wasm32) - let ret = findFirstPoint(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }(), matching: String.bridgeJSLiftParameter(matchingBytes, matchingLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processUnsafeRawPointerArray") -@_cdecl("bjs_processUnsafeRawPointerArray") -public func _bjs_processUnsafeRawPointerArray() -> Void { - #if arch(wasm32) - let ret = processUnsafeRawPointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [UnsafeRawPointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(UnsafeRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processUnsafeMutableRawPointerArray") -@_cdecl("bjs_processUnsafeMutableRawPointerArray") -public func _bjs_processUnsafeMutableRawPointerArray() -> Void { - #if arch(wasm32) - let ret = processUnsafeMutableRawPointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [UnsafeMutableRawPointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(UnsafeMutableRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOpaquePointerArray") -@_cdecl("bjs_processOpaquePointerArray") -public func _bjs_processOpaquePointerArray() -> Void { - #if arch(wasm32) - let ret = processOpaquePointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [OpaquePointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(OpaquePointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalIntArray") -@_cdecl("bjs_processOptionalIntArray") -public func _bjs_processOptionalIntArray() -> Void { - #if arch(wasm32) - let ret = processOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_unwrapped_ret_elem))} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalStringArray") -@_cdecl("bjs_processOptionalStringArray") -public func _bjs_processOptionalStringArray() -> Void { - #if arch(wasm32) - let ret = processOptionalStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - var __bjs_str_ret_elem = __bjs_unwrapped_ret_elem - __bjs_str_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalArray") -@_cdecl("bjs_processOptionalArray") -public func _bjs_processOptionalArray(_ values: Int32) -> Void { - #if arch(wasm32) - let ret = processOptionalArray(_: { - if values == 0 { - return Optional<[Int]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }() - } - }()) - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalPointArray") -@_cdecl("bjs_processOptionalPointArray") -public func _bjs_processOptionalPointArray() -> Void { - #if arch(wasm32) - let ret = processOptionalPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalDirectionArray") -@_cdecl("bjs_processOptionalDirectionArray") -public func _bjs_processOptionalDirectionArray() -> Void { - #if arch(wasm32) - let ret = processOptionalDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(__bjs_unwrapped_ret_elem.bridgeJSLowerParameter())} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processOptionalStatusArray") -@_cdecl("bjs_processOptionalStatusArray") -public func _bjs_processOptionalStatusArray() -> Void { - #if arch(wasm32) - let ret = processOptionalStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(__bjs_unwrapped_ret_elem.bridgeJSLowerParameter())} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processNestedIntArray") -@_cdecl("bjs_processNestedIntArray") -public func _bjs_processNestedIntArray() -> Void { - #if arch(wasm32) - let ret = processNestedIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Int]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret_elem))} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processNestedStringArray") -@_cdecl("bjs_processNestedStringArray") -public func _bjs_processNestedStringArray() -> Void { - #if arch(wasm32) - let ret = processNestedStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[String]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - var __bjs_ret_elem_elem = __bjs_elem_ret_elem - __bjs_ret_elem_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processNestedPointArray") -@_cdecl("bjs_processNestedPointArray") -public func _bjs_processNestedPointArray() -> Void { - #if arch(wasm32) - let ret = processNestedPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Point]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Point] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Point.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - __bjs_elem_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processItemArray") -@_cdecl("bjs_processItemArray") -public func _bjs_processItemArray() -> Void { - #if arch(wasm32) - let ret = processItemArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Item] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Item.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processNestedItemArray") -@_cdecl("bjs_processNestedItemArray") -public func _bjs_processNestedItemArray() -> Void { - #if arch(wasm32) - let ret = processNestedItemArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Item]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Item] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Item.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_pointer(__bjs_elem_ret_elem.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Item_deinit") -@_cdecl("bjs_Item_deinit") -public func _bjs_Item_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension Item: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Item_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Item_wrap") -fileprivate func _bjs_Item_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Item_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.json deleted file mode 100644 index 77c5b3678..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Async.json +++ /dev/null @@ -1,184 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_asyncReturnVoid", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncReturnVoid", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripInt", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripInt", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripString", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripString", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripBool", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripBool", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripFloat", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripFloat", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "float" : { - - } - } - } - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripDouble", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripDouble", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_asyncRoundTripJSObject", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripJSObject", - "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "jsObject" : { - - } - } - } - ], - "returnType" : { - "jsObject" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.json deleted file mode 100644 index 97def2060..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.ReverseOrder.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_FunctionA_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_FunctionA_processB", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processB", - "parameters" : [ - { - "label" : "b", - "name" : "b", - "type" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_FunctionA_createB", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createB", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "name" : "FunctionA", - "properties" : [ - - ], - "swiftCallName" : "FunctionA" - }, - { - "constructor" : { - "abiName" : "bjs_FunctionB_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "FunctionB", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "FunctionB" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_standaloneFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "standaloneFunction", - "parameters" : [ - { - "label" : "b", - "name" : "b", - "type" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.json deleted file mode 100644 index acfa4c9ef..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileFunctionTypes.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_FunctionB_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "FunctionB", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "FunctionB" - }, - { - "constructor" : { - "abiName" : "bjs_FunctionA_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_FunctionA_processB", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processB", - "parameters" : [ - { - "label" : "b", - "name" : "b", - "type" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_FunctionA_createB", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createB", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "name" : "FunctionA", - "properties" : [ - - ], - "swiftCallName" : "FunctionA" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_standaloneFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "standaloneFunction", - "parameters" : [ - { - "label" : "b", - "name" : "b", - "type" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "FunctionB" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.json deleted file mode 100644 index de5fb19b0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.ReverseOrder.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "classes" : [ - { - "methods" : [ - - ], - "name" : "ClassA", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "linkedB", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "ClassB" - } - } - } - } - } - ], - "swiftCallName" : "ClassA" - }, - { - "constructor" : { - "abiName" : "bjs_ClassB_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "ClassB", - "properties" : [ - - ], - "swiftCallName" : "ClassB" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.json deleted file mode 100644 index 53a5f858c..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/CrossFileTypeResolution.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_ClassB_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "ClassB", - "properties" : [ - - ], - "swiftCallName" : "ClassB" - }, - { - "methods" : [ - - ], - "name" : "ClassA", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "linkedB", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "ClassB" - } - } - } - } - } - ], - "swiftCallName" : "ClassA" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.json deleted file mode 100644 index f2e6a4e2e..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/DefaultParameters.json +++ /dev/null @@ -1,1270 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_DefaultGreeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "DefaultGreeter", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "DefaultGreeter" - }, - { - "constructor" : { - "abiName" : "bjs_EmptyGreeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "EmptyGreeter", - "properties" : [ - - ], - "swiftCallName" : "EmptyGreeter" - }, - { - "constructor" : { - "abiName" : "bjs_ConstructorDefaults_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Default" - } - }, - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "int" : { - "_0" : 42 - } - }, - "label" : "count", - "name" : "count", - "type" : { - "int" : { - - } - } - }, - { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "enabled", - "name" : "enabled", - "type" : { - "bool" : { - - } - } - }, - { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "active" - } - }, - "label" : "status", - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "defaultValue" : { - "null" : { - - } - }, - "label" : "tag", - "name" : "tag", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "ConstructorDefaults", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "count", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "enabled", - "type" : { - "bool" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "tag", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "swiftCallName" : "ConstructorDefaults" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "active" - }, - { - "associatedValues" : [ - - ], - "name" : "inactive" - }, - { - "associatedValues" : [ - - ], - "name" : "pending" - } - ], - "emitStyle" : "const", - "explicitAccessControl" : "public", - "name" : "Status", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Status", - "tsFullPath" : "Status" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_testStringDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testStringDefault", - "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Hello World" - } - }, - "label" : "message", - "name" : "message", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_testNegativeIntDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testNegativeIntDefault", - "parameters" : [ - { - "defaultValue" : { - "int" : { - "_0" : -42 - } - }, - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_testBoolDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testBoolDefault", - "parameters" : [ - { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "flag", - "name" : "flag", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_testNegativeFloatDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testNegativeFloatDefault", - "parameters" : [ - { - "defaultValue" : { - "float" : { - "_0" : -273.15 - } - }, - "label" : "temp", - "name" : "temp", - "type" : { - "float" : { - - } - } - } - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_testDoubleDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testDoubleDefault", - "parameters" : [ - { - "defaultValue" : { - "double" : { - "_0" : 2.718 - } - }, - "label" : "precision", - "name" : "precision", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_testOptionalDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testOptionalDefault", - "parameters" : [ - { - "defaultValue" : { - "null" : { - - } - }, - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testOptionalStringDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testOptionalStringDefault", - "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Hi" - } - }, - "label" : "greeting", - "name" : "greeting", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testMultipleDefaults", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testMultipleDefaults", - "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "Default Title" - } - }, - "label" : "title", - "name" : "title", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "int" : { - "_0" : 10 - } - }, - "label" : "count", - "name" : "count", - "type" : { - "int" : { - - } - } - }, - { - "defaultValue" : { - "bool" : { - "_0" : false - } - }, - "label" : "enabled", - "name" : "enabled", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_testEnumDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testEnumDefault", - "parameters" : [ - { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "active" - } - }, - "label" : "status", - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - } - ], - "returnType" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "abiName" : "bjs_testComplexInit", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testComplexInit", - "parameters" : [ - { - "defaultValue" : { - "objectWithArguments" : { - "_0" : "DefaultGreeter", - "_1" : [ - { - "string" : { - "_0" : "DefaultUser" - } - } - ] - } - }, - "label" : "greeter", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "DefaultGreeter" - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "DefaultGreeter" - } - } - }, - { - "abiName" : "bjs_testEmptyInit", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testEmptyInit", - "parameters" : [ - { - "defaultValue" : { - "object" : { - "_0" : "EmptyGreeter" - } - }, - "label" : "greeter", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "EmptyGreeter" - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "EmptyGreeter" - } - } - }, - { - "abiName" : "bjs_testOptionalStructDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testOptionalStructDefault", - "parameters" : [ - { - "defaultValue" : { - "null" : { - - } - }, - "label" : "point", - "name" : "point", - "type" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Config" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Config" - } - } - } - } - }, - { - "abiName" : "bjs_testOptionalStructWithValueDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testOptionalStructWithValueDefault", - "parameters" : [ - { - "defaultValue" : { - "structLiteral" : { - "_0" : "Config", - "_1" : [ - { - "name" : "name", - "value" : { - "string" : { - "_0" : "default" - } - } - }, - { - "name" : "value", - "value" : { - "int" : { - "_0" : 42 - } - } - }, - { - "name" : "enabled", - "value" : { - "bool" : { - "_0" : true - } - } - } - ] - } - }, - "label" : "point", - "name" : "point", - "type" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Config" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Config" - } - } - } - } - }, - { - "abiName" : "bjs_testIntArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testIntArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 1 - } - }, - { - "int" : { - "_0" : 2 - } - }, - { - "int" : { - "_0" : 3 - } - } - ] - } - }, - "label" : "values", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testStringArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testStringArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "string" : { - "_0" : "a" - } - }, - { - "string" : { - "_0" : "b" - } - }, - { - "string" : { - "_0" : "c" - } - } - ] - } - }, - "label" : "names", - "name" : "names", - "type" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testDoubleArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testDoubleArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "double" : { - "_0" : 1.5 - } - }, - { - "double" : { - "_0" : 2.5 - } - }, - { - "double" : { - "_0" : 3.5 - } - } - ] - } - }, - "label" : "values", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "double" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "double" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testBoolArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testBoolArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "bool" : { - "_0" : true - } - }, - { - "bool" : { - "_0" : false - } - }, - { - "bool" : { - "_0" : true - } - } - ] - } - }, - "label" : "flags", - "name" : "flags", - "type" : { - "array" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "bool" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testEmptyArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testEmptyArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - - ] - } - }, - "label" : "items", - "name" : "items", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testMixedWithArrayDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testMixedWithArrayDefault", - "parameters" : [ - { - "defaultValue" : { - "string" : { - "_0" : "test" - } - }, - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 10 - } - }, - { - "int" : { - "_0" : 20 - } - }, - { - "int" : { - "_0" : 30 - } - } - ] - } - }, - "label" : "values", - "name" : "values", - "type" : { - "array" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "enabled", - "name" : "enabled", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - { - "methods" : [ - - ], - "name" : "Config", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "value", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "enabled", - "type" : { - "bool" : { - - } - } - } - ], - "swiftCallName" : "Config" - }, - { - "constructor" : { - "abiName" : "bjs_MathOperations_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "defaultValue" : { - "double" : { - "_0" : 0 - } - }, - "label" : "baseValue", - "name" : "baseValue", - "type" : { - "double" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_MathOperations_add", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "add", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "double" : { - - } - } - }, - { - "defaultValue" : { - "double" : { - "_0" : 10 - } - }, - "label" : "b", - "name" : "b", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_MathOperations_multiply", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "multiply", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "double" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_MathOperations_static_subtract", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "subtract", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "double" : { - - } - } - }, - { - "defaultValue" : { - "double" : { - "_0" : 5 - } - }, - "label" : "b", - "name" : "b", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - }, - "staticContext" : { - "structName" : { - "_0" : "MathOperations" - } - } - } - ], - "name" : "MathOperations", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "baseValue", - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "MathOperations" - } - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.json deleted file mode 100644 index ab7fbfd9d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.json +++ /dev/null @@ -1,844 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - } - ], - "name" : "flag" - }, - { - "associatedValues" : [ - { - "type" : { - "float" : { - - } - } - } - ], - "name" : "rate" - }, - { - "associatedValues" : [ - { - "type" : { - "double" : { - - } - } - } - ], - "name" : "precise" - }, - { - "associatedValues" : [ - - ], - "name" : "info" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "error" - }, - { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "status" - }, - { - "associatedValues" : [ - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "double" : { - - } - } - } - ], - "name" : "coordinates" - }, - { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - }, - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "double" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "comprehensive" - }, - { - "associatedValues" : [ - - ], - "name" : "info" - } - ], - "emitStyle" : "const", - "name" : "ComplexResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "ComplexResult", - "tsFullPath" : "ComplexResult" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utilities", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utilities", - "tsFullPath" : "Utilities" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - }, - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "status" - } - ], - "emitStyle" : "const", - "name" : "Result", - "namespace" : [ - "Utilities" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utilities.Result", - "tsFullPath" : "Utilities.Result" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - }, - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - } - ], - "emitStyle" : "const", - "name" : "NetworkingResult", - "namespace" : [ - "API" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "NetworkingResult", - "tsFullPath" : "API.NetworkingResult" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - { - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - }, - { - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "name" : "status" - } - ], - "emitStyle" : "const", - "name" : "APIOptionalResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIOptionalResult", - "tsFullPath" : "APIOptionalResult" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_handle", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "handle", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getResult", - "parameters" : [ - - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - }, - { - "abiName" : "bjs_roundtripAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtripAPIResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalAPIResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - } - }, - { - "abiName" : "bjs_handleComplex", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "handleComplex", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getComplexResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getComplexResult", - "parameters" : [ - - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - }, - { - "abiName" : "bjs_roundtripComplexResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtripComplexResult", - "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalComplexResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalComplexResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalUtilitiesResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalUtilitiesResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "Utilities.Result" - } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalNetworkingResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalNetworkingResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "NetworkingResult" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "NetworkingResult" - } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalAPIOptionalResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalAPIOptionalResult", - "parameters" : [ - { - "label" : "result", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } - } - } - }, - { - "abiName" : "bjs_compareAPIResults", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "compareAPIResults", - "parameters" : [ - { - "label" : "result1", - "name" : "result1", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } - } - } - }, - { - "label" : "result2", - "name" : "result2", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.swift deleted file mode 100644 index e35da2f77..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumAssociatedValue.swift +++ /dev/null @@ -1,614 +0,0 @@ -extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { - switch caseId { - case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 2: - return .flag(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 3: - return .rate(Float.bridgeJSLiftParameter(_swift_js_pop_f32())) - case 4: - return .precise(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - case 5: - return .info - default: - fatalError("Unknown APIResult case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(0) - case .failure(let param0): - _swift_js_push_i32(Int32(param0)) - return Int32(1) - case .flag(let param0): - _swift_js_push_i32(param0 ? 1 : 0) - return Int32(2) - case .rate(let param0): - _swift_js_push_f32(param0) - return Int32(3) - case .precise(let param0): - _swift_js_push_f64(param0) - return Int32(4) - case .info: - return Int32(5) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - case .flag(let param0): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - case .rate(let param0): - _swift_js_push_tag(Int32(3)) - _swift_js_push_f32(param0) - case .precise(let param0): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - case .info: - _swift_js_push_tag(Int32(5)) - } - } -} - -extension ComplexResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> ComplexResult { - switch caseId { - case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .error(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 2: - return .status(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 3: - return .coordinates(Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - case 4: - return .comprehensive(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 5: - return .info - default: - fatalError("Unknown ComplexResult case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(0) - case .error(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - return Int32(1) - case .status(let param0, let param1, let param2): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(2) - case .coordinates(let param0, let param1, let param2): - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) - return Int32(3) - case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(4) - case .info: - return Int32(5) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .error(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .coordinates(let param0, let param1, let param2): - _swift_js_push_tag(Int32(3)) - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) - case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_tag(Int32(4)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .info: - _swift_js_push_tag(Int32(5)) - } - } -} - -extension Utilities.Result: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> Utilities.Result { - switch caseId { - case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .failure(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 2: - return .status(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - default: - fatalError("Unknown Utilities.Result case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(0) - case .failure(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - return Int32(1) - case .status(let param0, let param1, let param2): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(2) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> Utilities.Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> Utilities.Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - } -} - -extension NetworkingResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> NetworkingResult { - switch caseId { - case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .failure(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - default: - fatalError("Unknown NetworkingResult case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(0) - case .failure(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - return Int32(1) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> NetworkingResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> NetworkingResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - } - } -} - -extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIOptionalResult { - switch caseId { - case 0: - return .success(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .failure(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 2: - return .status(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) - default: - fatalError("Unknown APIOptionalResult case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - var __bjs_str_param0 = __bjs_unwrapped_param0 - __bjs_str_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - return Int32(0) - case .failure(let param0, let param1): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param0)) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(__bjs_unwrapped_param1 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - return Int32(1) - case .status(let param0, let param1, let param2): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(__bjs_unwrapped_param0 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param1)) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - var __bjs_str_param2 = __bjs_unwrapped_param2 - __bjs_str_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) - return Int32(2) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIOptionalResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIOptionalResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - var __bjs_str_param0 = __bjs_unwrapped_param0 - __bjs_str_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param0)) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(__bjs_unwrapped_param1 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(__bjs_unwrapped_param0 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param1)) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - var __bjs_str_param2 = __bjs_unwrapped_param2 - __bjs_str_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) - } - } -} - -@_expose(wasm, "bjs_handle") -@_cdecl("bjs_handle") -public func _bjs_handle(_ result: Int32) -> Void { - #if arch(wasm32) - handle(result: APIResult.bridgeJSLiftParameter(result)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_getResult") -@_cdecl("bjs_getResult") -public func _bjs_getResult() -> Void { - #if arch(wasm32) - let ret = getResult() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundtripAPIResult") -@_cdecl("bjs_roundtripAPIResult") -public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { - #if arch(wasm32) - let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAPIResult") -@_cdecl("bjs_roundTripOptionalAPIResult") -public func _bjs_roundTripOptionalAPIResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAPIResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_handleComplex") -@_cdecl("bjs_handleComplex") -public func _bjs_handleComplex(_ result: Int32) -> Void { - #if arch(wasm32) - handleComplex(result: ComplexResult.bridgeJSLiftParameter(result)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_getComplexResult") -@_cdecl("bjs_getComplexResult") -public func _bjs_getComplexResult() -> Void { - #if arch(wasm32) - let ret = getComplexResult() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundtripComplexResult") -@_cdecl("bjs_roundtripComplexResult") -public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { - #if arch(wasm32) - let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalComplexResult") -@_cdecl("bjs_roundTripOptionalComplexResult") -public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalComplexResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalUtilitiesResult") -@_cdecl("bjs_roundTripOptionalUtilitiesResult") -public func _bjs_roundTripOptionalUtilitiesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalUtilitiesResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalNetworkingResult") -@_cdecl("bjs_roundTripOptionalNetworkingResult") -public func _bjs_roundTripOptionalNetworkingResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalNetworkingResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAPIOptionalResult") -@_cdecl("bjs_roundTripOptionalAPIOptionalResult") -public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_compareAPIResults") -@_cdecl("bjs_compareAPIResults") -public func _bjs_compareAPIResults(_ result1IsSome: Int32, _ result1CaseId: Int32, _ result2IsSome: Int32, _ result2CaseId: Int32) -> Void { - #if arch(wasm32) - let _tmp_result2 = Optional.bridgeJSLiftParameter(result2IsSome, result2CaseId) - let _tmp_result1 = Optional.bridgeJSLiftParameter(result1IsSome, result1CaseId) - let ret = compareAPIResults(result1: _tmp_result1, result2: _tmp_result2) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumCase.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumCase.json deleted file mode 100644 index ca6fabceb..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumCase.json +++ /dev/null @@ -1,320 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "const", - "name" : "Direction", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "loading" - }, - { - "associatedValues" : [ - - ], - "name" : "success" - }, - { - "associatedValues" : [ - - ], - "name" : "error" - } - ], - "emitStyle" : "const", - "name" : "Status", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Status", - "tsFullPath" : "Status" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSDirection", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSDirection", - "tsFullPath" : "TSDirection" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "success" - } - ], - "emitStyle" : "const", - "explicitAccessControl" : "public", - "name" : "PublicStatus", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "PublicStatus", - "tsFullPath" : "PublicStatus" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_setDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setDirection", - "parameters" : [ - { - "label" : "_", - "name" : "direction", - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getDirection", - "parameters" : [ - - ], - "returnType" : { - "caseEnum" : { - "_0" : "Direction" - } - } - }, - { - "abiName" : "bjs_processDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processDirection", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - ], - "returnType" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalDirection", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - }, - { - "abiName" : "bjs_setTSDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setTSDirection", - "parameters" : [ - { - "label" : "_", - "name" : "direction", - "type" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getTSDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTSDirection", - "parameters" : [ - - ], - "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalTSDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalTSDirection", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.json deleted file mode 100644 index 42a084c44..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.Global.json +++ /dev/null @@ -1,415 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Converter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_Converter_toString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "toString", - "namespace" : [ - "Utils" - ], - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Converter", - "namespace" : [ - "Utils" - ], - "properties" : [ - - ], - "swiftCallName" : "Utils.Converter" - }, - { - "constructor" : { - "abiName" : "bjs_HTTPServer_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_HTTPServer_call", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "call", - "namespace" : [ - "Networking", - "API" - ], - "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "HTTPServer", - "namespace" : [ - "Networking", - "API" - ], - "properties" : [ - - ], - "swiftCallName" : "Networking.API.HTTPServer" - }, - { - "constructor" : { - "abiName" : "bjs_TestServer_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_TestServer_call", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "call", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "TestServer", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "properties" : [ - - ], - "swiftCallName" : "Internal.TestServer" - } - ], - "enums" : [ - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Networking", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking", - "tsFullPath" : "Networking" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "API", - "namespace" : [ - "Networking" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API", - "tsFullPath" : "Networking.API" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "get" - }, - { - "associatedValues" : [ - - ], - "name" : "post" - }, - { - "associatedValues" : [ - - ], - "name" : "put" - }, - { - "associatedValues" : [ - - ], - "name" : "delete" - } - ], - "emitStyle" : "const", - "name" : "Method", - "namespace" : [ - "Networking", - "API" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API.Method", - "tsFullPath" : "Networking.API.Method" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Configuration", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration", - "tsFullPath" : "Configuration" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "debug", - "rawValue" : "debug" - }, - { - "associatedValues" : [ - - ], - "name" : "info", - "rawValue" : "info" - }, - { - "associatedValues" : [ - - ], - "name" : "warning", - "rawValue" : "warning" - }, - { - "associatedValues" : [ - - ], - "name" : "error", - "rawValue" : "error" - } - ], - "emitStyle" : "const", - "name" : "LogLevel", - "namespace" : [ - "Configuration" - ], - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.LogLevel", - "tsFullPath" : "Configuration.LogLevel" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "http", - "rawValue" : "80" - }, - { - "associatedValues" : [ - - ], - "name" : "https", - "rawValue" : "443" - }, - { - "associatedValues" : [ - - ], - "name" : "development", - "rawValue" : "3000" - } - ], - "emitStyle" : "const", - "name" : "Port", - "namespace" : [ - "Configuration" - ], - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.Port", - "tsFullPath" : "Configuration.Port" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Internal", - "namespace" : [ - "Networking", - "APIV2" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal", - "tsFullPath" : "Networking.APIV2.Internal" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "get" - }, - { - "associatedValues" : [ - - ], - "name" : "post" - } - ], - "emitStyle" : "const", - "name" : "SupportedMethod", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal.SupportedMethod", - "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" - } - ], - "exposeToGlobal" : true, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.json deleted file mode 100644 index 23bb06429..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumNamespace.json +++ /dev/null @@ -1,415 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Converter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_Converter_toString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "toString", - "namespace" : [ - "Utils" - ], - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Converter", - "namespace" : [ - "Utils" - ], - "properties" : [ - - ], - "swiftCallName" : "Utils.Converter" - }, - { - "constructor" : { - "abiName" : "bjs_HTTPServer_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_HTTPServer_call", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "call", - "namespace" : [ - "Networking", - "API" - ], - "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "HTTPServer", - "namespace" : [ - "Networking", - "API" - ], - "properties" : [ - - ], - "swiftCallName" : "Networking.API.HTTPServer" - }, - { - "constructor" : { - "abiName" : "bjs_TestServer_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_TestServer_call", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "call", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "parameters" : [ - { - "label" : "_", - "name" : "method", - "type" : { - "caseEnum" : { - "_0" : "Internal.SupportedMethod" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "TestServer", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "properties" : [ - - ], - "swiftCallName" : "Internal.TestServer" - } - ], - "enums" : [ - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Networking", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking", - "tsFullPath" : "Networking" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "API", - "namespace" : [ - "Networking" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API", - "tsFullPath" : "Networking.API" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "get" - }, - { - "associatedValues" : [ - - ], - "name" : "post" - }, - { - "associatedValues" : [ - - ], - "name" : "put" - }, - { - "associatedValues" : [ - - ], - "name" : "delete" - } - ], - "emitStyle" : "const", - "name" : "Method", - "namespace" : [ - "Networking", - "API" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Networking.API.Method", - "tsFullPath" : "Networking.API.Method" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Configuration", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration", - "tsFullPath" : "Configuration" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "debug", - "rawValue" : "debug" - }, - { - "associatedValues" : [ - - ], - "name" : "info", - "rawValue" : "info" - }, - { - "associatedValues" : [ - - ], - "name" : "warning", - "rawValue" : "warning" - }, - { - "associatedValues" : [ - - ], - "name" : "error", - "rawValue" : "error" - } - ], - "emitStyle" : "const", - "name" : "LogLevel", - "namespace" : [ - "Configuration" - ], - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.LogLevel", - "tsFullPath" : "Configuration.LogLevel" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "http", - "rawValue" : "80" - }, - { - "associatedValues" : [ - - ], - "name" : "https", - "rawValue" : "443" - }, - { - "associatedValues" : [ - - ], - "name" : "development", - "rawValue" : "3000" - } - ], - "emitStyle" : "const", - "name" : "Port", - "namespace" : [ - "Configuration" - ], - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Configuration.Port", - "tsFullPath" : "Configuration.Port" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Internal", - "namespace" : [ - "Networking", - "APIV2" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal", - "tsFullPath" : "Networking.APIV2.Internal" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "get" - }, - { - "associatedValues" : [ - - ], - "name" : "post" - } - ], - "emitStyle" : "const", - "name" : "SupportedMethod", - "namespace" : [ - "Networking", - "APIV2", - "Internal" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Internal.SupportedMethod", - "tsFullPath" : "Networking.APIV2.Internal.SupportedMethod" - } - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.json deleted file mode 100644 index 078772ff2..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/EnumRawType.json +++ /dev/null @@ -1,1498 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ - - ], - "name" : "dark", - "rawValue" : "dark" - }, - { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "const", - "name" : "Theme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Theme", - "tsFullPath" : "Theme" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ - - ], - "name" : "dark", - "rawValue" : "dark" - }, - { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSTheme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSTheme", - "tsFullPath" : "TSTheme" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "enabled", - "rawValue" : "true" - }, - { - "associatedValues" : [ - - ], - "name" : "disabled", - "rawValue" : "false" - } - ], - "emitStyle" : "const", - "name" : "FeatureFlag", - "rawType" : "Bool", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "FeatureFlag", - "tsFullPath" : "FeatureFlag" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "ok", - "rawValue" : "200" - }, - { - "associatedValues" : [ - - ], - "name" : "notFound", - "rawValue" : "404" - }, - { - "associatedValues" : [ - - ], - "name" : "serverError", - "rawValue" : "500" - } - ], - "emitStyle" : "const", - "name" : "HttpStatus", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "HttpStatus", - "tsFullPath" : "HttpStatus" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "ok", - "rawValue" : "200" - }, - { - "associatedValues" : [ - - ], - "name" : "notFound", - "rawValue" : "404" - }, - { - "associatedValues" : [ - - ], - "name" : "serverError", - "rawValue" : "500" - } - ], - "emitStyle" : "tsEnum", - "name" : "TSHttpStatus", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TSHttpStatus", - "tsFullPath" : "TSHttpStatus" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "lowest", - "rawValue" : "-1" - }, - { - "associatedValues" : [ - - ], - "name" : "low", - "rawValue" : "2" - }, - { - "associatedValues" : [ - - ], - "name" : "medium", - "rawValue" : "3" - }, - { - "associatedValues" : [ - - ], - "name" : "high", - "rawValue" : "4" - }, - { - "associatedValues" : [ - - ], - "name" : "highest", - "rawValue" : "5" - } - ], - "emitStyle" : "const", - "name" : "Priority", - "rawType" : "Int32", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Priority", - "tsFullPath" : "Priority" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "tiny", - "rawValue" : "1024" - }, - { - "associatedValues" : [ - - ], - "name" : "small", - "rawValue" : "10240" - }, - { - "associatedValues" : [ - - ], - "name" : "medium", - "rawValue" : "102400" - }, - { - "associatedValues" : [ - - ], - "name" : "large", - "rawValue" : "1048576" - } - ], - "emitStyle" : "const", - "name" : "FileSize", - "rawType" : "Int64", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "FileSize", - "tsFullPath" : "FileSize" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "guest", - "rawValue" : "0" - }, - { - "associatedValues" : [ - - ], - "name" : "user", - "rawValue" : "1000" - }, - { - "associatedValues" : [ - - ], - "name" : "admin", - "rawValue" : "9999" - } - ], - "emitStyle" : "const", - "name" : "UserId", - "rawType" : "UInt", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "UserId", - "tsFullPath" : "UserId" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "invalid", - "rawValue" : "0" - }, - { - "associatedValues" : [ - - ], - "name" : "session", - "rawValue" : "12345" - }, - { - "associatedValues" : [ - - ], - "name" : "refresh", - "rawValue" : "67890" - } - ], - "emitStyle" : "const", - "name" : "TokenId", - "rawType" : "UInt32", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "TokenId", - "tsFullPath" : "TokenId" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "none", - "rawValue" : "0" - }, - { - "associatedValues" : [ - - ], - "name" : "active", - "rawValue" : "9876543210" - }, - { - "associatedValues" : [ - - ], - "name" : "expired", - "rawValue" : "1234567890" - } - ], - "emitStyle" : "const", - "name" : "SessionId", - "rawType" : "UInt64", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "SessionId", - "tsFullPath" : "SessionId" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "rough", - "rawValue" : "0.1" - }, - { - "associatedValues" : [ - - ], - "name" : "normal", - "rawValue" : "0.01" - }, - { - "associatedValues" : [ - - ], - "name" : "fine", - "rawValue" : "0.001" - } - ], - "emitStyle" : "const", - "name" : "Precision", - "rawType" : "Float", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Precision", - "tsFullPath" : "Precision" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "quarter", - "rawValue" : "0.25" - }, - { - "associatedValues" : [ - - ], - "name" : "half", - "rawValue" : "0.5" - }, - { - "associatedValues" : [ - - ], - "name" : "golden", - "rawValue" : "1.618" - }, - { - "associatedValues" : [ - - ], - "name" : "pi", - "rawValue" : "3.14159" - } - ], - "emitStyle" : "const", - "name" : "Ratio", - "rawType" : "Double", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Ratio", - "tsFullPath" : "Ratio" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_setTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setTheme", - "parameters" : [ - { - "label" : "_", - "name" : "theme", - "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTheme", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalTheme", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - } - }, - { - "abiName" : "bjs_setTSTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setTSTheme", - "parameters" : [ - { - "label" : "_", - "name" : "theme", - "type" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getTSTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTSTheme", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalTSTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalTSTheme", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } - } - } - }, - { - "abiName" : "bjs_setFeatureFlag", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setFeatureFlag", - "parameters" : [ - { - "label" : "_", - "name" : "flag", - "type" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "Bool" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getFeatureFlag", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getFeatureFlag", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "Bool" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalFeatureFlag", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalFeatureFlag", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "Bool" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "Bool" - } - } - } - } - }, - { - "abiName" : "bjs_setHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setHttpStatus", - "parameters" : [ - { - "label" : "_", - "name" : "status", - "type" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getHttpStatus", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalHttpStatus", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - } - } - }, - { - "abiName" : "bjs_setTSHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setTSHttpStatus", - "parameters" : [ - { - "label" : "_", - "name" : "status", - "type" : { - "rawValueEnum" : { - "_0" : "TSHttpStatus", - "_1" : "Int" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getTSHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTSHttpStatus", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "TSHttpStatus", - "_1" : "Int" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalHttpStatus", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSHttpStatus", - "_1" : "Int" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSHttpStatus", - "_1" : "Int" - } - } - } - } - }, - { - "abiName" : "bjs_setPriority", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setPriority", - "parameters" : [ - { - "label" : "_", - "name" : "priority", - "type" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int32" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getPriority", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getPriority", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int32" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalPriority", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalPriority", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int32" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int32" - } - } - } - } - }, - { - "abiName" : "bjs_setFileSize", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setFileSize", - "parameters" : [ - { - "label" : "_", - "name" : "size", - "type" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getFileSize", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getFileSize", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalFileSize", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalFileSize", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - } - } - } - }, - { - "abiName" : "bjs_setUserId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setUserId", - "parameters" : [ - { - "label" : "_", - "name" : "id", - "type" : { - "rawValueEnum" : { - "_0" : "UserId", - "_1" : "UInt" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getUserId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getUserId", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "UserId", - "_1" : "UInt" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalUserId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalUserId", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "UserId", - "_1" : "UInt" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "UserId", - "_1" : "UInt" - } - } - } - } - }, - { - "abiName" : "bjs_setTokenId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setTokenId", - "parameters" : [ - { - "label" : "_", - "name" : "token", - "type" : { - "rawValueEnum" : { - "_0" : "TokenId", - "_1" : "UInt32" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getTokenId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTokenId", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "TokenId", - "_1" : "UInt32" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalTokenId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalTokenId", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TokenId", - "_1" : "UInt32" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TokenId", - "_1" : "UInt32" - } - } - } - } - }, - { - "abiName" : "bjs_setSessionId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setSessionId", - "parameters" : [ - { - "label" : "_", - "name" : "session", - "type" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getSessionId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getSessionId", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalSessionId", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalSessionId", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" - } - } - } - } - }, - { - "abiName" : "bjs_setPrecision", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setPrecision", - "parameters" : [ - { - "label" : "_", - "name" : "precision", - "type" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getPrecision", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getPrecision", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalPrecision", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalPrecision", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - } - }, - { - "abiName" : "bjs_setRatio", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setRatio", - "parameters" : [ - { - "label" : "_", - "name" : "ratio", - "type" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_getRatio", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getRatio", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" - } - } - }, - { - "abiName" : "bjs_roundTripOptionalRatio", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalRatio", - "parameters" : [ - { - "label" : "_", - "name" : "input", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" - } - } - } - } - }, - { - "abiName" : "bjs_processTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processTheme", - "parameters" : [ - { - "label" : "_", - "name" : "theme", - "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - }, - { - "abiName" : "bjs_convertPriority", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "convertPriority", - "parameters" : [ - { - "label" : "_", - "name" : "status", - "type" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - } - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int32" - } - } - }, - { - "abiName" : "bjs_validateSession", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "validateSession", - "parameters" : [ - { - "label" : "_", - "name" : "session", - "type" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" - } - } - } - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.json deleted file mode 100644 index 6ee073ca8..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_makeFoo", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "makeFoo", - "parameters" : [ - - ], - "returnType" : { - "jsObject" : { - "_0" : "Foo" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.swift deleted file mode 100644 index 0bebd4e73..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/ImportedTypeInExportedInterface.swift +++ /dev/null @@ -1,24 +0,0 @@ -@_expose(wasm, "bjs_makeFoo") -@_cdecl("bjs_makeFoo") -public func _bjs_makeFoo() -> Int32 { - #if arch(wasm32) - do { - let ret = try makeFoo() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.json deleted file mode 100644 index 5409a400e..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedGlobal.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_GlobalClass_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_GlobalClass_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "GlobalClass", - "namespace" : [ - "GlobalAPI" - ], - "properties" : [ - - ], - "swiftCallName" : "GlobalClass" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_GlobalAPI_globalFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "globalFunction", - "namespace" : [ - "GlobalAPI" - ], - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.json deleted file mode 100644 index bc58d985e..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/MixedPrivate.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_PrivateClass_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_PrivateClass_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "PrivateClass", - "namespace" : [ - "PrivateAPI" - ], - "properties" : [ - - ], - "swiftCallName" : "PrivateClass" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_PrivateAPI_privateFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "privateFunction", - "namespace" : [ - "PrivateAPI" - ], - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.json deleted file mode 100644 index eb11e983f..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.Global.json +++ /dev/null @@ -1,182 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Greeter", - "namespace" : [ - "__Swift", - "Foundation" - ], - "properties" : [ - - ], - "swiftCallName" : "Greeter" - }, - { - "constructor" : { - "abiName" : "bjs_Converter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_Converter_toString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "toString", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Converter", - "namespace" : [ - "Utils", - "Converters" - ], - "properties" : [ - - ], - "swiftCallName" : "Converter" - }, - { - "methods" : [ - { - "abiName" : "bjs_UUID_uuidString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "uuidString", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "UUID", - "namespace" : [ - "__Swift", - "Foundation" - ], - "properties" : [ - - ], - "swiftCallName" : "UUID" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : true, - "functions" : [ - { - "abiName" : "bjs_plainFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "plainFunction", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_MyModule_Utils_namespacedFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "namespacedFunction", - "namespace" : [ - "MyModule", - "Utils" - ], - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.json deleted file mode 100644 index 914b7b894..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Namespaces.json +++ /dev/null @@ -1,182 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Greeter", - "namespace" : [ - "__Swift", - "Foundation" - ], - "properties" : [ - - ], - "swiftCallName" : "Greeter" - }, - { - "constructor" : { - "abiName" : "bjs_Converter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_Converter_toString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "toString", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Converter", - "namespace" : [ - "Utils", - "Converters" - ], - "properties" : [ - - ], - "swiftCallName" : "Converter" - }, - { - "methods" : [ - { - "abiName" : "bjs_UUID_uuidString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "uuidString", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "UUID", - "namespace" : [ - "__Swift", - "Foundation" - ], - "properties" : [ - - ], - "swiftCallName" : "UUID" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_plainFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "plainFunction", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_MyModule_Utils_namespacedFunction", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "namespacedFunction", - "namespace" : [ - "MyModule", - "Utils" - ], - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.json deleted file mode 100644 index b3a4fc2c0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.json +++ /dev/null @@ -1,699 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_Greeter_changeName", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "changeName", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "Greeter", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "swiftCallName" : "Greeter" - }, - { - "constructor" : { - "abiName" : "bjs_OptionalPropertyHolder_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "OptionalPropertyHolder", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalName", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalAge", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalGreeter", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } - } - ], - "swiftCallName" : "OptionalPropertyHolder" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundTripOptionalClass", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalClass", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } - }, - { - "abiName" : "bjs_testOptionalPropertyRoundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testOptionalPropertyRoundtrip", - "parameters" : [ - { - "label" : "_", - "name" : "holder", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "OptionalPropertyHolder" - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "OptionalPropertyHolder" - } - } - } - } - }, - { - "abiName" : "bjs_roundTripString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripString", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripBool", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripBool", - "parameters" : [ - { - "label" : "flag", - "name" : "flag", - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripFloat", - "parameters" : [ - { - "label" : "number", - "name" : "number", - "type" : { - "optional" : { - "_0" : { - "float" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "float" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDouble", - "parameters" : [ - { - "label" : "precision", - "name" : "precision", - "type" : { - "optional" : { - "_0" : { - "double" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "double" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripSyntax", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSyntax", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripMixSyntax", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripMixSyntax", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripSwiftSyntax", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSwiftSyntax", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripMixedSwiftSyntax", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripMixedSwiftSyntax", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripWithSpaces", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripWithSpaces", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "optional" : { - "_0" : { - "double" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "double" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripAlias", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripAlias", - "parameters" : [ - { - "label" : "age", - "name" : "age", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalAlias", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalAlias", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "abiName" : "bjs_testMixedOptionals", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testMixedOptionals", - "parameters" : [ - { - "label" : "firstName", - "name" : "firstName", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "label" : "lastName", - "name" : "lastName", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "label" : "age", - "name" : "age", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "label" : "active", - "name" : "active", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.swift deleted file mode 100644 index 88195f37d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Optionals.swift +++ /dev/null @@ -1,341 +0,0 @@ -@_expose(wasm, "bjs_roundTripOptionalClass") -@_cdecl("bjs_roundTripOptionalClass") -public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testOptionalPropertyRoundtrip") -@_cdecl("bjs_testOptionalPropertyRoundtrip") -public func _bjs_testOptionalPropertyRoundtrip(_ holderIsSome: Int32, _ holderValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = testOptionalPropertyRoundtrip(_: Optional.bridgeJSLiftParameter(holderIsSome, holderValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripString") -@_cdecl("bjs_roundTripString") -public func _bjs_roundTripString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripInt") -@_cdecl("bjs_roundTripInt") -public func _bjs_roundTripInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripBool") -@_cdecl("bjs_roundTripBool") -public func _bjs_roundTripBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripFloat") -@_cdecl("bjs_roundTripFloat") -public func _bjs_roundTripFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { - #if arch(wasm32) - let ret = roundTripFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripDouble") -@_cdecl("bjs_roundTripDouble") -public func _bjs_roundTripDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { - #if arch(wasm32) - let ret = roundTripDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripSyntax") -@_cdecl("bjs_roundTripSyntax") -public func _bjs_roundTripSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripMixSyntax") -@_cdecl("bjs_roundTripMixSyntax") -public func _bjs_roundTripMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripSwiftSyntax") -@_cdecl("bjs_roundTripSwiftSyntax") -public func _bjs_roundTripSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripMixedSwiftSyntax") -@_cdecl("bjs_roundTripMixedSwiftSyntax") -public func _bjs_roundTripMixedSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripMixedSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripWithSpaces") -@_cdecl("bjs_roundTripWithSpaces") -public func _bjs_roundTripWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { - #if arch(wasm32) - let ret = roundTripWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripAlias") -@_cdecl("bjs_roundTripAlias") -public func _bjs_roundTripAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundTripOptionalAlias") -@_cdecl("bjs_roundTripOptionalAlias") -public func _bjs_roundTripOptionalAlias(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalAlias(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testMixedOptionals") -@_cdecl("bjs_testMixedOptionals") -public func _bjs_testMixedOptionals(_ firstNameIsSome: Int32, _ firstNameBytes: Int32, _ firstNameLength: Int32, _ lastNameIsSome: Int32, _ lastNameBytes: Int32, _ lastNameLength: Int32, _ ageIsSome: Int32, _ ageValue: Int32, _ active: Int32) -> Void { - #if arch(wasm32) - let ret = testMixedOptionals(firstName: Optional.bridgeJSLiftParameter(firstNameIsSome, firstNameBytes, firstNameLength), lastName: Optional.bridgeJSLiftParameter(lastNameIsSome, lastNameBytes, lastNameLength), age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue), active: Bool.bridgeJSLiftParameter(active)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_init") -@_cdecl("bjs_Greeter_init") -public func _bjs_Greeter_init(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = Greeter(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_greet") -@_cdecl("bjs_Greeter_greet") -public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_changeName") -@_cdecl("bjs_Greeter_changeName") -public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { - #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_name_get") -@_cdecl("bjs_Greeter_name_get") -public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_name_set") -@_cdecl("bjs_Greeter_name_set") -public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).name = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Greeter_deinit") -@_cdecl("bjs_Greeter_deinit") -public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -@_expose(wasm, "bjs_OptionalPropertyHolder_init") -@_cdecl("bjs_OptionalPropertyHolder_init") -public func _bjs_OptionalPropertyHolder_init() -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = OptionalPropertyHolder() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") -public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") -public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") -public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") -public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") -public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") -public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") -@_cdecl("bjs_OptionalPropertyHolder_deinit") -public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_OptionalPropertyHolder_wrap") -fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.json deleted file mode 100644 index 3b45bf30f..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_check", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "check", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "uint" : { - - } - } - }, - { - "label" : "c", - "name" : "c", - "type" : { - "float" : { - - } - } - }, - { - "label" : "d", - "name" : "d", - "type" : { - "double" : { - - } - } - }, - { - "label" : "e", - "name" : "e", - "type" : { - "bool" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.swift deleted file mode 100644 index f91e1e213..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveParameters.swift +++ /dev/null @@ -1,9 +0,0 @@ -@_expose(wasm, "bjs_check") -@_cdecl("bjs_check") -public func _bjs_check(_ a: Int32, _ b: Int32, _ c: Float32, _ d: Float64, _ e: Int32) -> Void { - #if arch(wasm32) - check(a: Int.bridgeJSLiftParameter(a), b: UInt.bridgeJSLiftParameter(b), c: Float.bridgeJSLiftParameter(c), d: Double.bridgeJSLiftParameter(d), e: Bool.bridgeJSLiftParameter(e)) - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.json deleted file mode 100644 index d70b0c9b5..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PrimitiveReturn.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_checkInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkInt", - "parameters" : [ - - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_checkUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkUInt", - "parameters" : [ - - ], - "returnType" : { - "uint" : { - - } - } - }, - { - "abiName" : "bjs_checkFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkFloat", - "parameters" : [ - - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_checkDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkDouble", - "parameters" : [ - - ], - "returnType" : { - "double" : { - - } - } - }, - { - "abiName" : "bjs_checkBool", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkBool", - "parameters" : [ - - ], - "returnType" : { - "bool" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.json deleted file mode 100644 index 43d05d9fa..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/PropertyTypes.json +++ /dev/null @@ -1,360 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_PropertyHolder_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "intValue", - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "label" : "floatValue", - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "label" : "doubleValue", - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "label" : "boolValue", - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "stringValue", - "name" : "stringValue", - "type" : { - "string" : { - - } - } - }, - { - "label" : "jsObject", - "name" : "jsObject", - "type" : { - "jsObject" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_PropertyHolder_getAllValues", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getAllValues", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "PropertyHolder", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "stringValue", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "readonlyInt", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "readonlyFloat", - "type" : { - "float" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "readonlyDouble", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "readonlyBool", - "type" : { - "bool" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "readonlyString", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "jsObject", - "type" : { - "jsObject" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "sibling", - "type" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "lazyValue", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "computedReadonly", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "computedReadWrite", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "observedProperty", - "type" : { - "int" : { - - } - } - } - ], - "swiftCallName" : "PropertyHolder" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_createPropertyHolder", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createPropertyHolder", - "parameters" : [ - { - "label" : "intValue", - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "label" : "floatValue", - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "label" : "doubleValue", - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "label" : "boolValue", - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "stringValue", - "name" : "stringValue", - "type" : { - "string" : { - - } - } - }, - { - "label" : "jsObject", - "name" : "jsObject", - "type" : { - "jsObject" : { - - } - } - } - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" - } - } - }, - { - "abiName" : "bjs_testPropertyHolder", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testPropertyHolder", - "parameters" : [ - { - "label" : "holder", - "name" : "holder", - "type" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.json deleted file mode 100644 index eb8f2426a..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Protocol.json +++ /dev/null @@ -1,898 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Helper_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Helper_increment", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "increment", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "Helper", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "swiftCallName" : "Helper" - }, - { - "constructor" : { - "abiName" : "bjs_MyViewController_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "delegate", - "name" : "delegate", - "type" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_MyViewController_triggerEvent", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "triggerEvent", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewController_updateValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "updateValue", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewController_updateCount", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "updateCount", - "parameters" : [ - { - "label" : "_", - "name" : "count", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_MyViewController_updateLabel", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "updateLabel", - "parameters" : [ - { - "label" : "_", - "name" : "prefix", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "suffix", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewController_checkEvenCount", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkEvenCount", - "parameters" : [ - - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_MyViewController_sendHelper", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "sendHelper", - "parameters" : [ - { - "label" : "_", - "name" : "helper", - "type" : { - "swiftHeapObject" : { - "_0" : "Helper" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "MyViewController", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "delegate", - "type" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "secondDelegate", - "type" : { - "optional" : { - "_0" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - } - } - ], - "swiftCallName" : "MyViewController" - }, - { - "constructor" : { - "abiName" : "bjs_DelegateManager_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "delegates", - "name" : "delegates", - "type" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_DelegateManager_notifyAll", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "notifyAll", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "DelegateManager", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "delegates", - "type" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - } - } - ], - "swiftCallName" : "DelegateManager" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "const", - "name" : "Direction", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "test", - "rawValue" : "test" - }, - { - "associatedValues" : [ - - ], - "name" : "test2", - "rawValue" : "test2" - } - ], - "emitStyle" : "const", - "name" : "ExampleEnum", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "ExampleEnum", - "tsFullPath" : "ExampleEnum" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - } - ], - "emitStyle" : "const", - "name" : "Result", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Result", - "tsFullPath" : "Result" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "low", - "rawValue" : "-1" - }, - { - "associatedValues" : [ - - ], - "name" : "medium", - "rawValue" : "0" - }, - { - "associatedValues" : [ - - ], - "name" : "high", - "rawValue" : "1" - } - ], - "emitStyle" : "const", - "name" : "Priority", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Priority", - "tsFullPath" : "Priority" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_processDelegates", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processDelegates", - "parameters" : [ - { - "label" : "_", - "name" : "delegates", - "type" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "swiftProtocol" : { - "_0" : "MyViewControllerDelegate" - } - } - } - } - } - ], - "protocols" : [ - { - "methods" : [ - { - "abiName" : "bjs_MyViewControllerDelegate_onSomethingHappened", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onSomethingHappened", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_onValueChanged", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onValueChanged", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_onCountUpdated", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onCountUpdated", - "parameters" : [ - { - "label" : "count", - "name" : "count", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_onLabelUpdated", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onLabelUpdated", - "parameters" : [ - { - "label" : "_", - "name" : "prefix", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "suffix", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_isCountEven", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "isCountEven", - "parameters" : [ - - ], - "returnType" : { - "bool" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_onHelperUpdated", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onHelperUpdated", - "parameters" : [ - { - "label" : "_", - "name" : "helper", - "type" : { - "swiftHeapObject" : { - "_0" : "Helper" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_createHelper", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createHelper", - "parameters" : [ - - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Helper" - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_onOptionalHelperUpdated", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "onOptionalHelperUpdated", - "parameters" : [ - { - "label" : "_", - "name" : "helper", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Helper" - } - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_createOptionalHelper", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createOptionalHelper", - "parameters" : [ - - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Helper" - } - } - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_createEnum", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createEnum", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "ExampleEnum", - "_1" : "String" - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_handleResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "handleResult", - "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "Result" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_MyViewControllerDelegate_getResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getResult", - "parameters" : [ - - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "Result" - } - } - } - ], - "name" : "MyViewControllerDelegate", - "properties" : [ - { - "isReadonly" : false, - "name" : "eventCount", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "name" : "delegateName", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "name" : "optionalName", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "isReadonly" : false, - "name" : "optionalRawEnum", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "ExampleEnum", - "_1" : "String" - } - } - } - } - }, - { - "isReadonly" : false, - "name" : "rawStringEnum", - "type" : { - "rawValueEnum" : { - "_0" : "ExampleEnum", - "_1" : "String" - } - } - }, - { - "isReadonly" : false, - "name" : "result", - "type" : { - "associatedValueEnum" : { - "_0" : "Result" - } - } - }, - { - "isReadonly" : false, - "name" : "optionalResult", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "Result" - } - } - } - } - }, - { - "isReadonly" : false, - "name" : "direction", - "type" : { - "caseEnum" : { - "_0" : "Direction" - } - } - }, - { - "isReadonly" : false, - "name" : "directionOptional", - "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - }, - { - "isReadonly" : false, - "name" : "priority", - "type" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int" - } - } - }, - { - "isReadonly" : false, - "name" : "priorityOptional", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Priority", - "_1" : "Int" - } - } - } - } - } - ] - } - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.json deleted file mode 100644 index 3b6937c30..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.Global.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_MathUtils_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_MathUtils_static_subtract", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "subtract", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } - }, - { - "abiName" : "bjs_MathUtils_static_add", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "add", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } - }, - { - "abiName" : "bjs_MathUtils_multiply", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "multiply", - "parameters" : [ - { - "label" : "x", - "name" : "x", - "type" : { - "int" : { - - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - } - ], - "name" : "MathUtils", - "properties" : [ - - ], - "swiftCallName" : "MathUtils" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "scientific" - }, - { - "associatedValues" : [ - - ], - "name" : "basic" - } - ], - "emitStyle" : "const", - "name" : "Calculator", - "staticMethods" : [ - { - "abiName" : "bjs_Calculator_static_square", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "square", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Calculator", - "tsFullPath" : "Calculator" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - { - "abiName" : "bjs_APIResult_static_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "staticContext" : { - "enumName" : { - "_0" : "APIResult" - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "String", - "namespace" : [ - "Utils" - ], - "staticMethods" : [ - { - "abiName" : "bjs_Utils_String_static_uppercase", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "uppercase", - "namespace" : [ - "Utils", - "String" - ], - "parameters" : [ - { - "label" : "_", - "name" : "text", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - }, - "staticContext" : { - "namespaceEnum" : { - - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils.String", - "tsFullPath" : "Utils.String" - } - ], - "exposeToGlobal" : true, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.json deleted file mode 100644 index 652465dff..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticFunctions.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_MathUtils_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - { - "abiName" : "bjs_MathUtils_static_subtract", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "subtract", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } - }, - { - "abiName" : "bjs_MathUtils_static_add", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "add", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "int" : { - - } - } - }, - { - "label" : "b", - "name" : "b", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "className" : { - "_0" : "MathUtils" - } - } - }, - { - "abiName" : "bjs_MathUtils_multiply", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "multiply", - "parameters" : [ - { - "label" : "x", - "name" : "x", - "type" : { - "int" : { - - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - } - } - ], - "name" : "MathUtils", - "properties" : [ - - ], - "swiftCallName" : "MathUtils" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "scientific" - }, - { - "associatedValues" : [ - - ], - "name" : "basic" - } - ], - "emitStyle" : "const", - "name" : "Calculator", - "staticMethods" : [ - { - "abiName" : "bjs_Calculator_static_square", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "square", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { - - } - } - } - ], - "returnType" : { - "int" : { - - } - }, - "staticContext" : { - "enumName" : { - "_0" : "Calculator" - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Calculator", - "tsFullPath" : "Calculator" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - { - "abiName" : "bjs_APIResult_static_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - }, - "staticContext" : { - "enumName" : { - "_0" : "APIResult" - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Utils", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils", - "tsFullPath" : "Utils" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "String", - "namespace" : [ - "Utils" - ], - "staticMethods" : [ - { - "abiName" : "bjs_Utils_String_static_uppercase", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "uppercase", - "namespace" : [ - "Utils", - "String" - ], - "parameters" : [ - { - "label" : "_", - "name" : "text", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - }, - "staticContext" : { - "namespaceEnum" : { - - } - } - } - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Utils.String", - "tsFullPath" : "Utils.String" - } - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.json deleted file mode 100644 index 4ec19f83c..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.Global.json +++ /dev/null @@ -1,339 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_PropertyClass_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "PropertyClass", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "staticConstant", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "staticVariable", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "jsObjectProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "jsObject" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "classVariable", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "readOnlyComputed", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "optionalProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "swiftCallName" : "PropertyClass" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "value1" - }, - { - "associatedValues" : [ - - ], - "name" : "value2" - } - ], - "emitStyle" : "const", - "name" : "PropertyEnum", - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumProperty", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "enumConstant", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedEnum", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "PropertyEnum", - "tsFullPath" : "PropertyEnum" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "PropertyNamespace", - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "namespaceProperty", - "namespace" : [ - "PropertyNamespace" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "namespaceConstant", - "namespace" : [ - "PropertyNamespace" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "PropertyNamespace", - "tsFullPath" : "PropertyNamespace" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Nested", - "namespace" : [ - "PropertyNamespace" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedProperty", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "nestedConstant", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedDouble", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "PropertyNamespace.Nested", - "tsFullPath" : "PropertyNamespace.Nested" - } - ], - "exposeToGlobal" : true, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.json deleted file mode 100644 index 0e8b2de22..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StaticProperties.json +++ /dev/null @@ -1,339 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_PropertyClass_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - - ] - }, - "methods" : [ - - ], - "name" : "PropertyClass", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "staticConstant", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "staticVariable", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "jsObjectProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "jsObject" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "classVariable", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "readOnlyComputed", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "optionalProperty", - "staticContext" : { - "className" : { - "_0" : "PropertyClass" - } - }, - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "swiftCallName" : "PropertyClass" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "value1" - }, - { - "associatedValues" : [ - - ], - "name" : "value2" - } - ], - "emitStyle" : "const", - "name" : "PropertyEnum", - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "enumProperty", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "enumConstant", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "computedEnum", - "staticContext" : { - "enumName" : { - "_0" : "PropertyEnum" - } - }, - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "PropertyEnum", - "tsFullPath" : "PropertyEnum" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "PropertyNamespace", - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "namespaceProperty", - "namespace" : [ - "PropertyNamespace" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "namespaceConstant", - "namespace" : [ - "PropertyNamespace" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "PropertyNamespace", - "tsFullPath" : "PropertyNamespace" - }, - { - "cases" : [ - - ], - "emitStyle" : "const", - "name" : "Nested", - "namespace" : [ - "PropertyNamespace" - ], - "staticMethods" : [ - - ], - "staticProperties" : [ - { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedProperty", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "nestedConstant", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "nestedDouble", - "namespace" : [ - "PropertyNamespace", - "Nested" - ], - "staticContext" : { - "namespaceEnum" : { - - } - }, - "type" : { - "double" : { - - } - } - } - ], - "swiftCallName" : "PropertyNamespace.Nested", - "tsFullPath" : "PropertyNamespace.Nested" - } - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.json deleted file mode 100644 index 9116fd482..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_checkString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkString", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_roundtripString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtripString", - "parameters" : [ - { - "label" : "a", - "name" : "a", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.swift deleted file mode 100644 index d980f5bc6..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringParameter.swift +++ /dev/null @@ -1,20 +0,0 @@ -@_expose(wasm, "bjs_checkString") -@_cdecl("bjs_checkString") -public func _bjs_checkString(_ aBytes: Int32, _ aLength: Int32) -> Void { - #if arch(wasm32) - checkString(a: String.bridgeJSLiftParameter(aBytes, aLength)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_roundtripString") -@_cdecl("bjs_roundtripString") -public func _bjs_roundtripString(_ aBytes: Int32, _ aLength: Int32) -> Void { - #if arch(wasm32) - let ret = roundtripString(a: String.bridgeJSLiftParameter(aBytes, aLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.json deleted file mode 100644 index 01f9ca4b7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_checkString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "checkString", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.swift deleted file mode 100644 index 1c260ec55..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/StringReturn.swift +++ /dev/null @@ -1,10 +0,0 @@ -@_expose(wasm, "bjs_checkString") -@_cdecl("bjs_checkString") -public func _bjs_checkString() -> Void { - #if arch(wasm32) - let ret = checkString() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.json deleted file mode 100644 index b8f908c2d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClass.json +++ /dev/null @@ -1,142 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_Greeter_changeName", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "changeName", - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "name" : "Greeter", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "Greeter" - }, - { - "explicitAccessControl" : "public", - "methods" : [ - - ], - "name" : "PublicGreeter", - "properties" : [ - - ], - "swiftCallName" : "PublicGreeter" - }, - { - "explicitAccessControl" : "package", - "methods" : [ - - ], - "name" : "PackageGreeter", - "properties" : [ - - ], - "swiftCallName" : "PackageGreeter" - } - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_takeGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeGreeter", - "parameters" : [ - { - "label" : "greeter", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - ], - "returnType" : { - "void" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.json deleted file mode 100644 index 27627407b..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.json +++ /dev/null @@ -1,1075 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Person_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "explicitAccessControl" : "public", - "methods" : [ - - ], - "name" : "Person", - "properties" : [ - - ], - "swiftCallName" : "Person" - }, - { - "constructor" : { - "abiName" : "bjs_TestProcessor_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "transform", - "name" : "transform", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSS_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_TestProcessor_getTransform", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getTransform", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSS_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_processWithCustom", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processWithCustom", - "parameters" : [ - { - "label" : "_", - "name" : "text", - "type" : { - "string" : { - - } - } - }, - { - "label" : "customTransform", - "name" : "customTransform", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSS_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_printTogether", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "printTogether", - "parameters" : [ - { - "label" : "person", - "name" : "person", - "type" : { - "swiftHeapObject" : { - "_0" : "Person" - } - } - }, - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "label" : "ratio", - "name" : "ratio", - "type" : { - "double" : { - - } - } - }, - { - "label" : "customTransform", - "name" : "customTransform", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq6PersonCSqSSSqSd_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Person" - } - } - } - }, - { - "optional" : { - "_0" : { - "string" : { - - } - } - } - }, - { - "optional" : { - "_0" : { - "double" : { - - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "_", - "name" : "personClosure", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule6PersonC_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "swiftHeapObject" : { - "_0" : "Person" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule6PersonC_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "swiftHeapObject" : { - "_0" : "Person" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_roundtripOptional", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtripOptional", - "parameters" : [ - { - "label" : "_", - "name" : "personClosure", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq6PersonC_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Person" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq6PersonC_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Person" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_processDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processDirection", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule9DirectionO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "caseEnum" : { - "_0" : "Direction" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_processTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processTheme", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule5ThemeO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_processHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processHttpStatus", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule10HttpStatusO_Si", - "moduleName" : "TestModule", - "parameters" : [ - { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - ], - "returnType" : { - "int" : { - - } - } - } - } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_processAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processAPIResult", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule9APIResultO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_makeDirectionChecker", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeDirectionChecker", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule9DirectionO_Sb", - "moduleName" : "TestModule", - "parameters" : [ - { - "caseEnum" : { - "_0" : "Direction" - } - } - ], - "returnType" : { - "bool" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_makeThemeValidator", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeThemeValidator", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule5ThemeO_Sb", - "moduleName" : "TestModule", - "parameters" : [ - { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - ], - "returnType" : { - "bool" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_makeStatusCodeExtractor", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeStatusCodeExtractor", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule10HttpStatusO_Si", - "moduleName" : "TestModule", - "parameters" : [ - { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - ], - "returnType" : { - "int" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_makeAPIResultHandler", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeAPIResultHandler", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModule9APIResultO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - }, - { - "abiName" : "bjs_TestProcessor_processOptionalDirection", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalDirection", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq9DirectionO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_processOptionalTheme", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalTheme", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq5ThemeO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_processOptionalAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalAPIResult", - "parameters" : [ - { - "label" : "_", - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq9APIResultO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_TestProcessor_makeOptionalDirectionFormatter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeOptionalDirectionFormatter", - "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "10TestModuleSq9DirectionO_SS", - "moduleName" : "TestModule", - "parameters" : [ - { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - ], - "returnType" : { - "string" : { - - } - } - } - } - } - } - ], - "name" : "TestProcessor", - "properties" : [ - - ], - "swiftCallName" : "TestProcessor" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" - }, - { - "associatedValues" : [ - - ], - "name" : "south" - }, - { - "associatedValues" : [ - - ], - "name" : "east" - }, - { - "associatedValues" : [ - - ], - "name" : "west" - } - ], - "emitStyle" : "const", - "name" : "Direction", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Direction", - "tsFullPath" : "Direction" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "light", - "rawValue" : "light" - }, - { - "associatedValues" : [ - - ], - "name" : "dark", - "rawValue" : "dark" - }, - { - "associatedValues" : [ - - ], - "name" : "auto", - "rawValue" : "auto" - } - ], - "emitStyle" : "const", - "name" : "Theme", - "rawType" : "String", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Theme", - "tsFullPath" : "Theme" - }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "ok", - "rawValue" : "200" - }, - { - "associatedValues" : [ - - ], - "name" : "notFound", - "rawValue" : "404" - }, - { - "associatedValues" : [ - - ], - "name" : "serverError", - "rawValue" : "500" - }, - { - "associatedValues" : [ - - ], - "name" : "unknown", - "rawValue" : "-1" - } - ], - "emitStyle" : "const", - "name" : "HttpStatus", - "rawType" : "Int", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "HttpStatus", - "tsFullPath" : "HttpStatus" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "int" : { - - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - { - "type" : { - "bool" : { - - } - } - } - ], - "name" : "flag" - }, - { - "associatedValues" : [ - { - "type" : { - "float" : { - - } - } - } - ], - "name" : "rate" - }, - { - "associatedValues" : [ - { - "type" : { - "double" : { - - } - } - } - ], - "name" : "precise" - }, - { - "associatedValues" : [ - - ], - "name" : "info" - } - ], - "emitStyle" : "const", - "name" : "APIResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "APIResult", - "tsFullPath" : "APIResult" - } - ], - "exposeToGlobal" : false, - "functions" : [ - - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.swift deleted file mode 100644 index 415aa54f6..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftClosure.swift +++ /dev/null @@ -1,1016 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule10HttpStatusO_Si") -fileprivate func invoke_js_callback_TestModule_10TestModule10HttpStatusO_Si(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule10HttpStatusO_Si(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule10HttpStatusO_Si: _BridgedSwiftClosureBox { - let closure: (HttpStatus) -> Int - init(_ closure: @escaping (HttpStatus) -> Int) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule10HttpStatusO_Si { - static func bridgeJSLower(_ closure: @escaping (HttpStatus) -> Int) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule10HttpStatusO_Si(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (HttpStatus) -> Int { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule10HttpStatusO_Si(callbackValue, param0Value) - return Int.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule10HttpStatusO_Si") -@_cdecl("invoke_swift_closure_TestModule_10TestModule10HttpStatusO_Si") -public func _invoke_swift_closure_TestModule_10TestModule10HttpStatusO_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule10HttpStatusO_Si>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(HttpStatus.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule5ThemeO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule5ThemeO_SS: _BridgedSwiftClosureBox { - let closure: (Theme) -> String - init(_ closure: @escaping (Theme) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule5ThemeO_SS { - static func bridgeJSLower(_ closure: @escaping (Theme) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule5ThemeO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Theme) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_SS(callbackValue, param0Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule5ThemeO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModule5ThemeO_SS") -public func _invoke_swift_closure_TestModule_10TestModule5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule5ThemeO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule5ThemeO_Sb") -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule5ThemeO_Sb: _BridgedSwiftClosureBox { - let closure: (Theme) -> Bool - init(_ closure: @escaping (Theme) -> Bool) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule5ThemeO_Sb { - static func bridgeJSLower(_ closure: @escaping (Theme) -> Bool) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule5ThemeO_Sb(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Theme) -> Bool { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_Sb(callbackValue, param0Value) - return Bool.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule5ThemeO_Sb") -@_cdecl("invoke_swift_closure_TestModule_10TestModule5ThemeO_Sb") -public func _invoke_swift_closure_TestModule_10TestModule5ThemeO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule5ThemeO_Sb>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule6PersonC_SS") -fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_SS(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule6PersonC_SS(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule6PersonC_SS: _BridgedSwiftClosureBox { - let closure: (Person) -> String - init(_ closure: @escaping (Person) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule6PersonC_SS { - static func bridgeJSLower(_ closure: @escaping (Person) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule6PersonC_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Person) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Pointer = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule6PersonC_SS(callbackValue, param0Pointer) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule6PersonC_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModule6PersonC_SS") -public func _invoke_swift_closure_TestModule_10TestModule6PersonC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule6PersonC_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Person.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule9APIResultO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModule9APIResultO_SS(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule9APIResultO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule9APIResultO_SS: _BridgedSwiftClosureBox { - let closure: (APIResult) -> String - init(_ closure: @escaping (APIResult) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule9APIResultO_SS { - static func bridgeJSLower(_ closure: @escaping (APIResult) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule9APIResultO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (APIResult) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0CaseId = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule9APIResultO_SS(callbackValue, param0CaseId) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule9APIResultO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModule9APIResultO_SS") -public func _invoke_swift_closure_TestModule_10TestModule9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule9APIResultO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(APIResult.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule9DirectionO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_SS(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule9DirectionO_SS: _BridgedSwiftClosureBox { - let closure: (Direction) -> String - init(_ closure: @escaping (Direction) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule9DirectionO_SS { - static func bridgeJSLower(_ closure: @escaping (Direction) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule9DirectionO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Direction) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule9DirectionO_SS(callbackValue, param0Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule9DirectionO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModule9DirectionO_SS") -public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule9DirectionO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Direction.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule9DirectionO_Sb") -fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModule9DirectionO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModule9DirectionO_Sb: _BridgedSwiftClosureBox { - let closure: (Direction) -> Bool - init(_ closure: @escaping (Direction) -> Bool) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModule9DirectionO_Sb { - static func bridgeJSLower(_ closure: @escaping (Direction) -> Bool) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModule9DirectionO_Sb(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Direction) -> Bool { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule9DirectionO_Sb(callbackValue, param0Value) - return Bool.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule9DirectionO_Sb") -@_cdecl("invoke_swift_closure_TestModule_10TestModule9DirectionO_Sb") -public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModule9DirectionO_Sb>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Direction.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSS_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSS_SS: _BridgedSwiftClosureBox { - let closure: (String) -> String - init(_ closure: @escaping (String) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSS_SS { - static func bridgeJSLower(_ closure: @escaping (String) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSS_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (String) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSS_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSS_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSS_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq5ThemeO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSq5ThemeO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSq5ThemeO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSq5ThemeO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSq5ThemeO_SS(callbackValue, param0IsSome, param0Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSq5ThemeO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer, _ param1IsSome: Int32, _ param1Value: Int32, _ param2IsSome: Int32, _ param2Value: Float64) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer, _ param1IsSome: Int32, _ param1Value: Int32, _ param2IsSome: Int32, _ param2Value: Float64) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSq6PersonCSqSSSqSd_SS: _BridgedSwiftClosureBox { - let closure: (Optional, Optional, Optional) -> String - init(_ closure: @escaping (Optional, Optional, Optional) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSq6PersonCSqSSSqSd_SS { - static func bridgeJSLower(_ closure: @escaping (Optional, Optional, Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSq6PersonCSqSSSqSd_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional, Optional, Optional) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0, param1, param2 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() - let (param1IsSome, param1Value) = param1.bridgeJSLowerParameter() - let (param2IsSome, param2Value) = param2.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS(callbackValue, param0IsSome, param0Pointer, param1IsSome, param1Value, param2IsSome, param2Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSq6PersonCSqSSSqSd_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer, _ param1IsSome: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2IsSome: Int32, _ param2Value: Float64) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSq6PersonCSqSSSqSd_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value), Optional.bridgeJSLiftParameter(param1IsSome, param1Bytes, param1Length), Optional.bridgeJSLiftParameter(param2IsSome, param2Value)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq6PersonC_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6PersonC_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSq6PersonC_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSq6PersonC_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSq6PersonC_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSq6PersonC_SS(callbackValue, param0IsSome, param0Pointer) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq6PersonC_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq6PersonC_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSq6PersonC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSq6PersonC_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq9APIResultO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq9APIResultO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq9APIResultO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSq9APIResultO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSq9APIResultO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSq9APIResultO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSq9APIResultO_SS(callbackValue, param0IsSome, param0CaseId) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSq9APIResultO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq9DirectionO_SS") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq9DirectionO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq9DirectionO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_10TestModuleSq9DirectionO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } -} - -private enum _BJS_Closure_10TestModuleSq9DirectionO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_10TestModuleSq9DirectionO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModuleSq9DirectionO_SS(callbackValue, param0IsSome, param0Value) - return String.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_SS") -@_cdecl("invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_SS") -public func _invoke_swift_closure_TestModule_10TestModuleSq9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_10TestModuleSq9DirectionO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension Direction: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { - return Direction(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } - - private init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .north - case 1: - self = .south - case 2: - self = .east - case 3: - self = .west - default: - return nil - } - } - - private var bridgeJSRawValue: Int32 { - switch self { - case .north: - return 0 - case .south: - return 1 - case .east: - return 2 - case .west: - return 3 - } - } -} - -extension Theme: _BridgedSwiftEnumNoPayload { -} - -extension HttpStatus: _BridgedSwiftEnumNoPayload { -} - -extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { - switch caseId { - case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 2: - return .flag(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - case 3: - return .rate(Float.bridgeJSLiftParameter(_swift_js_pop_f32())) - case 4: - return .precise(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - case 5: - return .info - default: - fatalError("Unknown APIResult case ID: \(caseId)") - } - } - - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch self { - case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - return Int32(0) - case .failure(let param0): - _swift_js_push_i32(Int32(param0)) - return Int32(1) - case .flag(let param0): - _swift_js_push_i32(param0 ? 1 : 0) - return Int32(2) - case .rate(let param0): - _swift_js_push_f32(param0) - return Int32(3) - case .precise(let param0): - _swift_js_push_f64(param0) - return Int32(4) - case .info: - return Int32(5) - } - } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - case .flag(let param0): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - case .rate(let param0): - _swift_js_push_tag(Int32(3)) - _swift_js_push_f32(param0) - case .precise(let param0): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - case .info: - _swift_js_push_tag(Int32(5)) - } - } -} - -@_expose(wasm, "bjs_Person_init") -@_cdecl("bjs_Person_init") -public func _bjs_Person_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = Person(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Person_deinit") -@_cdecl("bjs_Person_deinit") -public func _bjs_Person_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension Person: ConvertibleToJSValue, _BridgedSwiftHeapObject { - public var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Person_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_Person_wrap") -fileprivate func _bjs_Person_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Person_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -@_expose(wasm, "bjs_TestProcessor_init") -@_cdecl("bjs_TestProcessor_init") -public func _bjs_TestProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor(transform: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(transform)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_getTransform") -@_cdecl("bjs_TestProcessor_getTransform") -public func _bjs_TestProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).getTransform() - return _BJS_Closure_10TestModuleSS_SS.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processWithCustom") -@_cdecl("bjs_TestProcessor_processWithCustom") -public func _bjs_TestProcessor_processWithCustom(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32, _ customTransform: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processWithCustom(_: String.bridgeJSLiftParameter(textBytes, textLength), customTransform: _BJS_Closure_10TestModuleSS_SS.bridgeJSLift(customTransform)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_printTogether") -@_cdecl("bjs_TestProcessor_printTogether") -public func _bjs_TestProcessor_printTogether(_ _self: UnsafeMutableRawPointer, _ person: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32, _ ratio: Float64, _ customTransform: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).printTogether(person: Person.bridgeJSLiftParameter(person), name: String.bridgeJSLiftParameter(nameBytes, nameLength), ratio: Double.bridgeJSLiftParameter(ratio), customTransform: _BJS_Closure_10TestModuleSq6PersonCSqSSSqSd_SS.bridgeJSLift(customTransform)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_roundtrip") -@_cdecl("bjs_TestProcessor_roundtrip") -public func _bjs_TestProcessor_roundtrip(_ _self: UnsafeMutableRawPointer, _ personClosure: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).roundtrip(_: _BJS_Closure_10TestModule6PersonC_SS.bridgeJSLift(personClosure)) - return _BJS_Closure_10TestModule6PersonC_SS.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_roundtripOptional") -@_cdecl("bjs_TestProcessor_roundtripOptional") -public func _bjs_TestProcessor_roundtripOptional(_ _self: UnsafeMutableRawPointer, _ personClosure: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).roundtripOptional(_: _BJS_Closure_10TestModuleSq6PersonC_SS.bridgeJSLift(personClosure)) - return _BJS_Closure_10TestModuleSq6PersonC_SS.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processDirection") -@_cdecl("bjs_TestProcessor_processDirection") -public func _bjs_TestProcessor_processDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processDirection(_: _BJS_Closure_10TestModule9DirectionO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processTheme") -@_cdecl("bjs_TestProcessor_processTheme") -public func _bjs_TestProcessor_processTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processTheme(_: _BJS_Closure_10TestModule5ThemeO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processHttpStatus") -@_cdecl("bjs_TestProcessor_processHttpStatus") -public func _bjs_TestProcessor_processHttpStatus(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processHttpStatus(_: _BJS_Closure_10TestModule10HttpStatusO_Si.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processAPIResult") -@_cdecl("bjs_TestProcessor_processAPIResult") -public func _bjs_TestProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processAPIResult(_: _BJS_Closure_10TestModule9APIResultO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_makeDirectionChecker") -@_cdecl("bjs_TestProcessor_makeDirectionChecker") -public func _bjs_TestProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).makeDirectionChecker() - return _BJS_Closure_10TestModule9DirectionO_Sb.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_makeThemeValidator") -@_cdecl("bjs_TestProcessor_makeThemeValidator") -public func _bjs_TestProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).makeThemeValidator() - return _BJS_Closure_10TestModule5ThemeO_Sb.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_makeStatusCodeExtractor") -@_cdecl("bjs_TestProcessor_makeStatusCodeExtractor") -public func _bjs_TestProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).makeStatusCodeExtractor() - return _BJS_Closure_10TestModule10HttpStatusO_Si.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_makeAPIResultHandler") -@_cdecl("bjs_TestProcessor_makeAPIResultHandler") -public func _bjs_TestProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).makeAPIResultHandler() - return _BJS_Closure_10TestModule9APIResultO_SS.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processOptionalDirection") -@_cdecl("bjs_TestProcessor_processOptionalDirection") -public func _bjs_TestProcessor_processOptionalDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processOptionalDirection(_: _BJS_Closure_10TestModuleSq9DirectionO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processOptionalTheme") -@_cdecl("bjs_TestProcessor_processOptionalTheme") -public func _bjs_TestProcessor_processOptionalTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processOptionalTheme(_: _BJS_Closure_10TestModuleSq5ThemeO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_processOptionalAPIResult") -@_cdecl("bjs_TestProcessor_processOptionalAPIResult") -public func _bjs_TestProcessor_processOptionalAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).processOptionalAPIResult(_: _BJS_Closure_10TestModuleSq9APIResultO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_makeOptionalDirectionFormatter") -@_cdecl("bjs_TestProcessor_makeOptionalDirectionFormatter") -public func _bjs_TestProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = TestProcessor.bridgeJSLiftParameter(_self).makeOptionalDirectionFormatter() - return _BJS_Closure_10TestModuleSq9DirectionO_SS.bridgeJSLower(ret) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_TestProcessor_deinit") -@_cdecl("bjs_TestProcessor_deinit") -public func _bjs_TestProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension TestProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TestProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "TestModule", name: "bjs_TestProcessor_wrap") -fileprivate func _bjs_TestProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_TestProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.json deleted file mode 100644 index ca8f7c625..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/SwiftStruct.json +++ /dev/null @@ -1,520 +0,0 @@ -{ - "classes" : [ - { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_Greeter_greet", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "greet", - "parameters" : [ - - ], - "returnType" : { - "string" : { - - } - } - } - ], - "name" : "Greeter", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "Greeter" - } - ], - "enums" : [ - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "rough", - "rawValue" : "0.1" - }, - { - "associatedValues" : [ - - ], - "name" : "fine", - "rawValue" : "0.001" - } - ], - "emitStyle" : "const", - "name" : "Precision", - "rawType" : "Float", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "Precision", - "tsFullPath" : "Precision" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundtrip", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundtrip", - "parameters" : [ - { - "label" : "_", - "name" : "session", - "type" : { - "swiftStruct" : { - "_0" : "Person" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "Person" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - { - "constructor" : { - "abiName" : "bjs_DataPoint_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "x", - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "double" : { - - } - } - }, - { - "label" : "label", - "name" : "label", - "type" : { - "string" : { - - } - } - }, - { - "label" : "optCount", - "name" : "optCount", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "label" : "optFlag", - "name" : "optFlag", - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "DataPoint", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "y", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "label", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "optCount", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "optFlag", - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } - } - } - ], - "swiftCallName" : "DataPoint" - }, - { - "methods" : [ - - ], - "name" : "Address", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "street", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "city", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "zipCode", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - } - ], - "swiftCallName" : "Address" - }, - { - "methods" : [ - - ], - "name" : "Person", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "age", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "address", - "type" : { - "swiftStruct" : { - "_0" : "Address" - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "email", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "swiftCallName" : "Person" - }, - { - "methods" : [ - - ], - "name" : "Session", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "id", - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "owner", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - ], - "swiftCallName" : "Session" - }, - { - "methods" : [ - - ], - "name" : "Measurement", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "value", - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "precision", - "type" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "optionalPrecision", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - } - } - } - ], - "swiftCallName" : "Measurement" - }, - { - "methods" : [ - { - "abiName" : "bjs_ConfigStruct_static_update", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "update", - "parameters" : [ - { - "label" : "_", - "name" : "timeout", - "type" : { - "double" : { - - } - } - } - ], - "returnType" : { - "double" : { - - } - }, - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" - } - } - } - ], - "name" : "ConfigStruct", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : true, - "name" : "maxRetries", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" - } - }, - "type" : { - "int" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "defaultConfig", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" - } - }, - "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : false, - "isStatic" : true, - "name" : "timeout", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" - } - }, - "type" : { - "double" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : true, - "name" : "computedSetting", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" - } - }, - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "ConfigStruct" - } - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Throws.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Throws.json deleted file mode 100644 index ad47cbf0b..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/Throws.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_throwsSomething", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "throwsSomething", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.json deleted file mode 100644 index f38cd9440..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/UnsafePointer.json +++ /dev/null @@ -1,413 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_takeUnsafeRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeUnsafeRawPointer", - "parameters" : [ - { - "label" : "_", - "name" : "p", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_takeUnsafeMutableRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeUnsafeMutableRawPointer", - "parameters" : [ - { - "label" : "_", - "name" : "p", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_takeOpaquePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeOpaquePointer", - "parameters" : [ - { - "label" : "_", - "name" : "p", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_takeUnsafePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeUnsafePointer", - "parameters" : [ - { - "label" : "_", - "name" : "p", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_takeUnsafeMutablePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "takeUnsafeMutablePointer", - "parameters" : [ - { - "label" : "_", - "name" : "p", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - } - ], - "returnType" : { - "void" : { - - } - } - }, - { - "abiName" : "bjs_returnUnsafeRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "returnUnsafeRawPointer", - "parameters" : [ - - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "abiName" : "bjs_returnUnsafeMutableRawPointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "returnUnsafeMutableRawPointer", - "parameters" : [ - - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "abiName" : "bjs_returnOpaquePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "returnOpaquePointer", - "parameters" : [ - - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "abiName" : "bjs_returnUnsafePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "returnUnsafePointer", - "parameters" : [ - - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "abiName" : "bjs_returnUnsafeMutablePointer", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "returnUnsafeMutablePointer", - "parameters" : [ - - ], - "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "abiName" : "bjs_roundTripPointerFields", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripPointerFields", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "swiftStruct" : { - "_0" : "PointerFields" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "PointerFields" - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - { - "constructor" : { - "abiName" : "bjs_PointerFields_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "raw", - "name" : "raw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "label" : "mutRaw", - "name" : "mutRaw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "label" : "opaque", - "name" : "opaque", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "label" : "ptr", - "name" : "ptr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "label" : "mutPtr", - "name" : "mutPtr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "PointerFields", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "raw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "mutRaw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "opaque", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "ptr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "mutPtr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - } - ], - "swiftCallName" : "PointerFields" - } - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.json deleted file mode 100644 index b6b9c7bcb..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "classes" : [ - - ], - "enums" : [ - - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_check", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "check", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - } - ], - "protocols" : [ - - ], - "structs" : [ - - ] -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.swift deleted file mode 100644 index d5bc03b15..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ExportSwiftTests/VoidParameterVoidReturn.swift +++ /dev/null @@ -1,9 +0,0 @@ -@_expose(wasm, "bjs_check") -@_cdecl("bjs_check") -public func _bjs_check() -> Void { - #if arch(wasm32) - check() - #else - fatalError("Only available on WebAssembly") - #endif -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.Macros.swift deleted file mode 100644 index cf1118df0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.Macros.swift +++ /dev/null @@ -1,13 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func checkArray(_ a: JSObject) throws (JSException) -> Void - -@JSFunction func checkArrayWithLength(_ a: JSObject, _ b: Double) throws (JSException) -> Void - -@JSFunction func checkArray(_ a: JSObject) throws (JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.swift deleted file mode 100644 index 4e2cec8dc..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ArrayParameter.swift +++ /dev/null @@ -1,51 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkArray") -fileprivate func bjs_checkArray(_ a: Int32) -> Void -#else -fileprivate func bjs_checkArray(_ a: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkArray(_ a: JSObject) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - bjs_checkArray(aValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkArrayWithLength") -fileprivate func bjs_checkArrayWithLength(_ a: Int32, _ b: Float64) -> Void -#else -fileprivate func bjs_checkArrayWithLength(_ a: Int32, _ b: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkArrayWithLength(_ a: JSObject, _ b: Double) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - let bValue = b.bridgeJSLowerParameter() - bjs_checkArrayWithLength(aValue, bValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkArray") -fileprivate func bjs_checkArray(_ a: Int32) -> Void -#else -fileprivate func bjs_checkArray(_ a: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkArray(_ a: JSObject) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - bjs_checkArray(aValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.Macros.swift deleted file mode 100644 index dd0377377..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.Macros.swift +++ /dev/null @@ -1,21 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func asyncReturnVoid() throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripInt(_ v: Double) throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripString(_ v: String) throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripBool(_ v: Bool) throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripFloat(_ v: Double) throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripDouble(_ v: Double) throws (JSException) -> JSPromise - -@JSFunction func asyncRoundTripJSObject(_ v: JSObject) throws (JSException) -> JSPromise diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.swift deleted file mode 100644 index 1cc954b0d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Async.swift +++ /dev/null @@ -1,124 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncReturnVoid") -fileprivate func bjs_asyncReturnVoid() -> Int32 -#else -fileprivate func bjs_asyncReturnVoid() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncReturnVoid() throws(JSException) -> JSPromise { - let ret = bjs_asyncReturnVoid() - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripInt") -fileprivate func bjs_asyncRoundTripInt(_ v: Float64) -> Int32 -#else -fileprivate func bjs_asyncRoundTripInt(_ v: Float64) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripInt(_ v: Double) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripInt(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripString") -fileprivate func bjs_asyncRoundTripString(_ v: Int32) -> Int32 -#else -fileprivate func bjs_asyncRoundTripString(_ v: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripString(_ v: String) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripString(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripBool") -fileprivate func bjs_asyncRoundTripBool(_ v: Int32) -> Int32 -#else -fileprivate func bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripBool(_ v: Bool) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripBool(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripFloat") -fileprivate func bjs_asyncRoundTripFloat(_ v: Float64) -> Int32 -#else -fileprivate func bjs_asyncRoundTripFloat(_ v: Float64) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripFloat(_ v: Double) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripFloat(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripDouble") -fileprivate func bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 -#else -fileprivate func bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripDouble(_ v: Double) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripDouble(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_asyncRoundTripJSObject") -fileprivate func bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 -#else -fileprivate func bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$asyncRoundTripJSObject(_ v: JSObject) throws(JSException) -> JSPromise { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_asyncRoundTripJSObject(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSPromise.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.Macros.swift deleted file mode 100644 index 5d13234ca..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.Macros.swift +++ /dev/null @@ -1,14 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func returnAnimatable() throws (JSException) -> Animatable - -@JSClass struct Animatable { - @JSFunction func animate(_ keyframes: JSObject, _ options: JSObject) throws (JSException) -> JSObject - @JSFunction func getAnimations(_ options: JSObject) throws (JSException) -> JSObject -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.swift deleted file mode 100644 index fd16bd0d8..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/Interface.swift +++ /dev/null @@ -1,55 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_returnAnimatable") -fileprivate func bjs_returnAnimatable() -> Int32 -#else -fileprivate func bjs_returnAnimatable() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$returnAnimatable() throws(JSException) -> Animatable { - let ret = bjs_returnAnimatable() - if let error = _swift_js_take_exception() { - throw error - } - return Animatable.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Animatable_animate") -fileprivate func bjs_Animatable_animate(_ self: Int32, _ keyframes: Int32, _ options: Int32) -> Int32 -#else -fileprivate func bjs_Animatable_animate(_ self: Int32, _ keyframes: Int32, _ options: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Animatable_getAnimations") -fileprivate func bjs_Animatable_getAnimations(_ self: Int32, _ options: Int32) -> Int32 -#else -fileprivate func bjs_Animatable_getAnimations(_ self: Int32, _ options: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$Animatable_animate(_ self: JSObject, _ keyframes: JSObject, _ options: JSObject) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() - let keyframesValue = keyframes.bridgeJSLowerParameter() - let optionsValue = options.bridgeJSLowerParameter() - let ret = bjs_Animatable_animate(selfValue, keyframesValue, optionsValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -func _$Animatable_getAnimations(_ self: JSObject, _ options: JSObject) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() - let optionsValue = options.bridgeJSLowerParameter() - let ret = bjs_Animatable_getAnimations(selfValue, optionsValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.Macros.swift deleted file mode 100644 index 43d6a3eb9..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.Macros.swift +++ /dev/null @@ -1,44 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func createArrayBuffer() throws (JSException) -> ArrayBufferLike - -@JSClass struct ArrayBufferLike { - @JSGetter var byteLength: Double - @JSFunction func slice(_ begin: Double, _ end: Double) throws (JSException) -> ArrayBufferLike -} - -@JSFunction func createWeirdObject() throws (JSException) -> WeirdNaming - -@JSClass struct WeirdNaming { - @JSGetter var normalProperty: String - @JSSetter func setNormalProperty(_ value: String) throws (JSException) - @JSGetter(jsName: "property-with-dashes") var property_with_dashes: Double - @JSSetter(jsName: "property-with-dashes") func setProperty_with_dashes(_ value: Double) throws (JSException) - @JSGetter(jsName: "123invalidStart") var _123invalidStart: Bool - @JSSetter(jsName: "123invalidStart") func set_123invalidStart(_ value: Bool) throws (JSException) - @JSGetter(jsName: "property with spaces") var property_with_spaces: String - @JSSetter(jsName: "property with spaces") func setProperty_with_spaces(_ value: String) throws (JSException) - @JSGetter(jsName: "@specialChar") var _specialChar: Double - @JSSetter(jsName: "@specialChar") func set_specialChar(_ value: Double) throws (JSException) - @JSGetter var constructor: String - @JSSetter func setConstructor(_ value: String) throws (JSException) - @JSGetter var `for`: String - @JSSetter func setFor(_ value: String) throws (JSException) - @JSGetter var `Any`: String - @JSSetter(jsName: "Any") func setAny(_ value: String) throws (JSException) - @JSFunction func `as`() throws (JSException) -> Void - @JSFunction func `try`() throws (JSException) -> Void -} - -@JSClass(jsName: "$Weird") struct _Weird { - @JSFunction init() throws (JSException) - @JSFunction(jsName: "method-with-dashes") func method_with_dashes() throws (JSException) -> Void -} - -@JSFunction func createWeirdClass() throws (JSException) -> _Weird diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.swift deleted file mode 100644 index 0ef52d4d7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/InvalidPropertyNames.swift +++ /dev/null @@ -1,444 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createArrayBuffer") -fileprivate func bjs_createArrayBuffer() -> Int32 -#else -fileprivate func bjs_createArrayBuffer() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createArrayBuffer() throws(JSException) -> ArrayBufferLike { - let ret = bjs_createArrayBuffer() - if let error = _swift_js_take_exception() { - throw error - } - return ArrayBufferLike.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createWeirdObject") -fileprivate func bjs_createWeirdObject() -> Int32 -#else -fileprivate func bjs_createWeirdObject() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createWeirdObject() throws(JSException) -> WeirdNaming { - let ret = bjs_createWeirdObject() - if let error = _swift_js_take_exception() { - throw error - } - return WeirdNaming.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createWeirdClass") -fileprivate func bjs_createWeirdClass() -> Int32 -#else -fileprivate func bjs_createWeirdClass() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createWeirdClass() throws(JSException) -> _Weird { - let ret = bjs_createWeirdClass() - if let error = _swift_js_take_exception() { - throw error - } - return _Weird.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_ArrayBufferLike_byteLength_get") -fileprivate func bjs_ArrayBufferLike_byteLength_get(_ self: Int32) -> Float64 -#else -fileprivate func bjs_ArrayBufferLike_byteLength_get(_ self: Int32) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_ArrayBufferLike_slice") -fileprivate func bjs_ArrayBufferLike_slice(_ self: Int32, _ begin: Float64, _ end: Float64) -> Int32 -#else -fileprivate func bjs_ArrayBufferLike_slice(_ self: Int32, _ begin: Float64, _ end: Float64) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$ArrayBufferLike_byteLength_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_ArrayBufferLike_byteLength_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -func _$ArrayBufferLike_slice(_ self: JSObject, _ begin: Double, _ end: Double) throws(JSException) -> ArrayBufferLike { - let selfValue = self.bridgeJSLowerParameter() - let beginValue = begin.bridgeJSLowerParameter() - let endValue = end.bridgeJSLowerParameter() - let ret = bjs_ArrayBufferLike_slice(selfValue, beginValue, endValue) - if let error = _swift_js_take_exception() { - throw error - } - return ArrayBufferLike.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_normalProperty_get") -fileprivate func bjs_WeirdNaming_normalProperty_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming_normalProperty_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_property_with_dashes_get") -fileprivate func bjs_WeirdNaming_property_with_dashes_get(_ self: Int32) -> Float64 -#else -fileprivate func bjs_WeirdNaming_property_with_dashes_get(_ self: Int32) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming__123invalidStart_get") -fileprivate func bjs_WeirdNaming__123invalidStart_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming__123invalidStart_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_property_with_spaces_get") -fileprivate func bjs_WeirdNaming_property_with_spaces_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming_property_with_spaces_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming__specialChar_get") -fileprivate func bjs_WeirdNaming__specialChar_get(_ self: Int32) -> Float64 -#else -fileprivate func bjs_WeirdNaming__specialChar_get(_ self: Int32) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_constructor_get") -fileprivate func bjs_WeirdNaming_constructor_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming_constructor_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_for_get") -fileprivate func bjs_WeirdNaming_for_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming_for_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_Any_get") -fileprivate func bjs_WeirdNaming_Any_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_WeirdNaming_Any_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_normalProperty_set") -fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_normalProperty_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_property_with_dashes_set") -fileprivate func bjs_WeirdNaming_property_with_dashes_set(_ self: Int32, _ newValue: Float64) -> Void -#else -fileprivate func bjs_WeirdNaming_property_with_dashes_set(_ self: Int32, _ newValue: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming__123invalidStart_set") -fileprivate func bjs_WeirdNaming__123invalidStart_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming__123invalidStart_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_property_with_spaces_set") -fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_property_with_spaces_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming__specialChar_set") -fileprivate func bjs_WeirdNaming__specialChar_set(_ self: Int32, _ newValue: Float64) -> Void -#else -fileprivate func bjs_WeirdNaming__specialChar_set(_ self: Int32, _ newValue: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_constructor_set") -fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_constructor_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_for_set") -fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_for_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_any_set") -fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_any_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_as") -fileprivate func bjs_WeirdNaming_as(_ self: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_as(_ self: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_WeirdNaming_try") -fileprivate func bjs_WeirdNaming_try(_ self: Int32) -> Void -#else -fileprivate func bjs_WeirdNaming_try(_ self: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$WeirdNaming_normalProperty_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_normalProperty_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_property_with_dashes_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_property_with_dashes_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming__123invalidStart_get(_ self: JSObject) throws(JSException) -> Bool { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming__123invalidStart_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_property_with_spaces_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_property_with_spaces_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming__specialChar_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming__specialChar_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_constructor_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_constructor_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_for_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_for_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_Any_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_WeirdNaming_Any_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_normalProperty_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_property_with_dashes_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_property_with_dashes_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming__123invalidStart_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming__123invalidStart_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_property_with_spaces_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming__specialChar_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_constructor_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_for_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_any_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_WeirdNaming_any_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_as(_ self: JSObject) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_as(selfValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$WeirdNaming_try(_ self: JSObject) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - bjs_WeirdNaming_try(selfValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs__Weird_init") -fileprivate func bjs__Weird_init() -> Int32 -#else -fileprivate func bjs__Weird_init() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs__Weird_method_with_dashes") -fileprivate func bjs__Weird_method_with_dashes(_ self: Int32) -> Void -#else -fileprivate func bjs__Weird_method_with_dashes(_ self: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$_Weird_init() throws(JSException) -> JSObject { - let ret = bjs__Weird_init() - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -func _$_Weird_method_with_dashes(_ self: JSObject) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - bjs__Weird_method_with_dashes(selfValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.Macros.swift deleted file mode 100644 index 47efcbc84..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.Macros.swift +++ /dev/null @@ -1,33 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func createDatabaseConnection(_ config: JSObject) throws (JSException) -> DatabaseConnection - -@JSClass struct DatabaseConnection { - @JSFunction func connect(_ url: String) throws (JSException) -> Void - @JSFunction func execute(_ query: String) throws (JSException) -> JSObject - @JSGetter var isConnected: Bool - @JSGetter var connectionTimeout: Double - @JSSetter func setConnectionTimeout(_ value: Double) throws (JSException) -} - -@JSFunction func createLogger(_ level: String) throws (JSException) -> Logger - -@JSClass struct Logger { - @JSFunction func log(_ message: String) throws (JSException) -> Void - @JSFunction func error(_ message: String, _ error: JSObject) throws (JSException) -> Void - @JSGetter var level: String -} - -@JSFunction func getConfigManager() throws (JSException) -> ConfigManager - -@JSClass struct ConfigManager { - @JSFunction func get(_ key: String) throws (JSException) -> JSObject - @JSFunction func set(_ key: String, _ value: JSObject) throws (JSException) -> Void - @JSGetter var configPath: String -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.swift deleted file mode 100644 index 1c1418af8..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/MultipleImportedTypes.swift +++ /dev/null @@ -1,254 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createDatabaseConnection") -fileprivate func bjs_createDatabaseConnection(_ config: Int32) -> Int32 -#else -fileprivate func bjs_createDatabaseConnection(_ config: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createDatabaseConnection(_ config: JSObject) throws(JSException) -> DatabaseConnection { - let configValue = config.bridgeJSLowerParameter() - let ret = bjs_createDatabaseConnection(configValue) - if let error = _swift_js_take_exception() { - throw error - } - return DatabaseConnection.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createLogger") -fileprivate func bjs_createLogger(_ level: Int32) -> Int32 -#else -fileprivate func bjs_createLogger(_ level: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createLogger(_ level: String) throws(JSException) -> Logger { - let levelValue = level.bridgeJSLowerParameter() - let ret = bjs_createLogger(levelValue) - if let error = _swift_js_take_exception() { - throw error - } - return Logger.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_getConfigManager") -fileprivate func bjs_getConfigManager() -> Int32 -#else -fileprivate func bjs_getConfigManager() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$getConfigManager() throws(JSException) -> ConfigManager { - let ret = bjs_getConfigManager() - if let error = _swift_js_take_exception() { - throw error - } - return ConfigManager.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_DatabaseConnection_isConnected_get") -fileprivate func bjs_DatabaseConnection_isConnected_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_DatabaseConnection_isConnected_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_DatabaseConnection_connectionTimeout_get") -fileprivate func bjs_DatabaseConnection_connectionTimeout_get(_ self: Int32) -> Float64 -#else -fileprivate func bjs_DatabaseConnection_connectionTimeout_get(_ self: Int32) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_DatabaseConnection_connectionTimeout_set") -fileprivate func bjs_DatabaseConnection_connectionTimeout_set(_ self: Int32, _ newValue: Float64) -> Void -#else -fileprivate func bjs_DatabaseConnection_connectionTimeout_set(_ self: Int32, _ newValue: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_DatabaseConnection_connect") -fileprivate func bjs_DatabaseConnection_connect(_ self: Int32, _ url: Int32) -> Void -#else -fileprivate func bjs_DatabaseConnection_connect(_ self: Int32, _ url: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_DatabaseConnection_execute") -fileprivate func bjs_DatabaseConnection_execute(_ self: Int32, _ query: Int32) -> Int32 -#else -fileprivate func bjs_DatabaseConnection_execute(_ self: Int32, _ query: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$DatabaseConnection_isConnected_get(_ self: JSObject) throws(JSException) -> Bool { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_DatabaseConnection_isConnected_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) -} - -func _$DatabaseConnection_connectionTimeout_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_DatabaseConnection_connectionTimeout_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -func _$DatabaseConnection_connectionTimeout_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_DatabaseConnection_connectionTimeout_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$DatabaseConnection_connect(_ self: JSObject, _ url: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let urlValue = url.bridgeJSLowerParameter() - bjs_DatabaseConnection_connect(selfValue, urlValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$DatabaseConnection_execute(_ self: JSObject, _ query: String) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() - let queryValue = query.bridgeJSLowerParameter() - let ret = bjs_DatabaseConnection_execute(selfValue, queryValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Logger_level_get") -fileprivate func bjs_Logger_level_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_Logger_level_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Logger_log") -fileprivate func bjs_Logger_log(_ self: Int32, _ message: Int32) -> Void -#else -fileprivate func bjs_Logger_log(_ self: Int32, _ message: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Logger_error") -fileprivate func bjs_Logger_error(_ self: Int32, _ message: Int32, _ error: Int32) -> Void -#else -fileprivate func bjs_Logger_error(_ self: Int32, _ message: Int32, _ error: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$Logger_level_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Logger_level_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$Logger_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let messageValue = message.bridgeJSLowerParameter() - bjs_Logger_log(selfValue, messageValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$Logger_error(_ self: JSObject, _ message: String, _ error: JSObject) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let messageValue = message.bridgeJSLowerParameter() - let errorValue = error.bridgeJSLowerParameter() - bjs_Logger_error(selfValue, messageValue, errorValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_ConfigManager_configPath_get") -fileprivate func bjs_ConfigManager_configPath_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_ConfigManager_configPath_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_ConfigManager_get") -fileprivate func bjs_ConfigManager_get(_ self: Int32, _ key: Int32) -> Int32 -#else -fileprivate func bjs_ConfigManager_get(_ self: Int32, _ key: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_ConfigManager_set") -fileprivate func bjs_ConfigManager_set(_ self: Int32, _ key: Int32, _ value: Int32) -> Void -#else -fileprivate func bjs_ConfigManager_set(_ self: Int32, _ key: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$ConfigManager_configPath_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_ConfigManager_configPath_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$ConfigManager_get(_ self: JSObject, _ key: String) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() - let keyValue = key.bridgeJSLowerParameter() - let ret = bjs_ConfigManager_get(selfValue, keyValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -func _$ConfigManager_set(_ self: JSObject, _ key: String, _ value: JSObject) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let keyValue = key.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - bjs_ConfigManager_set(selfValue, keyValue, valueValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.Macros.swift deleted file mode 100644 index eea42f30d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.Macros.swift +++ /dev/null @@ -1,9 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func check(_ a: Double, _ b: Bool) throws (JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.swift deleted file mode 100644 index 6d59ca52f..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveParameters.swift +++ /dev/null @@ -1,17 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_check") -fileprivate func bjs_check(_ a: Float64, _ b: Int32) -> Void -#else -fileprivate func bjs_check(_ a: Float64, _ b: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$check(_ a: Double, _ b: Bool) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - let bValue = b.bridgeJSLowerParameter() - bjs_check(aValue, bValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.Macros.swift deleted file mode 100644 index 15867131d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.Macros.swift +++ /dev/null @@ -1,11 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func checkNumber() throws (JSException) -> Double - -@JSFunction func checkBoolean() throws (JSException) -> Bool diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.swift deleted file mode 100644 index 17f536ba5..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/PrimitiveReturn.swift +++ /dev/null @@ -1,33 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkNumber") -fileprivate func bjs_checkNumber() -> Float64 -#else -fileprivate func bjs_checkNumber() -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkNumber() throws(JSException) -> Double { - let ret = bjs_checkNumber() - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkBoolean") -fileprivate func bjs_checkBoolean() -> Int32 -#else -fileprivate func bjs_checkBoolean() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkBoolean() throws(JSException) -> Bool { - let ret = bjs_checkBoolean() - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.Macros.swift deleted file mode 100644 index 0c0dfb362..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.Macros.swift +++ /dev/null @@ -1,14 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func jsRoundTripNumber(_ v: Double) throws (JSException) -> Double - -@JSClass struct JsGreeter { - @JSFunction init(_ name: String) throws (JSException) - @JSFunction func greet() throws (JSException) -> String -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.swift deleted file mode 100644 index 01c2b1e6e..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/ReExportFrom.swift +++ /dev/null @@ -1,53 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_jsRoundTripNumber") -fileprivate func bjs_jsRoundTripNumber(_ v: Float64) -> Float64 -#else -fileprivate func bjs_jsRoundTripNumber(_ v: Float64) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$jsRoundTripNumber(_ v: Double) throws(JSException) -> Double { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripNumber(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_JsGreeter_init") -fileprivate func bjs_JsGreeter_init(_ name: Int32) -> Int32 -#else -fileprivate func bjs_JsGreeter_init(_ name: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_JsGreeter_greet") -fileprivate func bjs_JsGreeter_greet(_ self: Int32) -> Int32 -#else -fileprivate func bjs_JsGreeter_greet(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$JsGreeter_init(_ name: String) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_init(nameValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_greet(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.Macros.swift deleted file mode 100644 index b0049af28..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.Macros.swift +++ /dev/null @@ -1,17 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -enum FeatureFlag: String { - case foo = "foo" - case bar = "bar" -} -extension FeatureFlag: _BridgedSwiftEnumNoPayload {} - -@JSFunction func takesFeatureFlag(_ flag: FeatureFlag) throws (JSException) -> Void - -@JSFunction func returnsFeatureFlag() throws (JSException) -> FeatureFlag diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.swift deleted file mode 100644 index 3059865ac..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringEnum.swift +++ /dev/null @@ -1,33 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_takesFeatureFlag") -fileprivate func bjs_takesFeatureFlag(_ flag: Int32) -> Void -#else -fileprivate func bjs_takesFeatureFlag(_ flag: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$takesFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> Void { - let flagValue = flag.bridgeJSLowerParameter() - bjs_takesFeatureFlag(flagValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_returnsFeatureFlag") -fileprivate func bjs_returnsFeatureFlag() -> Int32 -#else -fileprivate func bjs_returnsFeatureFlag() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$returnsFeatureFlag() throws(JSException) -> FeatureFlag { - let ret = bjs_returnsFeatureFlag() - if let error = _swift_js_take_exception() { - throw error - } - return FeatureFlag.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.Macros.swift deleted file mode 100644 index 38fe0dd2b..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.Macros.swift +++ /dev/null @@ -1,11 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func checkString(_ a: String) throws (JSException) -> Void - -@JSFunction func checkStringWithLength(_ a: String, _ b: Double) throws (JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.swift deleted file mode 100644 index 694c44e06..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringParameter.swift +++ /dev/null @@ -1,34 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkString") -fileprivate func bjs_checkString(_ a: Int32) -> Void -#else -fileprivate func bjs_checkString(_ a: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkString(_ a: String) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - bjs_checkString(aValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkStringWithLength") -fileprivate func bjs_checkStringWithLength(_ a: Int32, _ b: Float64) -> Void -#else -fileprivate func bjs_checkStringWithLength(_ a: Int32, _ b: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkStringWithLength(_ a: String, _ b: Double) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - let bValue = b.bridgeJSLowerParameter() - bjs_checkStringWithLength(aValue, bValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.Macros.swift deleted file mode 100644 index 60aae03c4..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.Macros.swift +++ /dev/null @@ -1,9 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func checkString() throws (JSException) -> String diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.swift deleted file mode 100644 index bde90ea74..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/StringReturn.swift +++ /dev/null @@ -1,16 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkString") -fileprivate func bjs_checkString() -> Int32 -#else -fileprivate func bjs_checkString() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkString() throws(JSException) -> String { - let ret = bjs_checkString() - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftClosureImports.ImportMacros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftClosureImports.ImportMacros.swift deleted file mode 100644 index 9e0959157..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftClosureImports.ImportMacros.swift +++ /dev/null @@ -1,84 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_Check_5CheckSi_Si") -fileprivate func invoke_js_callback_Check_5CheckSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_Check_5CheckSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -private final class _BJS_ClosureBox_5CheckSi_Si: _BridgedSwiftClosureBox { - let closure: (Int) -> Int - init(_ closure: @escaping (Int) -> Int) { - self.closure = closure - } -} - -private enum _BJS_Closure_5CheckSi_Si { - static func bridgeJSLower(_ closure: @escaping (Int) -> Int) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_5CheckSi_Si(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Int { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_Check_5CheckSi_Si(callbackValue, param0Value) - return Int.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -@_expose(wasm, "invoke_swift_closure_Check_5CheckSi_Si") -@_cdecl("invoke_swift_closure_Check_5CheckSi_Si") -public func _invoke_swift_closure_Check_5CheckSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { - #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_5CheckSi_Si>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Int.bridgeJSLiftParameter(param0)) - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_applyInt") -fileprivate func bjs_applyInt(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func bjs_applyInt(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$applyInt(_ value: Int, _ transform: @escaping (Int) -> Int) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() - let transformPointer = _BJS_Closure_5CheckSi_Si.bridgeJSLower(transform) - let ret = bjs_applyInt(valueValue, transformPointer) - if let error = _swift_js_take_exception() { - throw error - } - return Int.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_makeAdder") -fileprivate func bjs_makeAdder(_ base: Int32) -> Int32 -#else -fileprivate func bjs_makeAdder(_ base: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$makeAdder(_ base: Int) throws(JSException) -> (Int) -> Int { - let baseValue = base.bridgeJSLowerParameter() - let ret = bjs_makeAdder(baseValue) - if let error = _swift_js_take_exception() { - throw error - } - return _BJS_Closure_5CheckSi_Si.bridgeJSLift(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftStructImports.ImportMacros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftStructImports.ImportMacros.swift deleted file mode 100644 index 54470e5de..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/SwiftStructImports.ImportMacros.swift +++ /dev/null @@ -1,19 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_translate") -fileprivate func bjs_translate(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 -#else -fileprivate func bjs_translate(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { - let pointObjectId = point.bridgeJSLowerParameter() - let dxValue = dx.bridgeJSLowerParameter() - let dyValue = dy.bridgeJSLowerParameter() - let ret = bjs_translate(pointObjectId, dxValue, dyValue) - if let error = _swift_js_take_exception() { - throw error - } - return Point.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.Macros.swift deleted file mode 100644 index e0d6c9d24..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.Macros.swift +++ /dev/null @@ -1,22 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func createTS2Skeleton() throws (JSException) -> TypeScriptProcessor - -@JSClass struct TypeScriptProcessor { - @JSFunction func convert(_ ts: String) throws (JSException) -> String - @JSFunction func validate(_ ts: String) throws (JSException) -> Bool - @JSGetter var version: String -} - -@JSFunction func createCodeGenerator(_ format: String) throws (JSException) -> CodeGenerator - -@JSClass struct CodeGenerator { - @JSFunction func generate(_ input: JSObject) throws (JSException) -> String - @JSGetter var outputFormat: String -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.swift deleted file mode 100644 index 54d3b9156..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TS2SkeletonLike.swift +++ /dev/null @@ -1,127 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createTS2Skeleton") -fileprivate func bjs_createTS2Skeleton() -> Int32 -#else -fileprivate func bjs_createTS2Skeleton() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createTS2Skeleton() throws(JSException) -> TypeScriptProcessor { - let ret = bjs_createTS2Skeleton() - if let error = _swift_js_take_exception() { - throw error - } - return TypeScriptProcessor.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_createCodeGenerator") -fileprivate func bjs_createCodeGenerator(_ format: Int32) -> Int32 -#else -fileprivate func bjs_createCodeGenerator(_ format: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$createCodeGenerator(_ format: String) throws(JSException) -> CodeGenerator { - let formatValue = format.bridgeJSLowerParameter() - let ret = bjs_createCodeGenerator(formatValue) - if let error = _swift_js_take_exception() { - throw error - } - return CodeGenerator.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_TypeScriptProcessor_version_get") -fileprivate func bjs_TypeScriptProcessor_version_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_TypeScriptProcessor_version_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_TypeScriptProcessor_convert") -fileprivate func bjs_TypeScriptProcessor_convert(_ self: Int32, _ ts: Int32) -> Int32 -#else -fileprivate func bjs_TypeScriptProcessor_convert(_ self: Int32, _ ts: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_TypeScriptProcessor_validate") -fileprivate func bjs_TypeScriptProcessor_validate(_ self: Int32, _ ts: Int32) -> Int32 -#else -fileprivate func bjs_TypeScriptProcessor_validate(_ self: Int32, _ ts: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$TypeScriptProcessor_version_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_TypeScriptProcessor_version_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$TypeScriptProcessor_convert(_ self: JSObject, _ ts: String) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let tsValue = ts.bridgeJSLowerParameter() - let ret = bjs_TypeScriptProcessor_convert(selfValue, tsValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$TypeScriptProcessor_validate(_ self: JSObject, _ ts: String) throws(JSException) -> Bool { - let selfValue = self.bridgeJSLowerParameter() - let tsValue = ts.bridgeJSLowerParameter() - let ret = bjs_TypeScriptProcessor_validate(selfValue, tsValue) - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_CodeGenerator_outputFormat_get") -fileprivate func bjs_CodeGenerator_outputFormat_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_CodeGenerator_outputFormat_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_CodeGenerator_generate") -fileprivate func bjs_CodeGenerator_generate(_ self: Int32, _ input: Int32) -> Int32 -#else -fileprivate func bjs_CodeGenerator_generate(_ self: Int32, _ input: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -func _$CodeGenerator_outputFormat_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_CodeGenerator_outputFormat_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$CodeGenerator_generate(_ self: JSObject, _ input: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let inputValue = input.bridgeJSLowerParameter() - let ret = bjs_CodeGenerator_generate(selfValue, inputValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.Macros.swift deleted file mode 100644 index 62b2b4663..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.Macros.swift +++ /dev/null @@ -1,9 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func checkSimple(_ a: Double) throws (JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.swift deleted file mode 100644 index 0b5d0c40d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeAlias.swift +++ /dev/null @@ -1,16 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_checkSimple") -fileprivate func bjs_checkSimple(_ a: Float64) -> Void -#else -fileprivate func bjs_checkSimple(_ a: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$checkSimple(_ a: Double) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() - bjs_checkSimple(aValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.Macros.swift deleted file mode 100644 index 1fbf3376d..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.Macros.swift +++ /dev/null @@ -1,16 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSClass struct Greeter { - @JSGetter var name: String - @JSSetter func setName(_ value: String) throws (JSException) - @JSGetter var age: Double - @JSFunction init(_ name: String) throws (JSException) - @JSFunction func greet() throws (JSException) -> String - @JSFunction func changeName(_ name: String) throws (JSException) -> Void -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.swift deleted file mode 100644 index 67c778975..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/TypeScriptClass.swift +++ /dev/null @@ -1,107 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_init") -fileprivate func bjs_Greeter_init(_ name: Int32) -> Int32 -#else -fileprivate func bjs_Greeter_init(_ name: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_name_get") -fileprivate func bjs_Greeter_name_get(_ self: Int32) -> Int32 -#else -fileprivate func bjs_Greeter_name_get(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_age_get") -fileprivate func bjs_Greeter_age_get(_ self: Int32) -> Float64 -#else -fileprivate func bjs_Greeter_age_get(_ self: Int32) -> Float64 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_name_set") -fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_Greeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_greet") -fileprivate func bjs_Greeter_greet(_ self: Int32) -> Int32 -#else -fileprivate func bjs_Greeter_greet(_ self: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif - -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_Greeter_changeName") -fileprivate func bjs_Greeter_changeName(_ self: Int32, _ name: Int32) -> Void -#else -fileprivate func bjs_Greeter_changeName(_ self: Int32, _ name: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$Greeter_init(_ name: String) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let ret = bjs_Greeter_init(nameValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) -} - -func _$Greeter_name_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Greeter_name_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$Greeter_age_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Greeter_age_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) -} - -func _$Greeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Greeter_name_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } -} - -func _$Greeter_greet(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Greeter_greet(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) -} - -func _$Greeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let nameValue = name.bridgeJSLowerParameter() - bjs_Greeter_changeName(selfValue, nameValue) - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.Macros.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.Macros.swift deleted file mode 100644 index b3a7fc6f6..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.Macros.swift +++ /dev/null @@ -1,9 +0,0 @@ -// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, -// DO NOT EDIT. -// -// To update this file, just rebuild your project or run -// `swift package bridge-js`. - -@_spi(Experimental) import JavaScriptKit - -@JSFunction func check() throws (JSException) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.swift deleted file mode 100644 index 2a2622ce0..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/ImportTSTests/VoidParameterVoidReturn.swift +++ /dev/null @@ -1,15 +0,0 @@ -#if arch(wasm32) -@_extern(wasm, module: "Check", name: "bjs_check") -fileprivate func bjs_check() -> Void -#else -fileprivate func bjs_check() -> Void { - fatalError("Only available on WebAssembly") -} -#endif - -func _$check() throws(JSException) -> Void { - bjs_check() - if let error = _swift_js_take_exception() { - throw error - } -} \ No newline at end of file diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index 268f3f200..3e22736be 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -422,7 +422,10 @@ struct PackagingPlanner { wasmFilename: String, configuration: String, triple: String, - selfPath: BuildPath = BuildPath(absolute: #filePath), + // NOTE: We should use `ProcessInfo.processInfo.arguments[0]` instead of `CommandLine.arguments[0]` + // because the latter may not always be the full executable path (e.g. when invoked through PATH lookup). + // https://github.com/swiftlang/swift-foundation/blob/f5143f96d01cdb6d280665de8221b75fc8631d95/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift#L47 + selfPath: BuildPath = BuildPath(absolute: ProcessInfo.processInfo.arguments[0]), system: any PackagingSystem ) { self.options = options @@ -589,15 +592,10 @@ struct PackagingPlanner { packageInputs.append(packageJsonTask) if skeletons.count > 0 { - if ProcessInfo.processInfo.environment["JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS"] == nil { - fatalError( - "BridgeJS is still an experimental feature. Set the environment variable JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 to enable." - ) - } let bridgeJs = outputDir.appending(path: "bridge-js.js") let bridgeDts = outputDir.appending(path: "bridge-js.d.ts") packageInputs.append( - make.addTask(inputFiles: skeletons, output: bridgeJs) { _, scope in + make.addTask(inputFiles: skeletons + [selfPath], output: bridgeJs) { _, scope in var link = BridgeJSLink( sharedMemory: Self.isSharedMemoryEnabled(triple: triple) ) diff --git a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift index 3cbd29014..7e335c68e 100644 --- a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift +++ b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift @@ -751,9 +751,9 @@ class SkeletonCollector { let directories = [ target.directoryURL.appending(path: "Generated/JavaScript"), // context.pluginWorkDirectoryURL: ".build/plugins/PackageToJS/outputs/" - // .build/plugins/outputs/exportswift/MyApp/destination/BridgeJS/BridgeJS.ExportSwift.json + // .build/plugins/outputs/[package]/[target]/destination/BridgeJS/JavaScript/BridgeJS.json context.pluginWorkDirectoryURL.deletingLastPathComponent().deletingLastPathComponent() - .appending(path: "outputs/\(package.id)/\(target.name)/destination/BridgeJS"), + .appending(path: "outputs/\(package.id)/\(target.name)/destination/BridgeJS/JavaScript"), ] for directory in directories { let skeletonURL = directory.appending(path: skeletonFile) diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 54a7212c6..fd183583b 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -1,21 +1,21 @@ // @ts-check -import { SwiftRuntime } from "./runtime.js" +import { SwiftRuntime } from "./runtime.js"; export const MODULE_PATH = "@PACKAGE_TO_JS_MODULE_PATH@"; /* #if USE_SHARED_MEMORY */ export const MEMORY_TYPE = { - // @ts-ignore + // @ts-expect-error Substituted by PackageToJS preprocessor initial: import.meta.PACKAGE_TO_JS_MEMORY_INITIAL, - // @ts-ignore + // @ts-expect-error Substituted by PackageToJS preprocessor maximum: import.meta.PACKAGE_TO_JS_MEMORY_MAXIMUM, - // @ts-ignore + // @ts-expect-error Substituted by PackageToJS preprocessor shared: import.meta.PACKAGE_TO_JS_MEMORY_SHARED, -} +}; /* #endif */ /* #if HAS_BRIDGE */ -// @ts-ignore -import { createInstantiator } from "./bridge-js.js" +// @ts-expect-error Substituted by PackageToJS preprocessor +import { createInstantiator } from "./bridge-js.js"; /* #else */ /** * @param {import('./instantiate.d').InstantiateOptions} options @@ -30,7 +30,9 @@ async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { // Provide a default implementation for BridgeJS functions that are not // used at runtime without BridgeJS but required to instantiate the module. - const unexpectedBjsCall = () => { throw new Error("Unexpected call to BridgeJS function") } + const unexpectedBjsCall = () => { + throw new Error("Unexpected call to BridgeJS function"); + }; importObject["bjs"] = { swift_js_return_string: unexpectedBjsCall, swift_js_init_memory: unexpectedBjsCall, @@ -39,7 +41,6 @@ async function createInstantiator(options, swift) { swift_js_throw: unexpectedBjsCall, swift_js_retain: unexpectedBjsCall, swift_js_release: unexpectedBjsCall, - swift_js_push_tag: unexpectedBjsCall, swift_js_push_i32: unexpectedBjsCall, swift_js_push_f32: unexpectedBjsCall, swift_js_push_f64: unexpectedBjsCall, @@ -62,7 +63,10 @@ async function createInstantiator(options, swift) { swift_js_get_optional_double_presence: unexpectedBjsCall, swift_js_get_optional_double_value: unexpectedBjsCall, swift_js_get_optional_heap_object_pointer: unexpectedBjsCall, - } + swift_js_push_pointer: unexpectedBjsCall, + swift_js_pop_pointer: unexpectedBjsCall, + swift_js_closure_unregister: unexpectedBjsCall, + }; }, /** @param {WebAssembly.Instance} instance */ setInstance: (instance) => {}, @@ -70,67 +74,65 @@ async function createInstantiator(options, swift) { createExports: (instance) => { return {}; }, - } + }; } /* #endif */ /** @type {import('./instantiate.d').instantiate} */ -export async function instantiate( - options -) { +export async function instantiate(options) { const result = await _instantiate(options); -/* #if IS_WASI */ + /* #if IS_WASI */ options.wasi.initialize(result.instance); -/* #endif */ + /* #endif */ result.swift.main(); return result; } /** @type {import('./instantiate.d').instantiateForThread} */ -export async function instantiateForThread( - tid, startArg, options -) { +export async function instantiateForThread(tid, startArg, options) { const result = await _instantiate(options); -/* #if IS_WASI */ + /* #if IS_WASI */ options.wasi.setInstance(result.instance); -/* #endif */ - result.swift.startThread(tid, startArg) + /* #endif */ + result.swift.startThread(tid, startArg); return result; } /** @type {import('./instantiate.d').instantiate} */ -async function _instantiate( - options -) { +async function _instantiate(options) { const _WebAssembly = options.WebAssembly || WebAssembly; const moduleSource = options.module; -/* #if IS_WASI */ + /* #if IS_WASI */ const { wasi } = options; -/* #endif */ + /* #endif */ const swift = new SwiftRuntime({ -/* #if USE_SHARED_MEMORY */ + /* #if USE_SHARED_MEMORY */ sharedMemory: true, threadChannel: options.threadChannel, -/* #endif */ + /* #endif */ }); const instantiator = await createInstantiator(options, swift); /** @type {WebAssembly.Imports} */ const importObject = { javascript_kit: swift.wasmImports, -/* #if IS_WASI */ + /* #if IS_WASI */ wasi_snapshot_preview1: wasi.wasiImport, -/* #if USE_SHARED_MEMORY */ + /* #if USE_SHARED_MEMORY */ env: { memory: options.memory, }, wasi: { "thread-spawn": (startArg) => { - return options.threadChannel.spawnThread(module, options.memory, startArg); - } - } -/* #endif */ -/* #endif */ + return options.threadChannel.spawnThread( + module, + options.memory, + startArg, + ); + }, + }, + /* #endif */ + /* #endif */ }; const importsContext = { getInstance: () => instance, @@ -146,9 +148,15 @@ async function _instantiate( if (moduleSource instanceof _WebAssembly.Module) { module = moduleSource; instance = await _WebAssembly.instantiate(module, importObject); - } else if (typeof Response === "function" && (moduleSource instanceof Response || moduleSource instanceof Promise)) { + } else if ( + typeof Response === "function" && + (moduleSource instanceof Response || moduleSource instanceof Promise) + ) { if (typeof _WebAssembly.instantiateStreaming === "function") { - const result = await _WebAssembly.instantiateStreaming(moduleSource, importObject); + const result = await _WebAssembly.instantiateStreaming( + moduleSource, + importObject, + ); module = result.module; instance = result.instance; } else { @@ -161,7 +169,8 @@ async function _instantiate( module = await _WebAssembly.compile(moduleSource); instance = await _WebAssembly.instantiate(module, importObject); } - instance = options.instrumentInstance?.(instance, { _swift: swift }) ?? instance; + instance = + options.instrumentInstance?.(instance, { _swift: swift }) ?? instance; swift.setInstance(instance); instantiator.setInstance(instance); @@ -171,5 +180,5 @@ async function _instantiate( instance, swift, exports, - } + }; } diff --git a/Plugins/PackageToJS/Templates/runtime.mjs b/Plugins/PackageToJS/Templates/runtime.mjs index a40fc3df6..d79275476 100644 --- a/Plugins/PackageToJS/Templates/runtime.mjs +++ b/Plugins/PackageToJS/Templates/runtime.mjs @@ -1,6 +1,6 @@ /// Memory lifetime of closures in Swift are managed by Swift side class SwiftClosureDeallocator { - constructor(exports) { + constructor(exports$1) { if (typeof FinalizationRegistry === "undefined") { throw new Error("The Swift part of JavaScriptKit was configured to require " + "the availability of JavaScript WeakRefs. Please build " + @@ -8,7 +8,7 @@ class SwiftClosureDeallocator { "disable features that use WeakRefs."); } this.functionRegistry = new FinalizationRegistry((id) => { - exports.swjs_free_host_function(id); + exports$1.swjs_free_host_function(id); }); } track(func, func_ref) { @@ -30,6 +30,7 @@ const decode = (kind, payload1, payload2, objectSpace) => { case 1: return true; } + // falls through case 2 /* Kind.Number */: return payload2; case 1 /* Kind.String */: @@ -126,12 +127,12 @@ class ITCInterface { } send(sendingObject, transferringObjects, sendingContext) { const object = this.memory.getObject(sendingObject); - const transfer = transferringObjects.map(ref => this.memory.getObject(ref)); + const transfer = transferringObjects.map((ref) => this.memory.getObject(ref)); return { object, sendingContext, transfer }; } sendObjects(sendingObjects, transferringObjects, sendingContext) { - const objects = sendingObjects.map(ref => this.memory.getObject(ref)); - const transfer = transferringObjects.map(ref => this.memory.getObject(ref)); + const objects = sendingObjects.map((ref) => this.memory.getObject(ref)); + const transfer = transferringObjects.map((ref) => this.memory.getObject(ref)); return { object: objects, sendingContext, transfer }; } release(objectRef) { @@ -168,7 +169,9 @@ class MessageBroker { this.handlers.onResponse(message); return; } - const transfer = message.data.response.ok ? message.data.response.value.transfer : []; + const transfer = message.data.response.ok + ? message.data.response.value.transfer + : []; if ("postMessageToWorkerThread" in this.threadChannel) { // The response is for another worker thread sent from the main thread this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer); @@ -186,7 +189,7 @@ class MessageBroker { this.handlers.onRequest(message); } else if ("postMessageToWorkerThread" in this.threadChannel) { - // Receive a request from a worker thread to other worker on main thread. + // Receive a request from a worker thread to other worker on main thread. // Proxy the request to the target worker thread. this.threadChannel.postMessageToWorkerThread(message.data.targetTid, message, []); } @@ -202,7 +205,9 @@ class MessageBroker { else if ("postMessageToWorkerThread" in this.threadChannel) { // Receive a response from a worker thread to other worker on main thread. // Proxy the response to the target worker thread. - const transfer = message.data.response.ok ? message.data.response.value.transfer : []; + const transfer = message.data.response.ok + ? message.data.response.value.transfer + : []; this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer); } else if ("postMessageToMainThread" in this.threadChannel) { @@ -213,7 +218,14 @@ class MessageBroker { } function serializeError(error) { if (error instanceof Error) { - return { isError: true, value: { message: error.message, name: error.name, stack: error.stack } }; + return { + isError: true, + value: { + message: error.message, + name: error.name, + stack: error.stack, + }, + }; } return { isError: false, value: error }; } @@ -224,19 +236,7 @@ function deserializeError(error) { return error.value; } -let globalVariable; -if (typeof globalThis !== "undefined") { - globalVariable = globalThis; -} -else if (typeof window !== "undefined") { - globalVariable = window; -} -else if (typeof global !== "undefined") { - globalVariable = global; -} -else if (typeof self !== "undefined") { - globalVariable = self; -} +const globalVariable = globalThis; class JSObjectSpace { constructor() { @@ -312,7 +312,8 @@ class SwiftRuntime { // 1. It may not be available in the global scope if the context is not cross-origin isolated. // 2. The underlying buffer may be still backed by SAB even if the context is not cross-origin // isolated (e.g. localhost on Chrome on Android). - if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name === "SharedArrayBuffer") { + if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name === + "SharedArrayBuffer") { // When the wasm memory is backed by a SharedArrayBuffer, growing the memory // doesn't invalidate the data view by setting the byte length to 0. Instead, // the data view points to an old buffer after growing the memory. So we have @@ -463,7 +464,10 @@ class SwiftRuntime { returnValue = { ok: true, value: result }; } catch (error) { - returnValue = { ok: false, error: serializeError(error) }; + returnValue = { + ok: false, + error: serializeError(error), + }; } const responseMessage = { type: "response", @@ -479,7 +483,7 @@ class SwiftRuntime { catch (error) { responseMessage.data.response = { ok: false, - error: serializeError(new TypeError(`Failed to serialize message: ${error}`)) + error: serializeError(new TypeError(`Failed to serialize message: ${error}`)), }; newBroker.reply(responseMessage); } @@ -494,7 +498,7 @@ class SwiftRuntime { const errorObject = this.memory.retain(error); this.exports.swjs_receive_error(errorObject, message.data.context); } - } + }, }); broker = newBroker; return newBroker; @@ -532,21 +536,19 @@ class SwiftRuntime { this.getDataView().setUint32(bytes_ptr_result, bytes_ptr, true); return bytes.length; }, - swjs_decode_string: ( + swjs_decode_string: // NOTE: TextDecoder can't decode typed arrays backed by SharedArrayBuffer this.options.sharedMemory == true - ? ((bytes_ptr, length) => { - const bytes = this.getUint8Array() - .slice(bytes_ptr, bytes_ptr + length); + ? (bytes_ptr, length) => { + const bytes = this.getUint8Array().slice(bytes_ptr, bytes_ptr + length); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); - }) - : ((bytes_ptr, length) => { - const bytes = this.getUint8Array() - .subarray(bytes_ptr, bytes_ptr + length); + } + : (bytes_ptr, length) => { + const bytes = this.getUint8Array().subarray(bytes_ptr, bytes_ptr + length); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); - })), + }, swjs_load_string: (ref, buffer) => { const bytes = this.memory.getObject(ref); this.getUint8Array().set(bytes, buffer); @@ -554,7 +556,7 @@ class SwiftRuntime { swjs_call_function: (ref, argv, argc, payload1_ptr, payload2_ptr) => { const memory = this.memory; const func = memory.getObject(ref); - let result = undefined; + let result; try { const args = decodeArray(argv, argc, this.getDataView(), memory); result = func(...args); @@ -589,9 +591,8 @@ class SwiftRuntime { const memory = this.memory; const obj = memory.getObject(obj_ref); const func = memory.getObject(func_ref); - let result = undefined; const args = decodeArray(argv, argc, this.getDataView(), memory); - result = func.apply(obj, args); + const result = func.apply(obj, args); return writeAndReturnKindBits(result, payload1_ptr, payload2_ptr, false, this.getDataView(), this.memory); }, swjs_call_new: (ref, argv, argc) => { @@ -658,7 +659,9 @@ class SwiftRuntime { // Call `.slice()` to copy the memory return this.memory.retain(array.slice()); }, - swjs_create_object: () => { return this.memory.retain({}); }, + swjs_create_object: () => { + return this.memory.retain({}); + }, swjs_load_typed_array: (ref, buffer) => { const memory = this.memory; const typedArray = memory.getObject(ref); @@ -683,8 +686,8 @@ class SwiftRuntime { request: { method: "release", parameters: [ref], - } - } + }, + }, }); }, swjs_i64_to_bigint: (value, signed) => { @@ -708,17 +711,23 @@ class SwiftRuntime { swjs_i64_to_bigint_slow: (lower, upper, signed) => { const value = BigInt.asUintN(32, BigInt(lower)) + (BigInt.asUintN(32, BigInt(upper)) << BigInt(32)); - return this.memory.retain(signed ? BigInt.asIntN(64, value) : BigInt.asUintN(64, value)); + return this.memory.retain(signed + ? BigInt.asIntN(64, value) + : BigInt.asUintN(64, value)); }, swjs_unsafe_event_loop_yield: () => { throw new UnsafeEventLoopYield(); }, swjs_send_job_to_main_thread: (unowned_job) => { - this.postMessageToMainThread({ type: "job", data: unowned_job }); + this.postMessageToMainThread({ + type: "job", + data: unowned_job, + }); }, swjs_listen_message_from_main_thread: () => { const threadChannel = this.options.threadChannel; - if (!(threadChannel && "listenMessageFromMainThread" in threadChannel)) { + if (!(threadChannel && + "listenMessageFromMainThread" in threadChannel)) { throw new Error("listenMessageFromMainThread is not set in options given to SwiftRuntime. Please set it to listen to wake events from the main thread."); } const broker = getMessageBroker(threadChannel); @@ -735,9 +744,10 @@ class SwiftRuntime { broker.onReceivingResponse(message); break; } - default: + default: { const unknownMessage = message; throw new Error(`Unknown message type: ${unknownMessage}`); + } } }); }, @@ -746,7 +756,8 @@ class SwiftRuntime { }, swjs_listen_message_from_worker_thread: (tid) => { const threadChannel = this.options.threadChannel; - if (!(threadChannel && "listenMessageFromWorkerThread" in threadChannel)) { + if (!(threadChannel && + "listenMessageFromWorkerThread" in threadChannel)) { throw new Error("listenMessageFromWorkerThread is not set in options given to SwiftRuntime. Please set it to listen to jobs from worker threads."); } const broker = getMessageBroker(threadChannel); @@ -763,9 +774,10 @@ class SwiftRuntime { broker.onReceivingResponse(message); break; } - default: + default: { const unknownMessage = message; throw new Error(`Unknown message type: ${unknownMessage}`); + } } }); }, @@ -795,9 +807,13 @@ class SwiftRuntime { context: sending_context, request: { method: "send", - parameters: [sending_object, transferringObjects, sending_context], - } - } + parameters: [ + sending_object, + transferringObjects, + sending_context, + ], + }, + }, }); }, swjs_request_sending_objects: (sending_objects, sending_objects_count, transferring_objects, transferring_objects_count, object_source_tid, sending_context) => { @@ -817,9 +833,13 @@ class SwiftRuntime { context: sending_context, request: { method: "sendObjects", - parameters: [sendingObjects, transferringObjects, sending_context], - } - } + parameters: [ + sendingObjects, + transferringObjects, + sending_context, + ], + }, + }, }); }, }; diff --git a/README.md b/README.md index 6a0acaa27..03129c3e2 100644 --- a/README.md +++ b/README.md @@ -48,10 +48,10 @@ _ = document.body.appendChild(button) BridgeJS provides easy interoperability between Swift and JavaScript/TypeScript. It enables: -- **Exporting Swift APIs to JavaScript**: Make your Swift code callable from JavaScript -- **Importing TypeScript APIs into Swift**: Use JavaScript APIs with type safety in Swift +- **Export Swift to JavaScript** - Expose Swift functions, classes, and types to JavaScript; the plugin also generates TypeScript definitions (`.d.ts`) for the exported API. +- **Import JavaScript into Swift** - Make JavaScript/TypeScript APIs (functions, classes, globals like `document` or `console`) callable from Swift with type-safe bindings. You can declare bindings with macros in Swift or generate them from a TypeScript declaration file (`bridge-js.d.ts`). -For architecture details, see the [BridgeJS Plugin README](Plugins/BridgeJS/README.md). +For architecture details, see the [BridgeJS Plugin README](Plugins/BridgeJS/README.md). For package and build setup, see [Setting up BridgeJS](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/setting-up-bridgejs) in the documentation. ### Exporting Swift to JavaScript @@ -81,32 +81,36 @@ console.log(greeter.greet()); // "Hello, World!" **Learn more:** [Exporting Swift to JavaScript](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/exporting-swift-to-javascript) -### Importing TypeScript into Swift +### Importing JavaScript into Swift -Define TypeScript interfaces and BridgeJS generates type-safe Swift bindings: +Declare bindings in Swift with macros such as `@JSFunction`, `@JSClass`, `@JSGetter`, and `@JSSetter`: -```typescript -// bridge-js.d.ts -interface Document { - title: string; - getElementById(id: string): HTMLElement; - createElement(tagName: string): HTMLElement; +```swift +import JavaScriptKit + +@JSClass struct Document { + @JSFunction func getElementById(_ id: String) throws(JSException) -> HTMLElement + @JSFunction func createElement(_ tagName: String) throws(JSException) -> HTMLElement } +@JSGetter(from: .global) var document: Document -export function getDocument(): Document; -``` +@JSClass struct HTMLElement { + @JSGetter var innerText: String + @JSSetter func setInnerText(_ newValue: String) throws(JSException) + @JSFunction func appendChild(_ child: HTMLElement) throws(JSException) +} -**Swift usage:** -```swift @JS func run() throws(JSException) { - let document = try getDocument() - try document.setTitle("My Swift App") let button = try document.createElement("button") try button.setInnerText("Click Me") + let container = try document.getElementById("app") + try container.appendChild(button) } ``` -**Learn more:** [Importing TypeScript into Swift](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/importing-typescript-into-swift) +You can also generate the same macro-annotated Swift from a TypeScript file (`bridge-js.d.ts`). See [Generating bindings from TypeScript](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/generating-from-typescript) in the documentation. + +**Learn more:** [Importing JavaScript into Swift](https://swiftpackageindex.com/swiftwasm/JavaScriptKit/documentation/javascriptkit/importing-javascript-into-swift) ### Try It Online diff --git a/Runtime/src/closure-heap.ts b/Runtime/src/closure-heap.ts index 269934390..0ec0ba9ac 100644 --- a/Runtime/src/closure-heap.ts +++ b/Runtime/src/closure-heap.ts @@ -10,7 +10,7 @@ export class SwiftClosureDeallocator { "The Swift part of JavaScriptKit was configured to require " + "the availability of JavaScript WeakRefs. Please build " + "with `-Xswiftc -DJAVASCRIPTKIT_WITHOUT_WEAKREFS` to " + - "disable features that use WeakRefs." + "disable features that use WeakRefs.", ); } diff --git a/Runtime/src/find-global.ts b/Runtime/src/find-global.ts index f20afbf34..1530f446e 100644 --- a/Runtime/src/find-global.ts +++ b/Runtime/src/find-global.ts @@ -1,13 +1 @@ -interface GlobalVariable {} -declare const global: GlobalVariable; - -export let globalVariable: any; -if (typeof globalThis !== "undefined") { - globalVariable = globalThis; -} else if (typeof window !== "undefined") { - globalVariable = window; -} else if (typeof global !== "undefined") { - globalVariable = global; -} else if (typeof self !== "undefined") { - globalVariable = self; -} +export const globalVariable: any = globalThis; diff --git a/Runtime/src/index.ts b/Runtime/src/index.ts index 27b52c7da..5d6fe258f 100644 --- a/Runtime/src/index.ts +++ b/Runtime/src/index.ts @@ -7,7 +7,16 @@ import { MAIN_THREAD_TID, } from "./types.js"; import * as JSValue from "./js-value.js"; -import { deserializeError, MainToWorkerMessage, MessageBroker, ResponseMessage, ITCInterface, serializeError, SwiftRuntimeThreadChannel, WorkerToMainMessage } from "./itc.js"; +import { + deserializeError, + MainToWorkerMessage, + MessageBroker, + ResponseMessage, + ITCInterface, + serializeError, + SwiftRuntimeThreadChannel, + WorkerToMainMessage, +} from "./itc.js"; import { decodeObjectRefs } from "./js-value.js"; import { JSObjectSpace } from "./object-heap.js"; export { SwiftRuntimeThreadChannel }; @@ -36,8 +45,8 @@ export class SwiftRuntime { private textEncoder = new TextEncoder(); // Only support utf-8 /** The thread ID of the current thread. */ private tid: number | null; - private getDataView: (() => DataView); - private getUint8Array: (() => Uint8Array); + private getDataView: () => DataView; + private getUint8Array: () => Uint8Array; private wasmMemory: WebAssembly.Memory | null; UnsafeEventLoopYield = UnsafeEventLoopYield; @@ -49,10 +58,14 @@ export class SwiftRuntime { this.tid = null; this.options = options || {}; this.getDataView = () => { - throw new Error("Please call setInstance() before using any JavaScriptKit APIs from Swift."); + throw new Error( + "Please call setInstance() before using any JavaScriptKit APIs from Swift.", + ); }; this.getUint8Array = () => { - throw new Error("Please call setInstance() before using any JavaScriptKit APIs from Swift."); + throw new Error( + "Please call setInstance() before using any JavaScriptKit APIs from Swift.", + ); }; this.wasmMemory = null; } @@ -70,7 +83,10 @@ export class SwiftRuntime { // 1. It may not be available in the global scope if the context is not cross-origin isolated. // 2. The underlying buffer may be still backed by SAB even if the context is not cross-origin // isolated (e.g. localhost on Chrome on Android). - if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name === "SharedArrayBuffer") { + if ( + Object.getPrototypeOf(wasmMemory.buffer).constructor.name === + "SharedArrayBuffer" + ) { // When the wasm memory is backed by a SharedArrayBuffer, growing the memory // doesn't invalidate the data view by setting the byte length to 0. Instead, // the data view points to an old buffer after growing the memory. So we have @@ -105,14 +121,16 @@ export class SwiftRuntime { } this.wasmMemory = wasmMemory; } else { - throw new Error("instance.exports.memory is not a WebAssembly.Memory!?"); + throw new Error( + "instance.exports.memory is not a WebAssembly.Memory!?", + ); } if (typeof (this.exports as any)._start === "function") { throw new Error( `JavaScriptKit supports only WASI reactor ABI. Please make sure you are building with: -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor - ` + `, ); } if (this.exports.swjs_library_version() != this.version) { @@ -120,7 +138,7 @@ export class SwiftRuntime { `The versions of JavaScriptKit are incompatible. WebAssembly runtime ${this.exports.swjs_library_version()} != JS runtime ${ this.version - }` + }`, ); } } @@ -159,7 +177,7 @@ export class SwiftRuntime { instance.exports.wasi_thread_start(tid, startArg); } else { throw new Error( - `The WebAssembly module is not built for wasm32-unknown-wasip1-threads target.` + `The WebAssembly module is not built for wasm32-unknown-wasip1-threads target.`, ); } } catch (error) { @@ -190,7 +208,7 @@ export class SwiftRuntime { (features & LibraryFeatures.WeakRefs) != 0; if (librarySupportsWeakRef) { this._closureDeallocator = new SwiftClosureDeallocator( - this.exports + this.exports, ); } return this._closureDeallocator; @@ -200,7 +218,7 @@ export class SwiftRuntime { host_func_id: number, line: number, file: string, - args: any[] + args: any[], ) { const argc = args.length; const argv = this.exports.swjs_prepare_host_function_call(argc); @@ -209,7 +227,15 @@ export class SwiftRuntime { for (let index = 0; index < args.length; index++) { const argument = args[index]; const base = argv + 16 * index; - JSValue.write(argument, base, base + 4, base + 8, false, dataView, memory); + JSValue.write( + argument, + base, + base + 4, + base + 8, + false, + dataView, + memory, + ); } let output: any; // This ref is released by the swjs_call_host_function implementation @@ -220,11 +246,11 @@ export class SwiftRuntime { host_func_id, argv, argc, - callback_func_ref + callback_func_ref, ); if (alreadyReleased) { throw new Error( - `The JSClosure has been already released by Swift side. The closure is created at ${file}:${line} @${host_func_id}` + `The JSClosure has been already released by Swift side. The closure is created at ${file}:${line} @${host_func_id}`, ); } this.exports.swjs_cleanup_host_function_call(argv); @@ -244,10 +270,15 @@ export class SwiftRuntime { let returnValue: ResponseMessage["data"]["response"]; try { // @ts-ignore - const result = itcInterface[message.data.request.method](...message.data.request.parameters); + const result = itcInterface[ + message.data.request.method + ](...message.data.request.parameters); returnValue = { ok: true, value: result }; } catch (error) { - returnValue = { ok: false, error: serializeError(error) }; + returnValue = { + ok: false, + error: serializeError(error), + }; } const responseMessage: ResponseMessage = { type: "response", @@ -256,38 +287,52 @@ export class SwiftRuntime { context: message.data.context, response: returnValue, }, - } + }; try { newBroker.reply(responseMessage); } catch (error) { responseMessage.data.response = { ok: false, - error: serializeError(new TypeError(`Failed to serialize message: ${error}`)) + error: serializeError( + new TypeError( + `Failed to serialize message: ${error}`, + ), + ), }; newBroker.reply(responseMessage); } }, onResponse: (message) => { if (message.data.response.ok) { - const object = this.memory.retain(message.data.response.value.object); - this.exports.swjs_receive_response(object, message.data.context); + const object = this.memory.retain( + message.data.response.value.object, + ); + this.exports.swjs_receive_response( + object, + message.data.context, + ); } else { - const error = deserializeError(message.data.response.error); + const error = deserializeError( + message.data.response.error, + ); const errorObject = this.memory.retain(error); - this.exports.swjs_receive_error(errorObject, message.data.context); + this.exports.swjs_receive_error( + errorObject, + message.data.context, + ); } - } - }) + }, + }); broker = newBroker; return newBroker; - } + }; return { swjs_set_prop: ( ref: ref, name: ref, kind: JSValue.Kind, payload1: number, - payload2: number + payload2: number, ) => { const memory = this.memory; const obj = memory.getObject(ref); @@ -299,7 +344,7 @@ export class SwiftRuntime { ref: ref, name: ref, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const memory = this.memory; const obj = memory.getObject(ref); @@ -311,7 +356,7 @@ export class SwiftRuntime { payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, @@ -320,7 +365,7 @@ export class SwiftRuntime { index: number, kind: JSValue.Kind, payload1: number, - payload2: number + payload2: number, ) => { const memory = this.memory; const obj = memory.getObject(ref); @@ -331,7 +376,7 @@ export class SwiftRuntime { ref: ref, index: number, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const obj = this.memory.getObject(ref); const result = obj[index]; @@ -341,7 +386,7 @@ export class SwiftRuntime { payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, @@ -352,22 +397,25 @@ export class SwiftRuntime { this.getDataView().setUint32(bytes_ptr_result, bytes_ptr, true); return bytes.length; }, - swjs_decode_string: ( + swjs_decode_string: // NOTE: TextDecoder can't decode typed arrays backed by SharedArrayBuffer this.options.sharedMemory == true - ? ((bytes_ptr: pointer, length: number) => { - const bytes = this.getUint8Array() - .slice(bytes_ptr, bytes_ptr + length); - const string = this.textDecoder.decode(bytes); - return this.memory.retain(string); - }) - : ((bytes_ptr: pointer, length: number) => { - const bytes = this.getUint8Array() - .subarray(bytes_ptr, bytes_ptr + length); - const string = this.textDecoder.decode(bytes); - return this.memory.retain(string); - }) - ), + ? (bytes_ptr: pointer, length: number) => { + const bytes = this.getUint8Array().slice( + bytes_ptr, + bytes_ptr + length, + ); + const string = this.textDecoder.decode(bytes); + return this.memory.retain(string); + } + : (bytes_ptr: pointer, length: number) => { + const bytes = this.getUint8Array().subarray( + bytes_ptr, + bytes_ptr + length, + ); + const string = this.textDecoder.decode(bytes); + return this.memory.retain(string); + }, swjs_load_string: (ref: ref, buffer: pointer) => { const bytes = this.memory.getObject(ref); this.getUint8Array().set(bytes, buffer); @@ -378,13 +426,18 @@ export class SwiftRuntime { argv: pointer, argc: number, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const memory = this.memory; const func = memory.getObject(ref); - let result = undefined; + let result: any; try { - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); result = func(...args); } catch (error) { return JSValue.writeAndReturnKindBits( @@ -393,7 +446,7 @@ export class SwiftRuntime { payload2_ptr, true, this.getDataView(), - this.memory + this.memory, ); } return JSValue.writeAndReturnKindBits( @@ -402,7 +455,7 @@ export class SwiftRuntime { payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, swjs_call_function_no_catch: ( @@ -410,11 +463,16 @@ export class SwiftRuntime { argv: pointer, argc: number, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const memory = this.memory; const func = memory.getObject(ref); - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); const result = func(...args); return JSValue.writeAndReturnKindBits( result, @@ -422,7 +480,7 @@ export class SwiftRuntime { payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, @@ -432,14 +490,19 @@ export class SwiftRuntime { argv: pointer, argc: number, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const memory = this.memory; const obj = memory.getObject(obj_ref); const func = memory.getObject(func_ref); let result: any; try { - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); result = func.apply(obj, args); } catch (error) { return JSValue.writeAndReturnKindBits( @@ -448,7 +511,7 @@ export class SwiftRuntime { payload2_ptr, true, this.getDataView(), - this.memory + this.memory, ); } return JSValue.writeAndReturnKindBits( @@ -457,7 +520,7 @@ export class SwiftRuntime { payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, swjs_call_function_with_this_no_catch: ( @@ -466,28 +529,37 @@ export class SwiftRuntime { argv: pointer, argc: number, payload1_ptr: pointer, - payload2_ptr: pointer + payload2_ptr: pointer, ) => { const memory = this.memory; const obj = memory.getObject(obj_ref); const func = memory.getObject(func_ref); - let result = undefined; - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); - result = func.apply(obj, args); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); + const result = func.apply(obj, args); return JSValue.writeAndReturnKindBits( result, payload1_ptr, payload2_ptr, false, this.getDataView(), - this.memory + this.memory, ); }, swjs_call_new: (ref: ref, argv: pointer, argc: number) => { const memory = this.memory; const constructor = memory.getObject(ref); - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); const instance = new constructor(...args); return this.memory.retain(instance); }, @@ -497,13 +569,18 @@ export class SwiftRuntime { argc: number, exception_kind_ptr: pointer, exception_payload1_ptr: pointer, - exception_payload2_ptr: pointer + exception_payload2_ptr: pointer, ) => { let memory = this.memory; const constructor = memory.getObject(ref); let result: any; try { - const args = JSValue.decodeArray(argv, argc, this.getDataView(), memory); + const args = JSValue.decodeArray( + argv, + argc, + this.getDataView(), + memory, + ); result = new constructor(...args); } catch (error) { JSValue.write( @@ -513,7 +590,7 @@ export class SwiftRuntime { exception_payload2_ptr, true, this.getDataView(), - this.memory + this.memory, ); return -1; } @@ -525,7 +602,7 @@ export class SwiftRuntime { exception_payload2_ptr, false, this.getDataView(), - memory + memory, ); return memory.retain(result); }, @@ -547,7 +624,7 @@ export class SwiftRuntime { swjs_create_function: ( host_func_id: number, line: number, - file: ref + file: ref, ) => { const fileString = this.memory.getObject(file) as string; const func = (...args: any[]) => @@ -560,7 +637,7 @@ export class SwiftRuntime { swjs_create_oneshot_function: ( host_func_id: number, line: number, - file: ref + file: ref, ) => { const fileString = this.memory.getObject(file) as string; const func = (...args: any[]) => @@ -569,13 +646,30 @@ export class SwiftRuntime { return func_ref; }, - swjs_create_typed_array: ( + swjs_create_typed_array: < + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array + | Float32Array + | Float64Array + | Uint8ClampedArray, + >( constructor_ref: ref, elementsPtr: pointer, - length: number + length: number, ) => { type TypedArrayConstructor = { - new (buffer: ArrayBuffer, byteOffset: number, length: number): T; + new ( + buffer: ArrayBuffer, + byteOffset: number, + length: number, + ): T; new (): T; }; const ArrayType: TypedArrayConstructor = @@ -592,13 +686,15 @@ export class SwiftRuntime { const array = new ArrayType( this.wasmMemory!.buffer, elementsPtr, - length + length, ); // Call `.slice()` to copy the memory return this.memory.retain(array.slice()); }, - swjs_create_object: () => { return this.memory.retain({}); }, + swjs_create_object: () => { + return this.memory.retain({}); + }, swjs_load_typed_array: (ref: ref, buffer: pointer) => { const memory = this.memory; @@ -613,7 +709,9 @@ export class SwiftRuntime { swjs_release_remote: (tid: number, ref: ref) => { if (!this.options.threadChannel) { - throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to release objects on remote threads."); + throw new Error( + "threadChannel is not set in options given to SwiftRuntime. Please set it to release objects on remote threads.", + ); } const broker = getMessageBroker(this.options.threadChannel); broker.request({ @@ -625,20 +723,22 @@ export class SwiftRuntime { request: { method: "release", parameters: [ref], - } - } - }) + }, + }, + }); }, swjs_i64_to_bigint: (value: bigint, signed: number) => { return this.memory.retain( - signed ? value : BigInt.asUintN(64, value) + signed ? value : BigInt.asUintN(64, value), ); }, swjs_bigint_to_i64: (ref: ref, signed: number) => { const object = this.memory.getObject(ref); if (typeof object !== "bigint") { - throw new Error(`Expected a BigInt, but got ${typeof object}`); + throw new Error( + `Expected a BigInt, but got ${typeof object}`, + ); } if (signed) { return object; @@ -649,44 +749,61 @@ export class SwiftRuntime { return BigInt.asIntN(64, object); } }, - swjs_i64_to_bigint_slow: (lower: number, upper: number, signed: number) => { + swjs_i64_to_bigint_slow: ( + lower: number, + upper: number, + signed: number, + ) => { const value = BigInt.asUintN(32, BigInt(lower)) + (BigInt.asUintN(32, BigInt(upper)) << BigInt(32)); return this.memory.retain( - signed ? BigInt.asIntN(64, value) : BigInt.asUintN(64, value) + signed + ? BigInt.asIntN(64, value) + : BigInt.asUintN(64, value), ); }, swjs_unsafe_event_loop_yield: () => { throw new UnsafeEventLoopYield(); }, swjs_send_job_to_main_thread: (unowned_job: number) => { - this.postMessageToMainThread({ type: "job", data: unowned_job }); + this.postMessageToMainThread({ + type: "job", + data: unowned_job, + }); }, swjs_listen_message_from_main_thread: () => { const threadChannel = this.options.threadChannel; - if (!(threadChannel && "listenMessageFromMainThread" in threadChannel)) { + if ( + !( + threadChannel && + "listenMessageFromMainThread" in threadChannel + ) + ) { throw new Error( - "listenMessageFromMainThread is not set in options given to SwiftRuntime. Please set it to listen to wake events from the main thread." + "listenMessageFromMainThread is not set in options given to SwiftRuntime. Please set it to listen to wake events from the main thread.", ); } const broker = getMessageBroker(threadChannel); threadChannel.listenMessageFromMainThread((message) => { switch (message.type) { - case "wake": - this.exports.swjs_wake_worker_thread(); - break; - case "request": { - broker.onReceivingRequest(message); - break; - } - case "response": { - broker.onReceivingResponse(message); - break; - } - default: - const unknownMessage: never = message; - throw new Error(`Unknown message type: ${unknownMessage}`); + case "wake": + this.exports.swjs_wake_worker_thread(); + break; + case "request": { + broker.onReceivingRequest(message); + break; + } + case "response": { + broker.onReceivingResponse(message); + break; + } + default: { + const unknownMessage: never = message; + throw new Error( + `Unknown message type: ${unknownMessage}`, + ); + } } }); }, @@ -695,17 +812,23 @@ export class SwiftRuntime { }, swjs_listen_message_from_worker_thread: (tid: number) => { const threadChannel = this.options.threadChannel; - if (!(threadChannel && "listenMessageFromWorkerThread" in threadChannel)) { + if ( + !( + threadChannel && + "listenMessageFromWorkerThread" in threadChannel + ) + ) { throw new Error( - "listenMessageFromWorkerThread is not set in options given to SwiftRuntime. Please set it to listen to jobs from worker threads." + "listenMessageFromWorkerThread is not set in options given to SwiftRuntime. Please set it to listen to jobs from worker threads.", ); } const broker = getMessageBroker(threadChannel); - threadChannel.listenMessageFromWorkerThread( - tid, (message) => { - switch (message.type) { + threadChannel.listenMessageFromWorkerThread(tid, (message) => { + switch (message.type) { case "job": - this.exports.swjs_enqueue_main_job_from_worker(message.data); + this.exports.swjs_enqueue_main_job_from_worker( + message.data, + ); break; case "request": { broker.onReceivingRequest(message); @@ -715,12 +838,14 @@ export class SwiftRuntime { broker.onReceivingResponse(message); break; } - default: + default: { const unknownMessage: never = message; - throw new Error(`Unknown message type: ${unknownMessage}`); + throw new Error( + `Unknown message type: ${unknownMessage}`, + ); } - }, - ); + } + }); }, swjs_terminate_worker_thread: (tid: number) => { const threadChannel = this.options.threadChannel; @@ -740,10 +865,16 @@ export class SwiftRuntime { sending_context: pointer, ) => { if (!this.options.threadChannel) { - throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects."); + throw new Error( + "threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects.", + ); } const broker = getMessageBroker(this.options.threadChannel); - const transferringObjects = decodeObjectRefs(transferring_objects, transferring_objects_count, this.getDataView()); + const transferringObjects = decodeObjectRefs( + transferring_objects, + transferring_objects_count, + this.getDataView(), + ); broker.request({ type: "request", data: { @@ -752,10 +883,14 @@ export class SwiftRuntime { context: sending_context, request: { method: "send", - parameters: [sending_object, transferringObjects, sending_context], - } - } - }) + parameters: [ + sending_object, + transferringObjects, + sending_context, + ], + }, + }, + }); }, swjs_request_sending_objects: ( sending_objects: pointer, @@ -766,12 +901,22 @@ export class SwiftRuntime { sending_context: pointer, ) => { if (!this.options.threadChannel) { - throw new Error("threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects."); + throw new Error( + "threadChannel is not set in options given to SwiftRuntime. Please set it to request transferring objects.", + ); } const broker = getMessageBroker(this.options.threadChannel); const dataView = this.getDataView(); - const sendingObjects = decodeObjectRefs(sending_objects, sending_objects_count, dataView); - const transferringObjects = decodeObjectRefs(transferring_objects, transferring_objects_count, dataView); + const sendingObjects = decodeObjectRefs( + sending_objects, + sending_objects_count, + dataView, + ); + const transferringObjects = decodeObjectRefs( + transferring_objects, + transferring_objects_count, + dataView, + ); broker.request({ type: "request", data: { @@ -780,29 +925,40 @@ export class SwiftRuntime { context: sending_context, request: { method: "sendObjects", - parameters: [sendingObjects, transferringObjects, sending_context], - } - } - }) + parameters: [ + sendingObjects, + transferringObjects, + sending_context, + ], + }, + }, + }); }, }; } - private postMessageToMainThread(message: WorkerToMainMessage, transfer: any[] = []) { + private postMessageToMainThread( + message: WorkerToMainMessage, + transfer: any[] = [], + ) { const threadChannel = this.options.threadChannel; if (!(threadChannel && "postMessageToMainThread" in threadChannel)) { throw new Error( - "postMessageToMainThread is not set in options given to SwiftRuntime. Please set it to send messages to the main thread." + "postMessageToMainThread is not set in options given to SwiftRuntime. Please set it to send messages to the main thread.", ); } threadChannel.postMessageToMainThread(message, transfer); } - private postMessageToWorkerThread(tid: number, message: MainToWorkerMessage, transfer: any[] = []) { + private postMessageToWorkerThread( + tid: number, + message: MainToWorkerMessage, + transfer: any[] = [], + ) { const threadChannel = this.options.threadChannel; if (!(threadChannel && "postMessageToWorkerThread" in threadChannel)) { throw new Error( - "postMessageToWorkerThread is not set in options given to SwiftRuntime. Please set it to send messages to worker threads." + "postMessageToWorkerThread is not set in options given to SwiftRuntime. Please set it to send messages to worker threads.", ); } threadChannel.postMessageToWorkerThread(tid, message, transfer); diff --git a/Runtime/src/itc.ts b/Runtime/src/itc.ts index 08b420640..9fadff54a 100644 --- a/Runtime/src/itc.ts +++ b/Runtime/src/itc.ts @@ -39,19 +39,24 @@ import { JSObjectSpace as JSObjectSpace } from "./object-heap.js"; */ export type SwiftRuntimeThreadChannel = | { - /** - * This function is used to send messages from the worker thread to the main thread. - * The message submitted by this function is expected to be listened by `listenMessageFromWorkerThread`. - * @param message The message to be sent to the main thread. - * @param transfer The array of objects to be transferred to the main thread. - */ - postMessageToMainThread: (message: WorkerToMainMessage, transfer: any[]) => void; + /** + * This function is used to send messages from the worker thread to the main thread. + * The message submitted by this function is expected to be listened by `listenMessageFromWorkerThread`. + * @param message The message to be sent to the main thread. + * @param transfer The array of objects to be transferred to the main thread. + */ + postMessageToMainThread: ( + message: WorkerToMainMessage, + transfer: any[], + ) => void; /** * This function is expected to be set in the worker thread and should listen * to messages from the main thread sent by `postMessageToWorkerThread`. * @param listener The listener function to be called when a message is received from the main thread. */ - listenMessageFromMainThread: (listener: (message: MainToWorkerMessage) => void) => void; + listenMessageFromMainThread: ( + listener: (message: MainToWorkerMessage) => void, + ) => void; } | { /** @@ -61,7 +66,11 @@ export type SwiftRuntimeThreadChannel = * @param message The message to be sent to the worker thread. * @param transfer The array of objects to be transferred to the worker thread. */ - postMessageToWorkerThread: (tid: number, message: MainToWorkerMessage, transfer: any[]) => void; + postMessageToWorkerThread: ( + tid: number, + message: MainToWorkerMessage, + transfer: any[], + ) => void; /** * This function is expected to be set in the main thread and should listen * to messages sent by `postMessageToMainThread` from the worker thread. @@ -70,7 +79,7 @@ export type SwiftRuntimeThreadChannel = */ listenMessageFromWorkerThread: ( tid: number, - listener: (message: WorkerToMainMessage) => void + listener: (message: WorkerToMainMessage) => void, ) => void; /** @@ -81,23 +90,34 @@ export type SwiftRuntimeThreadChannel = terminateWorkerThread?: (tid: number) => void; }; - export class ITCInterface { constructor(private memory: JSObjectSpace) {} - send(sendingObject: ref, transferringObjects: ref[], sendingContext: pointer): { object: any, sendingContext: pointer, transfer: Transferable[] } { + send( + sendingObject: ref, + transferringObjects: ref[], + sendingContext: pointer, + ): { object: any; sendingContext: pointer; transfer: Transferable[] } { const object = this.memory.getObject(sendingObject); - const transfer = transferringObjects.map(ref => this.memory.getObject(ref)); + const transfer = transferringObjects.map((ref) => + this.memory.getObject(ref), + ); return { object, sendingContext, transfer }; } - sendObjects(sendingObjects: ref[], transferringObjects: ref[], sendingContext: pointer): { object: any[], sendingContext: pointer, transfer: Transferable[] } { - const objects = sendingObjects.map(ref => this.memory.getObject(ref)); - const transfer = transferringObjects.map(ref => this.memory.getObject(ref)); + sendObjects( + sendingObjects: ref[], + transferringObjects: ref[], + sendingContext: pointer, + ): { object: any[]; sendingContext: pointer; transfer: Transferable[] } { + const objects = sendingObjects.map((ref) => this.memory.getObject(ref)); + const transfer = transferringObjects.map((ref) => + this.memory.getObject(ref), + ); return { object: objects, sendingContext, transfer }; } - release(objectRef: ref): { object: undefined, transfer: Transferable[] } { + release(objectRef: ref): { object: undefined; transfer: Transferable[] } { this.memory.release(objectRef); return { object: undefined, transfer: [] }; } @@ -105,16 +125,18 @@ export class ITCInterface { type AllRequests> = { [K in keyof Interface]: { - method: K, - parameters: Parameters, - } -} + method: K; + parameters: Parameters; + }; +}; -type ITCRequest> = AllRequests[keyof AllRequests]; +type ITCRequest> = + AllRequests[keyof AllRequests]; type AllResponses> = { - [K in keyof Interface]: ReturnType -} -type ITCResponse> = AllResponses[keyof AllResponses]; + [K in keyof Interface]: ReturnType; +}; +type ITCResponse> = + AllResponses[keyof AllResponses]; export type RequestMessage = { type: "request"; @@ -127,10 +149,12 @@ export type RequestMessage = { context: pointer; /** The request content */ request: ITCRequest; - } -} + }; +}; -type SerializedError = { isError: true; value: Error } | { isError: false; value: unknown } +type SerializedError = + | { isError: true; value: Error } + | { isError: false; value: unknown }; export type ResponseMessage = { type: "response"; @@ -140,36 +164,42 @@ export type ResponseMessage = { /** The context pointer of the request */ context: pointer; /** The response content */ - response: { - ok: true, - value: ITCResponse; - } | { - ok: false, - error: SerializedError; - }; - } -} + response: + | { + ok: true; + value: ITCResponse; + } + | { + ok: false; + error: SerializedError; + }; + }; +}; -export type MainToWorkerMessage = { - type: "wake"; -} | RequestMessage | ResponseMessage; - -export type WorkerToMainMessage = { - type: "job"; - data: number; -} | RequestMessage | ResponseMessage; +export type MainToWorkerMessage = + | { + type: "wake"; + } + | RequestMessage + | ResponseMessage; +export type WorkerToMainMessage = + | { + type: "job"; + data: number; + } + | RequestMessage + | ResponseMessage; export class MessageBroker { constructor( private selfTid: number, private threadChannel: SwiftRuntimeThreadChannel, private handlers: { - onRequest: (message: RequestMessage) => void, - onResponse: (message: ResponseMessage) => void, - } - ) { - } + onRequest: (message: RequestMessage) => void; + onResponse: (message: ResponseMessage) => void; + }, + ) {} request(message: RequestMessage) { if (message.data.targetTid == this.selfTid) { @@ -177,7 +207,11 @@ export class MessageBroker { this.handlers.onRequest(message); } else if ("postMessageToWorkerThread" in this.threadChannel) { // The request is for another worker thread sent from the main thread - this.threadChannel.postMessageToWorkerThread(message.data.targetTid, message, []); + this.threadChannel.postMessageToWorkerThread( + message.data.targetTid, + message, + [], + ); } else if ("postMessageToMainThread" in this.threadChannel) { // The request is for other worker threads or the main thread sent from a worker thread this.threadChannel.postMessageToMainThread(message, []); @@ -192,10 +226,16 @@ export class MessageBroker { this.handlers.onResponse(message); return; } - const transfer = message.data.response.ok ? message.data.response.value.transfer : []; + const transfer = message.data.response.ok + ? message.data.response.value.transfer + : []; if ("postMessageToWorkerThread" in this.threadChannel) { // The response is for another worker thread sent from the main thread - this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer); + this.threadChannel.postMessageToWorkerThread( + message.data.sourceTid, + message, + transfer, + ); } else if ("postMessageToMainThread" in this.threadChannel) { // The response is for other worker threads or the main thread sent from a worker thread this.threadChannel.postMessageToMainThread(message, transfer); @@ -208,9 +248,13 @@ export class MessageBroker { if (message.data.targetTid == this.selfTid) { this.handlers.onRequest(message); } else if ("postMessageToWorkerThread" in this.threadChannel) { - // Receive a request from a worker thread to other worker on main thread. + // Receive a request from a worker thread to other worker on main thread. // Proxy the request to the target worker thread. - this.threadChannel.postMessageToWorkerThread(message.data.targetTid, message, []); + this.threadChannel.postMessageToWorkerThread( + message.data.targetTid, + message, + [], + ); } else if ("postMessageToMainThread" in this.threadChannel) { // A worker thread won't receive a request for other worker threads throw new Error("unreachable"); @@ -223,8 +267,14 @@ export class MessageBroker { } else if ("postMessageToWorkerThread" in this.threadChannel) { // Receive a response from a worker thread to other worker on main thread. // Proxy the response to the target worker thread. - const transfer = message.data.response.ok ? message.data.response.value.transfer : []; - this.threadChannel.postMessageToWorkerThread(message.data.sourceTid, message, transfer); + const transfer = message.data.response.ok + ? message.data.response.value.transfer + : []; + this.threadChannel.postMessageToWorkerThread( + message.data.sourceTid, + message, + transfer, + ); } else if ("postMessageToMainThread" in this.threadChannel) { // A worker thread won't receive a response for other worker threads throw new Error("unreachable"); @@ -234,7 +284,14 @@ export class MessageBroker { export function serializeError(error: unknown): SerializedError { if (error instanceof Error) { - return { isError: true, value: { message: error.message, name: error.name, stack: error.stack } }; + return { + isError: true, + value: { + message: error.message, + name: error.name, + stack: error.stack, + }, + }; } return { isError: false, value: error }; } diff --git a/Runtime/src/js-value.ts b/Runtime/src/js-value.ts index a188808bb..b044e5cbe 100644 --- a/Runtime/src/js-value.ts +++ b/Runtime/src/js-value.ts @@ -1,5 +1,10 @@ import { JSObjectSpace } from "./object-heap.js"; -import { assertNever, JavaScriptValueKindAndFlags, pointer, ref } from "./types.js"; +import { + assertNever, + JavaScriptValueKindAndFlags, + pointer, + ref, +} from "./types.js"; export const enum Kind { Boolean = 0, @@ -16,7 +21,7 @@ export const decode = ( kind: Kind, payload1: number, payload2: number, - objectSpace: JSObjectSpace + objectSpace: JSObjectSpace, ) => { switch (kind) { case Kind.Boolean: @@ -26,6 +31,7 @@ export const decode = ( case 1: return true; } + // falls through case Kind.Number: return payload2; @@ -48,7 +54,12 @@ export const decode = ( // Note: // `decodeValues` assumes that the size of RawJSValue is 16. -export const decodeArray = (ptr: pointer, length: number, memory: DataView, objectSpace: JSObjectSpace) => { +export const decodeArray = ( + ptr: pointer, + length: number, + memory: DataView, + objectSpace: JSObjectSpace, +) => { // fast path for empty array if (length === 0) { return []; @@ -76,7 +87,7 @@ export const write = ( payload2_ptr: pointer, is_exception: boolean, memory: DataView, - objectSpace: JSObjectSpace + objectSpace: JSObjectSpace, ) => { const kind = writeAndReturnKindBits( value, @@ -84,7 +95,7 @@ export const write = ( payload2_ptr, is_exception, memory, - objectSpace + objectSpace, ); memory.setUint32(kind_ptr, kind, true); }; @@ -95,7 +106,7 @@ export const writeAndReturnKindBits = ( payload2_ptr: pointer, is_exception: boolean, memory: DataView, - objectSpace: JSObjectSpace + objectSpace: JSObjectSpace, ): JavaScriptValueKindAndFlags => { const exceptionBit = (is_exception ? 1 : 0) << 31; if (value === null) { @@ -141,7 +152,11 @@ export const writeAndReturnKindBits = ( throw new Error("Unreachable"); }; -export function decodeObjectRefs(ptr: pointer, length: number, memory: DataView): ref[] { +export function decodeObjectRefs( + ptr: pointer, + length: number, + memory: DataView, +): ref[] { const result: ref[] = new Array(length); for (let i = 0; i < length; i++) { result[i] = memory.getUint32(ptr + 4 * i, true); diff --git a/Runtime/src/object-heap.ts b/Runtime/src/object-heap.ts index b90fc4eff..ba9cf8021 100644 --- a/Runtime/src/object-heap.ts +++ b/Runtime/src/object-heap.ts @@ -51,7 +51,7 @@ export class JSObjectSpace { const value = this._heapValueById.get(ref); if (value === undefined) { throw new ReferenceError( - "Attempted to read invalid reference " + ref + "Attempted to read invalid reference " + ref, ); } return value; diff --git a/Runtime/src/types.ts b/Runtime/src/types.ts index b8345cdfa..b39e949b2 100644 --- a/Runtime/src/types.ts +++ b/Runtime/src/types.ts @@ -13,7 +13,7 @@ export interface ExportedFunctions { host_func_id: number, argv: pointer, argc: number, - callback_func_ref: ref + callback_func_ref: ref, ): bool; swjs_free_host_function(host_func_id: number): void; diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift index d31e03597..7de4cb74a 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift @@ -4,7 +4,11 @@ // See: https://github.com/swiftlang/swift/pull/80266 // See: https://forums.swift.org/t/pitch-2-custom-main-and-global-executors/78437 +#if compiler(>=6.3) @_spi(ExperimentalCustomExecutors) import _Concurrency +#else +import _Concurrency +#endif import _CJavaScriptKit #if compiler(>=6.3) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift index 4b4115602..aebc90d65 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift @@ -1,5 +1,9 @@ import JavaScriptKit +#if compiler(>=6.3) @_spi(ExperimentalCustomExecutors) import _Concurrency +#else +import _Concurrency +#endif import _CJavaScriptEventLoop import _CJavaScriptKit diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 1e7893c82..15b5be9ee 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -15,8 +15,13 @@ import _CJavaScriptKit #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_throw") -@_spi(BridgeJS) public func _swift_js_throw(_ id: Int32) +private func _swift_js_throw_extern(_ id: Int32) #else +private func _swift_js_throw_extern(_ id: Int32) { + _onlyAvailableOnWasm() +} +#endif + /// Throws a JavaScript exception from Swift code. /// /// This function is called by the BridgeJS code generator when a Swift function throws @@ -24,10 +29,9 @@ import _CJavaScriptKit /// JavaScript-side runtime code. /// /// - Parameter id: The ID of the JavaScript exception object to throw -@_spi(BridgeJS) public func _swift_js_throw(_ id: Int32) { - _onlyAvailableOnWasm() +@_spi(BridgeJS) @inline(never) public func _swift_js_throw(_ id: Int32) { + _swift_js_throw_extern(id) } -#endif /// Retrieves and clears any pending JavaScript exception. /// @@ -49,6 +53,40 @@ import _CJavaScriptKit #endif } +/// Releases a Swift closure from the FinalizationRegistry +/// +/// This function is called by the BridgeJS code generator when a Swift closure is released. +/// The closure is released from the FinalizationRegistry so it can be garbage collected to +/// balance the +/// +/// - Parameter pointer: The pointer to `_BridgeJSTypedClosureBox` instance +@_expose(wasm, "bjs_release_swift_closure") +public func _bjs_release_swift_closure(_ pointer: UnsafeMutableRawPointer) { + Unmanaged.fromOpaque(pointer).release() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_closure_unregister") +internal func _swift_js_closure_unregister(_ id: Int32) +#else +/// Unregisters a Swift closure from the FinalizationRegistry +/// +/// - Parameter id: The JavaScriptObjectRef of the JS closure object created by +/// the BridgeJS's `make_swift_closure_{signature}` function. +/// +/// - Note: This is a best-effort operation. +/// According to the ECMAScript specification, calling +/// `FinalizationRegistry.prototype.unregister` does not guarantee that +/// a finalization callback will be suppressed if the target object has +/// already been garbage-collected and cleanup has been scheduled. +/// This means that the finalization callback should be tolerant of the +/// object being already collected. +/// See: https://tc39.es/ecma262/multipage/managing-memory.html#sec-finalization-registry.prototype.unregister +internal func _swift_js_closure_unregister(_ id: Int32) { + _onlyAvailableOnWasm() +} +#endif + // MARK: Type lowering/lifting // // The following part defines the parameter and return value lowering/lifting @@ -66,6 +104,11 @@ import _CJavaScriptKit // } // @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> <#WasmCoreType#> { // } +// // MARK: Stack ABI +// @_spi(BridgeJS) public static func bridgeJSStackPop() -> <#Self#> { +// } +// @_spi(BridgeJS) public consuming func bridgeJSStackPush() { +// } // } // ``` // @@ -76,6 +119,9 @@ import _CJavaScriptKit // - `func bridgeJSLiftReturn(_ ...) -> <#TargetType#>`: lift the given Wasm core type return value to a higher-level type // - `func bridgeJSLiftParameter(_ ...) -> <#TargetType#>`: lift the given Wasm core type parameters to a higher-level type // - `func bridgeJSLowerReturn() -> <#WasmCoreType#>`: lower the given higher-level return value to a Wasm core type +// - `func bridgeJSStackPop() -> <#TargetType#>`: no-arg overload that pops parameters from the param stack internally. +// Note: Pop order must match Swift's left-to-right argument evaluation order. +// - `func bridgeJSStackPush()`: push the value onto the return stack (used by _BridgedSwiftStackType for array elements) // // Optional types (ExportSwift only) additionally define: // - `func bridgeJSLowerParameterWithRetain()`: lower optional heap object with ownership transfer for escaping closures @@ -94,7 +140,21 @@ public protocol _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { consuming func bridgeJSLowerReturn() -> WasmCoreType } -extension Bool: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +public protocol _BridgedSwiftStackType { + associatedtype StackLiftResult = Self + static func bridgeJSStackPop() -> StackLiftResult + consuming func bridgeJSStackPush() +} + +/// Types that bridge with the same (isSome, value) ABI as Optional. +/// Used by JSUndefinedOr so all bridge methods delegate to Optional. +public protocol _BridgedAsOptional { + associatedtype Wrapped + var asOptional: Wrapped? { get } + init(optional: Wrapped?) +} + +extension Bool: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { self ? 1 : 0 @@ -106,12 +166,18 @@ extension Bool: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Bool { value == 1 } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Bool { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { self ? 1 : 0 } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(self ? 1 : 0) + } } -extension Int: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +extension Int: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(self) @@ -123,12 +189,18 @@ extension Int: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Int { Int(value) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(Int32(self)) + } } -extension UInt: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +extension UInt: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { Int32(bitPattern: UInt32(self)) @@ -140,12 +212,54 @@ extension UInt: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> UInt { UInt(UInt32(bitPattern: value)) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { Int32(bitPattern: UInt32(self)) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(Int32(bitPattern: UInt32(self))) + } +} + +extension Int32: _BridgedSwiftStackType { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int32 { + _swift_js_pop_i32() + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(self) + } +} + +extension Int64: _BridgedSwiftStackType { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Int64 { + Int64(_swift_js_pop_i32()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(Int32(self)) + } +} + +extension UInt32: _BridgedSwiftStackType { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt32 { + UInt32(bitPattern: _swift_js_pop_i32()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(Int32(bitPattern: self)) + } +} + +extension UInt64: _BridgedSwiftStackType { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> UInt64 { + UInt64(UInt32(bitPattern: _swift_js_pop_i32())) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(Int32(bitPattern: UInt32(self))) + } } -extension Float: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +extension Float: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Float32 { Float32(self) @@ -157,12 +271,18 @@ extension Float: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Float32) -> Float { Float(value) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Float { + bridgeJSLiftParameter(_swift_js_pop_f32()) + } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Float32 { Float32(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_f32(Float32(self)) + } } -extension Double: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { +extension Double: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Float64 { Float64(self) @@ -174,12 +294,20 @@ extension Double: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Float64) -> Double { Double(value) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Double { + bridgeJSLiftParameter(_swift_js_pop_f64()) + } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Float64 { Float64(self) } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_f64(Float64(self)) + } } -extension String { +extension String: _BridgedSwiftStackType { + public typealias StackLiftResult = String + // MARK: ImportTS @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { @@ -210,14 +338,30 @@ extension String { } } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> String { + let bytes = _swift_js_pop_i32() + let count = _swift_js_pop_i32() + return bridgeJSLiftParameter(bytes, count) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { return self.withUTF8 { ptr in _swift_js_return_string(ptr.baseAddress, Int32(ptr.count)) } } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + self.withUTF8 { ptr in + _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) + } + } } -extension JSObject { +extension JSObject: _BridgedSwiftStackType { + // JSObject is a non-final class, so we must explicitly specify the associated type + // rather than relying on the default `Self` (which Swift requires for covariant returns). + public typealias StackLiftResult = JSObject + // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { @@ -233,15 +377,91 @@ extension JSObject { JSObject(id: JavaScriptObjectRef(bitPattern: id)) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> JSObject { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { return _swift_js_retain(Int32(bitPattern: self.id)) } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(bridgeJSLowerReturn()) + } +} + +extension JSValue: _BridgedSwiftStackType { + public typealias StackLiftResult = JSValue + + @_transparent + private static func bridgeJSRetainPayloadIfNeeded(kind: Int32, payload1: Int32) -> Int32 { + guard let kindEnum = JavaScriptValueKind(rawValue: UInt32(kind)) else { + return payload1 + } + switch kindEnum { + case .string, .object, .symbol, .bigInt: + return _swift_js_retain(payload1) + default: + return payload1 + } + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> JSValue { + let payload2 = _swift_js_pop_f64() + let payload1 = _swift_js_pop_i32() + let kind = _swift_js_pop_i32() + return bridgeJSLiftParameter(kind, payload1, payload2) + } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() -> Void { + let lowered = bridgeJSLowerParameter() + let retainedPayload1 = Self.bridgeJSRetainPayloadIfNeeded(kind: lowered.kind, payload1: lowered.payload1) + _swift_js_push_i32(lowered.kind) + _swift_js_push_i32(retainedPayload1) + _swift_js_push_f64(lowered.payload2) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (kind: Int32, payload1: Int32, payload2: Double) { + return withRawJSValue { raw in + ( + kind: Int32(raw.kind.rawValue), + payload1: Int32(bitPattern: raw.payload1), + payload2: raw.payload2 + ) + } + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ kind: Int32, + _ payload1: Int32, + _ payload2: Double + ) -> JSValue { + let retainedPayload1 = bridgeJSRetainPayloadIfNeeded(kind: kind, payload1: payload1) + + guard let kindEnum = JavaScriptValueKind(rawValue: UInt32(kind)) else { + fatalError("Invalid JSValue kind: \(kind)") + } + let rawValue = RawJSValue( + kind: kindEnum, + payload1: JavaScriptPayload1(UInt32(bitPattern: retainedPayload1)), + payload2: payload2 + ) + return rawValue.jsValue + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> JSValue { + bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + bridgeJSStackPush() + } } /// A protocol that Swift heap objects exposed to JavaScript via `@JS class` must conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftHeapObject: AnyObject {} +public protocol _BridgedSwiftHeapObject: AnyObject, _BridgedSwiftStackType {} /// Define the lowering/lifting for `_BridgedSwiftHeapObject` extension _BridgedSwiftHeapObject { @@ -264,6 +484,13 @@ extension _BridgedSwiftHeapObject { // Perform a manual retain on the object, which will be balanced by a release called via FinalizationRegistry return Unmanaged.passRetained(self).toOpaque() } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSLiftParameter(_swift_js_pop_pointer()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_pointer(Unmanaged.passRetained(self).toOpaque()) + } } // MARK: Closure Box Protocol @@ -283,19 +510,29 @@ extension _JSBridgedClass { @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ id: Int32) -> Self { Self(unsafelyWrapping: JSObject.bridgeJSLiftParameter(id)) } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { jsObject.bridgeJSLowerReturn() } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(bridgeJSLowerReturn()) + } } /// A protocol that Swift protocol wrappers exposed from JavaScript must conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftProtocolWrapper { +public protocol _BridgedSwiftProtocolWrapper: _BridgedSwiftStackType { var jsObject: JSObject { get } static func bridgeJSLiftParameter(_ value: Int32) -> Self } extension _BridgedSwiftProtocolWrapper { // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { + bridgeJSStackPop() + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { jsObject.bridgeJSLowerReturn() } @@ -303,6 +540,14 @@ extension _BridgedSwiftProtocolWrapper { @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { jsObject.bridgeJSLowerParameter() } + + // MARK: Stack ABI + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(jsObject.bridgeJSLowerReturn()) + } } /// A protocol that Swift enum types that do not have a payload can conform to. @@ -310,10 +555,29 @@ extension _BridgedSwiftProtocolWrapper { /// The conformance is automatically synthesized by the BridgeJS code generator. public protocol _BridgedSwiftEnumNoPayload {} +/// A protocol for raw value enums that enables automatic stack operations. +/// +/// Conforming to this protocol provides default implementations of `_BridgedSwiftStackType` +/// methods by delegating to the raw value's stack operations. The raw value type must itself +/// conform to `_BridgedSwiftStackType`. +/// +/// The conformance is automatically synthesized by the BridgeJS code generator. +public protocol _BridgedSwiftRawValueEnum: _BridgedSwiftStackType, RawRepresentable +where RawValue: _BridgedSwiftStackType, RawValue.StackLiftResult == RawValue {} + +extension _BridgedSwiftRawValueEnum { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(rawValue: RawValue.bridgeJSStackPop())! + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + rawValue.bridgeJSStackPush() + } +} + /// A protocol that Swift case enum types (enums without raw values or associated values) conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftCaseEnum { +public protocol _BridgedSwiftCaseEnum: _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) consuming func bridgeJSLowerParameter() -> Int32 @_spi(BridgeJS) static func bridgeJSLiftReturn(_ value: Int32) -> Self @@ -323,26 +587,65 @@ public protocol _BridgedSwiftCaseEnum { @_spi(BridgeJS) consuming func bridgeJSLowerReturn() -> Int32 } +extension _BridgedSwiftCaseEnum { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSLiftParameter(_swift_js_pop_i32()) + } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(bridgeJSLowerReturn()) + } +} + /// A protocol that Swift associated value enum types conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftAssociatedValueEnum: _BridgedSwiftTypeLoweredIntoVoidType { - // MARK: ImportTS - @_spi(BridgeJS) consuming func bridgeJSLowerParameter() -> Int32 - @_spi(BridgeJS) static func bridgeJSLiftReturn(_ caseId: Int32) -> Self +public protocol _BridgedSwiftAssociatedValueEnum: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftStackType { + /// Pops the payload of the associated value enum from the stack. + /// + /// - Parameter caseId: The enum case ID. + /// - Returns: The associated value enum with its payload popped from the stack. + @_spi(BridgeJS) static func bridgeJSStackPopPayload(_ caseId: Int32) -> Self - // MARK: ExportSwift - @_spi(BridgeJS) static func bridgeJSLiftParameter(_ caseId: Int32) -> Self - @_spi(BridgeJS) consuming func bridgeJSLowerReturn() -> Void + /// Pushes the payload of the associated value enum onto the stack. + /// + /// - Returns: The enum case ID. + @_spi(BridgeJS) consuming func bridgeJSStackPushPayload() -> Int32 +} + +extension _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSStackPopPayload(_swift_js_pop_i32()) + } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_i32(bridgeJSStackPushPayload()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ caseId: Int32) -> Self { + return bridgeJSStackPopPayload(caseId) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + bridgeJSStackPush() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSStackPushPayload() + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { + return bridgeJSStackPopPayload(caseId) + } } /// A protocol that Swift struct types conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. -public protocol _BridgedSwiftStruct: _BridgedSwiftTypeLoweredIntoVoidType { +public protocol _BridgedSwiftStruct: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftGenericOptionalStackType { // MARK: ExportSwift - @_spi(BridgeJS) static func bridgeJSLiftParameter() -> Self - @_spi(BridgeJS) consuming func bridgeJSLowerReturn() -> Void + @_spi(BridgeJS) static func bridgeJSStackPop() -> Self + @_spi(BridgeJS) consuming func bridgeJSStackPush() -> Void /// Initializes a Swift struct by copying the fields from a bridged JS object. init(unsafelyCopying jsObject: JSObject) @@ -359,6 +662,13 @@ extension _BridgedSwiftStruct { let jsObject = JSObject.bridgeJSLiftReturn(objectId) return Self(unsafelyCopying: jsObject) } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { + bridgeJSStackPop() + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + bridgeJSStackPush() + } } extension _BridgedSwiftEnumNoPayload where Self: RawRepresentable, RawValue == String { @@ -399,95 +709,114 @@ where Self: RawRepresentable, RawValue: _BridgedSwiftTypeLoweredIntoSingleWasmCo #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_init_memory") -@_spi(BridgeJS) public func _swift_js_init_memory(_ sourceId: Int32, _ ptr: UnsafeMutablePointer) +private func _swift_js_init_memory_extern(_ sourceId: Int32, _ ptr: UnsafeMutablePointer) #else -@_spi(BridgeJS) public func _swift_js_init_memory(_ sourceId: Int32, _ ptr: UnsafeMutablePointer) { +private func _swift_js_init_memory_extern(_ sourceId: Int32, _ ptr: UnsafeMutablePointer) { _onlyAvailableOnWasm() } #endif -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_push_tag") -@_spi(BridgeJS) public func _swift_js_push_tag(_ tag: Int32) -#else -@_spi(BridgeJS) public func _swift_js_push_tag(_ tag: Int32) { - _onlyAvailableOnWasm() +/// Initializes WebAssembly memory with a Uint8Array referenced by `sourceId` at `ptr`. +/// Note that the ownership of the source Uint8Array id is taken by the callee, so callers +/// must not release the source Uint8Array id by themselves. +/// +/// - Parameter sourceId: The object ID of the source Uint8Array. +/// - Parameter ptr: The pointer to the WebAssembly memory to initialize. +@_spi(BridgeJS) @inline(never) public func _swift_js_init_memory(_ sourceId: Int32, _ ptr: UnsafeMutablePointer) +{ + _swift_js_init_memory_extern(sourceId, ptr) } -#endif #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_string") -@_spi(BridgeJS) public func _swift_js_push_string(_ ptr: UnsafePointer?, _ len: Int32) +private func _swift_js_push_string_extern(_ ptr: UnsafePointer?, _ len: Int32) #else -@_spi(BridgeJS) public func _swift_js_push_string(_ ptr: UnsafePointer?, _ len: Int32) { +private func _swift_js_push_string_extern(_ ptr: UnsafePointer?, _ len: Int32) { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_string(_ ptr: UnsafePointer?, _ len: Int32) { + _swift_js_push_string_extern(ptr, len) +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_i32") -@_spi(BridgeJS) public func _swift_js_push_i32(_ value: Int32) +private func _swift_js_push_i32_extern(_ value: Int32) #else -@_spi(BridgeJS) public func _swift_js_push_i32(_ value: Int32) { +private func _swift_js_push_i32_extern(_ value: Int32) { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_i32(_ value: Int32) { + _swift_js_push_i32_extern(value) +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_f32") -@_spi(BridgeJS) public func _swift_js_push_f32(_ value: Float32) +private func _swift_js_push_f32_extern(_ value: Float32) #else -@_spi(BridgeJS) public func _swift_js_push_f32(_ value: Float32) { +private func _swift_js_push_f32_extern(_ value: Float32) { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_f32(_ value: Float32) { + _swift_js_push_f32_extern(value) +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_f64") -@_spi(BridgeJS) public func _swift_js_push_f64(_ value: Float64) +private func _swift_js_push_f64_extern(_ value: Float64) #else -@_spi(BridgeJS) public func _swift_js_push_f64(_ value: Float64) { +private func _swift_js_push_f64_extern(_ value: Float64) { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_f64(_ value: Float64) { + _swift_js_push_f64_extern(value) +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_pop_i32") -@_spi(BridgeJS) public func _swift_js_pop_i32() -> Int32 +private func _swift_js_pop_i32_extern() -> Int32 #else -@_spi(BridgeJS) public func _swift_js_pop_i32() -> Int32 { +private func _swift_js_pop_i32_extern() -> Int32 { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_pop_i32() -> Int32 { + _swift_js_pop_i32_extern() +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_pop_f32") -@_spi(BridgeJS) public func _swift_js_pop_f32() -> Float32 +private func _swift_js_pop_f32_extern() -> Float32 #else -@_spi(BridgeJS) public func _swift_js_pop_f32() -> Float32 { +private func _swift_js_pop_f32_extern() -> Float32 { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_pop_f32() -> Float32 { + _swift_js_pop_f32_extern() +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_pop_f64") -@_spi(BridgeJS) public func _swift_js_pop_f64() -> Float64 +private func _swift_js_pop_f64_extern() -> Float64 #else -@_spi(BridgeJS) public func _swift_js_pop_f64() -> Float64 { +private func _swift_js_pop_f64_extern() -> Float64 { _onlyAvailableOnWasm() } #endif -// MARK: Struct bridging helpers (JS-side lowering/raising) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_cleanup") -@_spi(BridgeJS) public func _swift_js_struct_cleanup(_ cleanupId: Int32) -#else -@_spi(BridgeJS) public func _swift_js_struct_cleanup(_ cleanupId: Int32) { - _onlyAvailableOnWasm() +@_spi(BridgeJS) @inline(never) public func _swift_js_pop_f64() -> Float64 { + _swift_js_pop_f64_extern() } -#endif // MARK: Wasm externs used by type lowering/lifting @@ -676,288 +1005,301 @@ func _swift_js_return_optional_double(_ isSome: Int32, _ value: Float64) { #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_push_pointer") -@_spi(BridgeJS) public func _swift_js_push_pointer(_ pointer: UnsafeMutableRawPointer) +private func _swift_js_push_pointer_extern(_ pointer: UnsafeMutableRawPointer) #else -@_spi(BridgeJS) public func _swift_js_push_pointer(_ pointer: UnsafeMutableRawPointer) { +private func _swift_js_push_pointer_extern(_ pointer: UnsafeMutableRawPointer) { _onlyAvailableOnWasm() } #endif +@_spi(BridgeJS) @inline(never) public func _swift_js_push_pointer(_ pointer: UnsafeMutableRawPointer) { + _swift_js_push_pointer_extern(pointer) +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_pop_pointer") -@_spi(BridgeJS) public func _swift_js_pop_pointer() -> UnsafeMutableRawPointer +private func _swift_js_pop_pointer_extern() -> UnsafeMutableRawPointer #else -@_spi(BridgeJS) public func _swift_js_pop_pointer() -> UnsafeMutableRawPointer { +private func _swift_js_pop_pointer_extern() -> UnsafeMutableRawPointer { _onlyAvailableOnWasm() } #endif -// MARK: - UnsafePointer family +@_spi(BridgeJS) @inline(never) public func _swift_js_pop_pointer() -> UnsafeMutableRawPointer { + _swift_js_pop_pointer_extern() +} -extension UnsafeMutableRawPointer { - // MARK: ImportTS - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { self } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn( - _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeMutableRawPointer - { - pointer - } +// MARK: - UnsafePointer family - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( - _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeMutableRawPointer - { - pointer - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { self } +public protocol _BridgedSwiftUnsafePointerLike: _BridgedSwiftStackType { + @_spi(BridgeJS) func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer + @_spi(BridgeJS) static func bridgeJSFromUnsafeMutableRawPointer(_ pointer: UnsafeMutableRawPointer) -> Self } -extension UnsafeRawPointer { +extension _BridgedSwiftUnsafePointerLike { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { - UnsafeMutableRawPointer(mutating: self) + bridgeJSToUnsafeMutableRawPointer() } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn( - _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeRawPointer - { - UnsafeRawPointer(pointer) + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ pointer: UnsafeMutableRawPointer) -> Self { + bridgeJSFromUnsafeMutableRawPointer(pointer) } // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( - _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeRawPointer - { - UnsafeRawPointer(pointer) + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ pointer: UnsafeMutableRawPointer) -> Self { + bridgeJSFromUnsafeMutableRawPointer(pointer) + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeJSLiftParameter(_swift_js_pop_pointer()) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { - bridgeJSLowerParameter() + bridgeJSToUnsafeMutableRawPointer() + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + _swift_js_push_pointer(bridgeJSToUnsafeMutableRawPointer()) } } -extension OpaquePointer { - // MARK: ImportTS - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { - UnsafeMutableRawPointer(mutating: UnsafeRawPointer(self)) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn( +extension UnsafeMutableRawPointer: _BridgedSwiftUnsafePointerLike { + @_spi(BridgeJS) @_transparent public func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer { self } + @_spi(BridgeJS) @_transparent public static func bridgeJSFromUnsafeMutableRawPointer( _ pointer: UnsafeMutableRawPointer - ) - -> OpaquePointer - { - OpaquePointer(UnsafeRawPointer(pointer)) + ) -> UnsafeMutableRawPointer { + pointer } +} - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( - _ pointer: UnsafeMutableRawPointer - ) - -> OpaquePointer - { - OpaquePointer(UnsafeRawPointer(pointer)) +extension UnsafeRawPointer: _BridgedSwiftUnsafePointerLike { + @_spi(BridgeJS) @_transparent public func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer { + UnsafeMutableRawPointer(mutating: self) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { - bridgeJSLowerParameter() + @_spi(BridgeJS) @_transparent public static func bridgeJSFromUnsafeMutableRawPointer( + _ pointer: UnsafeMutableRawPointer + ) -> UnsafeRawPointer { + UnsafeRawPointer(pointer) } } -extension UnsafePointer { - // MARK: ImportTS - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { +extension OpaquePointer: _BridgedSwiftUnsafePointerLike { + @_spi(BridgeJS) @_transparent public func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer { UnsafeMutableRawPointer(mutating: UnsafeRawPointer(self)) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn( + @_spi(BridgeJS) @_transparent public static func bridgeJSFromUnsafeMutableRawPointer( _ pointer: UnsafeMutableRawPointer - ) - -> UnsafePointer - { - UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self) + ) -> OpaquePointer { + OpaquePointer(UnsafeRawPointer(pointer)) } +} - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( +extension UnsafePointer: _BridgedSwiftUnsafePointerLike { + @_spi(BridgeJS) @_transparent public func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer { + UnsafeMutableRawPointer(mutating: UnsafeRawPointer(self)) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSFromUnsafeMutableRawPointer( _ pointer: UnsafeMutableRawPointer - ) - -> UnsafePointer - { + ) -> UnsafePointer { UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { - bridgeJSLowerParameter() - } } -extension UnsafeMutablePointer { - // MARK: ImportTS - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { +extension UnsafeMutablePointer: _BridgedSwiftUnsafePointerLike { + @_spi(BridgeJS) @_transparent public func bridgeJSToUnsafeMutableRawPointer() -> UnsafeMutableRawPointer { UnsafeMutableRawPointer(self) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn( - _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeMutablePointer - { - pointer.assumingMemoryBound(to: Pointee.self) - } - - // MARK: ExportSwift - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter( + @_spi(BridgeJS) @_transparent public static func bridgeJSFromUnsafeMutableRawPointer( _ pointer: UnsafeMutableRawPointer - ) - -> UnsafeMutablePointer - { + ) -> UnsafeMutablePointer { pointer.assumingMemoryBound(to: Pointee.self) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { - bridgeJSLowerParameter() - } } -extension Optional where Wrapped == Bool { - // MARK: ImportTS - - @available(*, unavailable, message: "Optional Bool type is not supported to be passed to imported JS functions") - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Void {} - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( +// Optional support for JSTypedClosure +extension Optional { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Int32 - ) { + ) where Wrapped == JSTypedClosure { switch consume self { case .none: return (isSome: 0, value: 0) case .some(let wrapped): + // Use return lowering to retain the JS function so JS lifting can fetch it from the heap. return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) } } +} - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Bool? { - if isSome == 0 { - return nil - } else { - return Bool.bridgeJSLiftParameter(wrappedValue) +extension Optional { + @usableFromInline @_transparent func _bridgeJSLowerParameter( + noneValue: Payload, + lowerWrapped: (Wrapped) -> Payload + ) -> (isSome: Int32, value: Payload) { + switch self { + case .none: + return (isSome: 0, value: noneValue) + case .some(let wrapped): + return (isSome: 1, value: lowerWrapped(wrapped)) } } - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Bool? { - switch value { - case -1: + @usableFromInline @_transparent static func _bridgeJSLiftParameter( + _ isSome: Int32, + _ payload: Payload, + liftWrapped: (Payload) -> Wrapped + ) -> Wrapped? { + if isSome == 0 { return nil - case 0: - return false - case 1: - return true - default: - return nil // Treat invalid values as null } + return liftWrapped(payload) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { + @usableFromInline @_transparent func _bridgeJSLowerReturn( + noneValue: Payload, + lowerWrapped: (Wrapped) -> Payload, + write: (Int32, Payload) -> Void + ) { + switch self { case .none: - _swift_js_return_optional_bool(0, 0) - case .some(let value): - _swift_js_return_optional_bool(1, value.bridgeJSLowerReturn()) + write(0, noneValue) + case .some(let wrapped): + write(1, lowerWrapped(wrapped)) } } } -extension Optional where Wrapped == Int { - // MARK: ImportTS +public protocol _BridgedSwiftOptionalScalarBridge: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { + @_spi(BridgeJS) static func bridgeJSPopOptionalScalarPayload() -> WasmCoreType + @_spi(BridgeJS) static var bridgeJSOptionalScalarNonePayload: WasmCoreType { get } + @_spi(BridgeJS) static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: WasmCoreType) +} - @available(*, unavailable, message: "Optional Int type is not supported to be passed to imported JS functions") - @_spi(BridgeJS) public func bridgeJSLowerParameter() -> Void {} +public protocol _BridgedSwiftOptionalScalarSideChannelBridge: _BridgedSwiftOptionalScalarBridge { + @_spi(BridgeJS) static func bridgeJSReadOptionalSideChannelPresence() -> Int32 + @_spi(BridgeJS) static func bridgeJSReadOptionalSideChannelPayload() -> WasmCoreType +} - // MARK: ExportSwift +extension Bool: _BridgedSwiftOptionalScalarBridge { + @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } + @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } + @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { + _swift_js_return_optional_bool(isSome, value) + } +} + +extension Int: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } + @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } + @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { + _swift_js_return_optional_int(isSome, value) + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPresence() -> Int32 { + _swift_js_get_optional_int_presence() + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPayload() -> Int32 { + _swift_js_get_optional_int_value() + } +} + +extension UInt: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Int32 { _swift_js_pop_i32() } + @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Int32 { 0 } + @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Int32) { + _swift_js_return_optional_int(isSome, value) + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPresence() -> Int32 { + _swift_js_get_optional_int_presence() + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPayload() -> Int32 { + _swift_js_get_optional_int_value() + } +} + +extension Float: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Float32 { _swift_js_pop_f32() } + @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Float32 { 0.0 } + @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Float32) { + _swift_js_return_optional_float(isSome, value) + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPresence() -> Int32 { + _swift_js_get_optional_float_presence() + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPayload() -> Float32 { + _swift_js_get_optional_float_value() + } +} + +extension Double: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSPopOptionalScalarPayload() -> Float64 { _swift_js_pop_f64() } + @_spi(BridgeJS) public static var bridgeJSOptionalScalarNonePayload: Float64 { 0.0 } + @_spi(BridgeJS) public static func bridgeJSWriteOptionalReturn(_ isSome: Int32, _ value: Float64) { + _swift_js_return_optional_double(isSome, value) + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPresence() -> Int32 { + _swift_js_get_optional_double_presence() + } + @_spi(BridgeJS) public static func bridgeJSReadOptionalSideChannelPayload() -> Float64 { + _swift_js_get_optional_double_value() + } +} +extension Optional where Wrapped: _BridgedSwiftOptionalScalarBridge { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Int32 + isSome: Int32, value: Wrapped.WasmCoreType ) { switch consume self { case .none: - return (isSome: 0, value: 0) + return (isSome: 0, value: Wrapped.bridgeJSOptionalScalarNonePayload) case .some(let wrapped): return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Int? { + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ wrappedValue: Wrapped.WasmCoreType + ) -> Wrapped? { if isSome == 0 { return nil - } else { - return Int.bridgeJSLiftParameter(wrappedValue) } + return Wrapped.bridgeJSLiftParameter(wrappedValue) } - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Int? { - let isSome = _swift_js_get_optional_int_presence() - if isSome == 0 { - return nil - } else { - return Int.bridgeJSLiftReturn(_swift_js_get_optional_int_value()) - } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = Wrapped.bridgeJSPopOptionalScalarPayload() + return bridgeJSLiftParameter(isSome, wrappedValue) } - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { - switch self { + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + switch consume self { case .none: - _swift_js_return_optional_int(0, 0) + Wrapped.bridgeJSWriteOptionalReturn(0, Wrapped.bridgeJSOptionalScalarNonePayload) case .some(let value): - _swift_js_return_optional_int(1, value.bridgeJSLowerReturn()) + Wrapped.bridgeJSWriteOptionalReturn(1, value.bridgeJSLowerReturn()) } } } -extension Optional where Wrapped == UInt { - // MARK: ImportTS - - @available(*, unavailable, message: "Optional UInt type is not supported to be passed to imported JS functions") - @_spi(BridgeJS) public func bridgeJSLowerParameter() -> Void {} - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameterWithPresence() -> ( - isSome: Int32, value: Int32 - ) { - switch consume self { - case .none: - return (isSome: 0, value: 0) - case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> UInt? { +extension Optional where Wrapped: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { + let isSome = Wrapped.bridgeJSReadOptionalSideChannelPresence() if isSome == 0 { return nil - } else { - return UInt.bridgeJSLiftParameter(wrappedValue) } + return Wrapped.bridgeJSLiftReturn(Wrapped.bridgeJSReadOptionalSideChannelPayload()) } +} - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> UInt? { - let isSome = _swift_js_get_optional_int_presence() - if isSome == 0 { +extension Optional where Wrapped == Bool { + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Bool? { + switch value { + case -1: return nil - } else { - return UInt.bridgeJSLiftReturn(_swift_js_get_optional_int_value()) - } - } - - @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { - switch self { - case .none: - _swift_js_return_optional_int(0, 0) - case .some(let value): - _swift_js_return_optional_int(1, value.bridgeJSLowerReturn()) + case 0: + return false + case 1: + return true + default: + return nil // Treat invalid values as null } } } @@ -967,21 +1309,19 @@ extension Optional where Wrapped == String { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Int32 ) { - switch consume self { - case .none: - return (isSome: 0, value: 0) - case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) - } + _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) } @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ bytes: Int32, _ count: Int32) -> String? { - if isSome == 0 { - return nil - } else { - return String.bridgeJSLiftParameter(bytes, count) - } + _bridgeJSLiftParameter(isSome, (bytes, count), liftWrapped: { String.bridgeJSLiftParameter($0.0, $0.1) }) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> String? { + let isSome = _swift_js_pop_i32() + let bytes = _swift_js_pop_i32() + let count = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, bytes, count) } @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> String? { @@ -1009,51 +1349,136 @@ extension Optional where Wrapped == JSObject { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( isSome: Int32, value: Int32 + ) { + _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> JSObject? { + _bridgeJSLiftParameter(isSome, objectId, liftWrapped: JSObject.bridgeJSLiftParameter) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> JSObject? { + let isSome = _swift_js_pop_i32() + let objectId = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, objectId) + } + + @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { + _bridgeJSLowerReturn( + noneValue: 0, + lowerWrapped: { $0.bridgeJSLowerReturn() }, + write: _swift_js_return_optional_object + ) + } +} + +extension Optional where Wrapped == JSValue { + // MARK: ExportSwift + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, kind: Int32, payload1: Int32, payload2: Double ) { switch consume self { case .none: - return (isSome: 0, value: 0) + return (isSome: 0, kind: 0, payload1: 0, payload2: 0) case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) + let lowered = wrapped.bridgeJSLowerParameter() + return ( + isSome: 1, + kind: lowered.kind, + payload1: lowered.payload1, + payload2: lowered.payload2 + ) } } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> JSObject? { + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ kind: Int32, + _ payload1: Int32, + _ payload2: Double + ) -> JSValue? { if isSome == 0 { return nil } else { - return JSObject.bridgeJSLiftParameter(objectId) + return JSValue.bridgeJSLiftParameter(kind, payload1, payload2) + } + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> JSValue? { + let isSome = _swift_js_pop_i32() + if isSome == 0 { + return nil } + let payload2 = _swift_js_pop_f64() + let payload1 = _swift_js_pop_i32() + let kind = _swift_js_pop_i32() + return JSValue.bridgeJSLiftParameter(kind, payload1, payload2) } @_spi(BridgeJS) public func bridgeJSLowerReturn() -> Void { switch self { case .none: - _swift_js_return_optional_object(0, 0) + _swift_js_push_i32(0) case .some(let value): - let retainedId = value.bridgeJSLowerReturn() - _swift_js_return_optional_object(1, retainedId) + value.bridgeJSLowerReturn() + _swift_js_push_i32(1) } } } -extension Optional where Wrapped: _BridgedSwiftProtocolWrapper { +extension Optional where Wrapped == [JSValue] { // MARK: ExportSwift - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Wrapped? { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + switch consume self { + case .none: + return 0 + case .some(let array): + array.bridgeJSLowerReturn() + return 1 + } + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> [JSValue]? { if isSome == 0 { return nil - } else { - return Wrapped.bridgeJSLiftParameter(objectId) + } + return [JSValue].bridgeJSLiftParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [JSValue]? { + let isSome = _swift_js_pop_i32() + if isSome == 0 { + return nil + } + return [JSValue].bridgeJSLiftReturn() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + switch consume self { + case .none: + _swift_js_push_i32(0) + case .some(let array): + array.bridgeJSLowerReturn() + _swift_js_push_i32(1) } } +} + +extension Optional where Wrapped: _BridgedSwiftProtocolWrapper { + // MARK: ExportSwift + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Wrapped? { + _bridgeJSLiftParameter(isSome, objectId, liftWrapped: Wrapped.bridgeJSLiftParameter) + } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { switch consume self { case .none: _swift_js_return_optional_object(0, 0) case .some(let wrapper): - let retainedId = wrapper.bridgeJSLowerReturn() + let retainedId: Int32 = wrapper.bridgeJSLowerReturn() _swift_js_return_optional_object(1, retainedId) } } @@ -1114,11 +1539,13 @@ extension Optional where Wrapped: _BridgedSwiftHeapObject { _ isSome: Int32, _ pointer: UnsafeMutableRawPointer ) -> Optional { - if isSome == 0 { - return nil - } else { - return Wrapped.bridgeJSLiftParameter(pointer) - } + _bridgeJSLiftParameter(isSome, pointer, liftWrapped: Wrapped.bridgeJSLiftParameter) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let pointer = _swift_js_pop_pointer() + return bridgeJSLiftParameter(isSome, pointer) } @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { @@ -1135,113 +1562,27 @@ extension Optional where Wrapped: _BridgedSwiftHeapObject { case .none: _swift_js_return_optional_heap_object(0, nil) case .some(let value): - let retainedPointer = value.bridgeJSLowerReturn() + let retainedPointer: UnsafeMutableRawPointer = value.bridgeJSLowerReturn() _swift_js_return_optional_heap_object(1, retainedPointer) } } } -extension Optional where Wrapped == Float { - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Float32 - ) { - switch consume self { - case .none: - return (isSome: 0, value: 0.0) - case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Float? { - if isSome == 0 { - return nil - } else { - return Float.bridgeJSLiftParameter(wrappedValue) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Float? { - let isSome = _swift_js_get_optional_float_presence() - if isSome == 0 { - return nil - } else { - return Float.bridgeJSLiftReturn(_swift_js_get_optional_float_value()) - } - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { - case .none: - _swift_js_return_optional_float(0, 0.0) - case .some(let value): - _swift_js_return_optional_float(1, value.bridgeJSLowerReturn()) - } - } -} - -/// Optional support for Double -extension Optional where Wrapped == Double { - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> ( - isSome: Int32, value: Float64 - ) { - switch consume self { - case .none: - return (isSome: 0, value: 0.0) - case .some(let wrapped): - return (isSome: 1, value: wrapped.bridgeJSLowerParameter()) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Double? { - if isSome == 0 { - return nil - } else { - return Double.bridgeJSLiftParameter(wrappedValue) - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Double? { - let isSome = _swift_js_get_optional_double_presence() - if isSome == 0 { - return nil - } else { - return Double.bridgeJSLiftReturn(_swift_js_get_optional_double_value()) - } - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { - case .none: - _swift_js_return_optional_double(0, 0.0) - case .some(let value): - _swift_js_return_optional_double(1, value.bridgeJSLowerReturn()) - } - } -} - /// Optional support for case enums extension Optional where Wrapped: _BridgedSwiftCaseEnum { // MARK: ExportSwift @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { - switch consume self { - case .none: - return (isSome: 0, value: 0) - case .some(let value): - return (isSome: 1, value: value.bridgeJSLowerParameter()) - } + _bridgeJSLowerParameter(noneValue: 0, lowerWrapped: { $0.bridgeJSLowerParameter() }) } @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Wrapped? { - if isSome == 0 { - return nil - } else { - return Wrapped.bridgeJSLiftParameter(wrappedValue) - } + _bridgeJSLiftParameter(isSome, wrappedValue, liftWrapped: Wrapped.bridgeJSLiftParameter) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, wrappedValue) } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Wrapped? { @@ -1253,12 +1594,11 @@ extension Optional where Wrapped: _BridgedSwiftCaseEnum { } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { - case .none: - _swift_js_return_optional_int(0, 0) - case .some(let value): - _swift_js_return_optional_int(1, value.bridgeJSLowerReturn()) - } + _bridgeJSLowerReturn( + noneValue: 0, + lowerWrapped: { $0.bridgeJSLowerReturn() }, + write: _swift_js_return_optional_int + ) } } @@ -1267,17 +1607,6 @@ public protocol _BridgedSwiftTypeLoweredIntoVoidType { consuming func bridgeJSLowerReturn() -> Void } -extension Optional where Wrapped: _BridgedSwiftTypeLoweredIntoVoidType { - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - switch consume self { - case .none: - () - case .some(let value): - value.bridgeJSLowerReturn() - } - } -} - // MARK: Optional Raw Value Enum Support extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { @@ -1317,6 +1646,12 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres let optionalRawValue: String? = self?.rawValue optionalRawValue.bridgeJSLowerReturn() } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let bytes = _swift_js_pop_i32() + let count = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, bytes, count) + } } extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { @@ -1335,6 +1670,12 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, wrappedValue) + } + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_int_presence() if isSome == 0 { @@ -1359,6 +1700,12 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, wrappedValue) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { let optionalRawValue: Bool? = self?.rawValue optionalRawValue.bridgeJSLowerReturn() @@ -1384,6 +1731,12 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = _swift_js_pop_f32() + return bridgeJSLiftParameter(isSome, wrappedValue) + } + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_float_presence() if isSome == 0 { @@ -1419,6 +1772,12 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres return optionalRawValue.flatMap { Wrapped(rawValue: $0) } } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let wrappedValue = _swift_js_pop_f64() + return bridgeJSLiftParameter(isSome, wrappedValue) + } + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Wrapped? { let isSome = _swift_js_get_optional_double_presence() if isSome == 0 { @@ -1438,11 +1797,27 @@ extension Optional where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepres // MARK: Optional Associated Value Enum Support extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { - // MARK: ExportSwift - - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { - switch consume self { - case .none: + private static func bridgeJSStackPopPayload(_ discriminant: Int32) -> Wrapped? { + if discriminant == -1 { + return nil + } else { + return Wrapped.bridgeJSStackPopPayload(discriminant) + } + } + private consuming func bridgeJSStackPushPayload() -> Int32 { + switch consume self { + case .none: + return -1 + case .some(let value): + return value.bridgeJSStackPushPayload() + } + } + + // MARK: ExportSwift + + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { + switch consume self { + case .none: return (isSome: 0, caseId: 0) case .some(let value): return (isSome: 1, caseId: value.bridgeJSLowerParameter()) @@ -1458,19 +1833,25 @@ extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { } @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Wrapped? { - if caseId == -1 { - return nil - } else { - return Wrapped.bridgeJSLiftReturn(caseId) - } + return bridgeJSStackPopPayload(caseId) } - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + bridgeJSStackPush() + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + let caseId = _swift_js_pop_i32() + return bridgeJSLiftParameter(isSome, caseId) + } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() -> Void { switch consume self { case .none: - _swift_js_push_tag(-1) // Use -1 as sentinel for null + _swift_js_push_i32(-1) // Use -1 as sentinel for null case .some(let value): - value.bridgeJSLowerReturn() + value.bridgeJSStackPush() } } } @@ -1478,23 +1859,508 @@ extension Optional where Wrapped: _BridgedSwiftAssociatedValueEnum { // MARK: Optional Struct Support extension Optional where Wrapped: _BridgedSwiftStruct { - // MARK: ExportSwift - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Wrapped? { if isSome == 0 { return nil } else { - return Wrapped.bridgeJSLiftParameter() + return Wrapped.bridgeJSStackPop() } } + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Wrapped? { + return bridgeJSStackPop() + } +} - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { +// MARK: - Generic Optional Stack Support + +/// Marker protocol for types whose Optional wrapper should use the generic +/// stack-based ABI (`_BridgedSwiftStackType`). Only Array, Dictionary, and +/// `_BridgedSwiftStruct` conform. Primitives and other types keep their +/// own type-specific Optional extensions. +public protocol _BridgedSwiftGenericOptionalStackType: _BridgedSwiftStackType +where StackLiftResult == Self {} + +extension Optional: _BridgedSwiftStackType +where Wrapped: _BridgedSwiftGenericOptionalStackType { + public typealias StackLiftResult = Wrapped? + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Wrapped? { + let isSome = _swift_js_pop_i32() + if isSome == 0 { + return nil + } + return Wrapped.bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { switch consume self { case .none: - _swift_js_push_i32(0) // Push only isSome=0 (no struct fields) + _swift_js_push_i32(0) case .some(let value): - value.bridgeJSLowerReturn() // Push all struct fields FIRST - _swift_js_push_i32(1) // Then push isSome=1 LAST (so it's popped FIRST by JS) + value.bridgeJSStackPush() + _swift_js_push_i32(1) + } + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Wrapped? { + return bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + bridgeJSStackPush() + } +} + +// MARK: - _BridgedAsOptional (JSUndefinedOr) delegating to Optional + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarBridge { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Wrapped.WasmCoreType + ) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ wrappedValue: Wrapped.WasmCoreType + ) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } +} + +extension _BridgedAsOptional where Wrapped == Bool { + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftReturn(value)) + } +} + +extension _BridgedAsOptional where Wrapped == String { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ bytes: Int32, + _ count: Int32 + ) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped == JSObject { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, objectId)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftProtocolWrapper { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, objectId)) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftHeapObject { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, pointer: UnsafeMutableRawPointer) + { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerParameterWithRetain() -> ( + isSome: Int32, pointer: UnsafeMutableRawPointer + ) { + asOptional.bridgeJSLowerParameterWithRetain() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ pointer: UnsafeMutableRawPointer + ) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, pointer)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftReturn(caseId)) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == String { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ bytes: Int32, + _ count: Int32 + ) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Int { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Bool { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Float { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Float32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftEnumNoPayload, Wrapped: RawRepresentable, Wrapped.RawValue == Double { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, value: Float64) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ wrappedValue: Float64) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, wrappedValue)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel()) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (isSome: Int32, caseId: Int32) { + asOptional.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ caseId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, caseId)) + } + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ caseId: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftReturn(caseId)) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + asOptional.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftStruct { + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome)) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() + } + + // MARK: Stack ABI + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + Self(optional: Optional.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + asOptional.bridgeJSStackPush() + } +} + +// MARK: - Array Support + +extension Array: _BridgedSwiftGenericOptionalStackType +where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element {} +extension Array: _BridgedSwiftStackType where Element: _BridgedSwiftStackType, Element.StackLiftResult == Element { + public typealias StackLiftResult = [Element] + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> [Element] { + let count = Int(_swift_js_pop_i32()) + var result: [Element] = [] + result.reserveCapacity(count) + for _ in 0.. [Element] { + bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + self.bridgeJSStackPush() + } + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() { + self.bridgeJSStackPush() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [Element] { + bridgeJSStackPop() + } +} + +// MARK: - Dictionary Support + +public protocol _BridgedSwiftDictionaryStackType: _BridgedSwiftTypeLoweredIntoVoidType, + _BridgedSwiftGenericOptionalStackType +{ + associatedtype DictionaryValue: _BridgedSwiftStackType + where DictionaryValue.StackLiftResult == DictionaryValue +} + +extension Dictionary: _BridgedSwiftGenericOptionalStackType +where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value {} +extension Dictionary: _BridgedSwiftStackType +where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { + public typealias StackLiftResult = [String: Value] + // Lowering/return use stack-based encoding, so dictionary also behaves like a void-lowered type. + // Optional/JSUndefinedOr wrappers rely on this conformance to push an isSome flag and + // then delegate to the stack-based lowering defined below. + // swiftlint:disable:next type_name +} + +extension Dictionary: _BridgedSwiftTypeLoweredIntoVoidType, _BridgedSwiftDictionaryStackType +where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { + public typealias DictionaryValue = Value + + @_spi(BridgeJS) public static func bridgeJSStackPop() -> [String: Value] { + let count = Int(_swift_js_pop_i32()) + var result: [String: Value] = [:] + result.reserveCapacity(count) + for _ in 0.. [String: Value] { + bridgeJSStackPop() + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { + self.bridgeJSStackPush() + } + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() { + self.bridgeJSStackPush() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Value] { + bridgeJSStackPop() + } +} + +extension Optional where Wrapped: _BridgedSwiftDictionaryStackType { + typealias DictionaryValue = Wrapped.DictionaryValue + + private consuming func bridgeJSStackPushPayload() -> Int32 { + switch consume self { + case .none: + return 0 + case .some(let dict): + dict.bridgeJSStackPush() + return 1 + } + } + private static func bridgeJSStackPopPayload(_ isSome: Int32) -> [String: Wrapped.DictionaryValue]? { + if isSome == 0 { + return nil + } + return Dictionary.bridgeJSStackPop() + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSStackPushPayload() + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> [String: Wrapped.DictionaryValue]? { + return bridgeJSStackPopPayload(isSome) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> [String: Wrapped.DictionaryValue]? { + return bridgeJSStackPopPayload(_swift_js_pop_i32()) + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftDictionaryStackType { + typealias DictionaryValue = Wrapped.DictionaryValue + + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + let opt = asOptional + if let dict = opt { + dict.bridgeJSLowerReturn() + return 1 + } + return 0 + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { + let isSome = _swift_js_pop_i32() + if isSome == 0 { + return Self(optional: nil) + } + let value = Dictionary.bridgeJSLiftParameter() as! Wrapped + return Self(optional: value) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.bridgeJSLowerReturn() } } diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Ahead-of-Time-Code-Generation.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Ahead-of-Time-Code-Generation.md index ee6ac3047..776f6f577 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Ahead-of-Time-Code-Generation.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Ahead-of-Time-Code-Generation.md @@ -6,7 +6,7 @@ Learn how to improve build times by generating BridgeJS code ahead of time. > Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. -The BridgeJS build plugin automatically processes `@JS` annotations and TypeScript definitions during each build. While convenient, this can significantly increase build times for larger projects. To address this, JavaScriptKit provides a command plugin that lets you generate the bridge code ahead of time. +The BridgeJS build plugin automatically processes macro annotations and TypeScript definitions during each build. While convenient, this can significantly increase build times for larger projects. To address this, JavaScriptKit provides a command plugin that lets you generate the bridge code ahead of time. ## Using the Command Plugin @@ -54,7 +54,7 @@ $ echo "{}" > Sources/MyApp/bridge-js.config.json ### Step 3: Create Your Swift Code with @JS Annotations -Write your Swift code with `@JS` annotations as usual: +Write your Swift code with macro annotations as usual: ```swift import JavaScriptKit @@ -65,13 +65,13 @@ import JavaScriptKit @JS class Counter { private var count = 0 - + @JS init() {} - + @JS func increment() { count += 1 } - + @JS func getValue() -> Int { return count } @@ -104,14 +104,15 @@ swift package plugin bridge-js This command will: -1. Process all Swift files with `@JS` annotations +1. Process all Swift files with macro annotations 2. Process any TypeScript definition files 3. Generate Swift binding code in a `Generated` directory within your source folder For example, with a target named "MyApp", it will create: ``` -Sources/MyApp/Generated/BridgeJS.swift # Generated code for both exports and imports +Sources/MyApp/Generated/BridgeJS.swift # Glue code for both exports and imports +Sources/MyApp/Generated/BridgeJS.Macros.swift # Bridging interface generated from bridge-js.d.ts Sources/MyApp/Generated/JavaScript/BridgeJS.json # Unified skeleton JSON ``` @@ -173,4 +174,4 @@ git commit -m "Update generated BridgeJS code" 2. **Version Control**: Always commit the generated files if using the command plugin 3. **API Boundaries**: Try to stabilize your API boundaries to minimize regeneration 4. **Documentation**: Document your approach in your project README -5. **CI/CD**: If using the command plugin, consider verifying that generated code is up-to-date in CI +5. **CI/CD**: If using the command plugin, consider verifying that generated code is up-to-date in CI diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md index 78b5d2d37..604017aad 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Configuration.md @@ -42,7 +42,7 @@ Later files override settings from earlier files. This allows teams to commit a Controls whether exported Swift APIs are exposed to the JavaScript global namespace (`globalThis`). -When `true`, exported functions, classes, and namespaces are available via `globalThis` in JavaScript. When `false`, they are only available through the exports object returned by `createExports()`. +When `true`, exported functions, classes, and namespaces are available via `globalThis` in JavaScript. When `false`, they are only available through the exports object returned by `createExports()`. Using Exports provides better module isolation and support multiple WebAssembly instances in the same JavaScript context. Example: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/BridgeJS-Internals.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/BridgeJS-Internals.md new file mode 100644 index 000000000..b8589b49e --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/BridgeJS-Internals.md @@ -0,0 +1,11 @@ +# BridgeJS Internals + +Internal design, performance rationale, and low-level details for BridgeJS. + +## Overview + +This section is for maintainers and contributors who want to understand how BridgeJS works under the hood, why it is designed the way it is, and how it interacts with the JavaScript engine and ABI. + +## Topics + +- diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/Design-Rationale.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/Design-Rationale.md new file mode 100644 index 000000000..8bfc5d302 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/BridgeJS-Internals/Design-Rationale.md @@ -0,0 +1,38 @@ +# BridgeJS Design Rationale + +Why BridgeJS is faster than dynamic `JSObject`/`JSValue` APIs and how engine optimizations influence the design. + +## Overview + +BridgeJS generates **specialized** bridge code per exported or imported interface. That specialization, combined with stable call and property access patterns, allows JavaScript engines to optimize the boundary crossing much better than with generic dynamic code. This page explains the main performance rationale. + +## Why generated code is faster + +1. **Specialized code per interface** - Each bridged function or property gets its own glue path with known types. The engine does not need to handle arbitrary shapes or types at the call site. + +2. **Use of static type information** - The generator knows parameter and return types at compile time. It can avoid dynamic type checks and boxing where the dynamic API would require them. + +3. **IC-friendly access patterns** - Property and method accesses use stable, predictable shapes instead of a single generic subscript path. That keeps engine **inline caches (ICs)** effective instead of turning them **megamorphic**. + +## Inline caches (ICs) and megamorphic penalty + +JavaScript engines (and many other dynamic-language VMs) use **inline caches** at property and method access sites: they remember the object shape (e.g. “this property is at offset X”) so the next access with the same shape can take a fast path. + +- **Monomorphic** - One shape seen at a site → very fast, offset cached. +- **Polymorphic** - A few shapes → still fast, small dispatch in the IC. +- **Megamorphic** - Too many different shapes at the same site → the IC gives up and falls back to a generic property lookup, which is much slower. + +Engines typically allow only a small number of shapes per IC (e.g. on the order of a few) before marking the site megamorphic. + +## Why `JSObject` subscript is problematic + +`JSObject.subscript` (and similar dynamic property access) shares **one** code path for all property names and all object shapes. Every access goes through the same call site with varying keys and receiver shapes. That site therefore sees many different shapes and quickly becomes **megamorphic**, so the engine cannot cache property offsets and must do a generic lookup every time. + +So even if you cache the property name (e.g. with `CachedJSStrings`), you are still using the same generic subscript path; the call site stays megamorphic and pays the slow-path cost. + +BridgeJS avoids this by generating **separate** access paths per property or method. Each generated getter/setter or function call has a stable shape at the engine level, so the IC can stay monomorphic or polymorphic and the fast path is used. + +## What to read next + +- ABI and binary interface details will be documented in this section as they stabilize. +- For using BridgeJS in your app, see , , and . diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md new file mode 100644 index 000000000..ce1d9d555 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md @@ -0,0 +1,80 @@ +# Bringing Swift Closures to JavaScript + +Use ``JSTypedClosure`` to pass or return Swift closures to the JavaScript world with BridgeJS-with type safety and explicit lifetime management. + +## Overview + +``JSTypedClosure`` wraps a **Swift closure** so you can **pass it or return it to JavaScript** through BridgeJS. The closure lives in Swift; JavaScript receives a function that calls back into that closure when invoked. Use it when: + +- You **pass** a Swift closure as an argument to a JavaScript API (e.g. an ``JSFunction(jsName:from:)`` that takes a callback parameter). +- You **return** a Swift closure from Swift exported by ``JS(namespace:enumStyle:)`` so JavaScript can call it later. + +Unlike ``JSClosure``, which uses untyped ``JSValue`` arguments and return values, ``JSTypedClosure`` has a concrete **signature** (e.g. `(Int) -> Int` or `(String) -> Void`). BridgeJS generates the glue code for that signature, so you get compile-time type safety when crossing into the JS world. + +You **must call** ``JSTypedClosure/release()`` when the closure is no longer needed by JavaScript. After release, any attempt to invoke the closure from JavaScript throws an explicit JS exception. + +## Creating a JSTypedClosure + +BridgeJS generates an initializer for each closure signature used in your module. Wrap your Swift closure and pass or return it to JavaScript: + +```swift +import JavaScriptKit + +// Pass a Swift closure to a JS function that expects a callback (Int) -> Int +@JSFunction static func applyTransform(_ value: Int, _ transform: JSTypedClosure<(Int) -> Int>) throws(JSException) -> Int + +let double = JSTypedClosure<(Int) -> Int> { $0 * 2 } +defer { double.release() } +let result = try applyTransform(10, double) // 20 - JS calls back into Swift +``` + +You can pass or return typed closures with other signatures the same way: + +```swift +let sum = JSTypedClosure<(Int, Int) -> Int> { $0 + $1 } +defer { sum.release() } + +let log = JSTypedClosure<(String) -> Void> { print($0) } +defer { log.release() } +``` + +## Lifetime and release() + +A ``JSTypedClosure`` keeps the Swift closure alive and exposes a JavaScript function that calls into it. To avoid leaks and use-after-free: + +1. **Call `release()` exactly once** when the closure is no longer needed by JavaScript (e.g. when the callback is unregistered or the object that held it is released). +2. Prefer **`defer { closure.release() }`** right after creating the closure so cleanup runs when the current scope exits. +3. After `release()`, calling the closure from JavaScript throws an exception with a message that includes the file and line where the ``JSTypedClosure`` was created. + +A **FinalizationRegistry** on the JavaScript side may eventually release the Swift storage if you never call `release()`, but that is non-deterministic. Do not rely on it for timely cleanup. + +## Getting the underlying JavaScript function + +When you need to store or pass the function on the JavaScript side (e.g. to compare identity or attach to a DOM node), use the ``JSTypedClosure/jsObject`` property to get the ``JSObject`` that represents the JavaScript function. + +## JSTypedClosure vs JSClosure + +Both let you pass or return a Swift closure to the JavaScript world. The difference is how they are typed and which API you use: + +| | JSTypedClosure | JSClosure | +|:--|:--|:--| +| **API** | BridgeJS (macros, generated code) | Dynamic ``JSObject`` / ``JSValue`` | +| **Types** | Typed signature, e.g. `(Int) -> Int` | Untyped `([JSValue]) -> JSValue` | +| **Lifetime** | Explicit `release()` required | Explicit `release()` required | +| **Use case** | Passing/returning closures at the BridgeJS boundary with a fixed signature | Passing Swift functions to JS via dynamic APIs (e.g. DOM events) | + +Use ``JSTypedClosure`` when you pass or return closures through BridgeJS-declared APIs. Use ``JSClosure`` when you pass a Swift function to JavaScript using the dynamic APIs (e.g. ``JSObject``, ``JSValue``) without generated glue. + +## JSTypedClosure vs auto-managed closures + +BridgeJS can also expose **plain** Swift closure types (e.g. `(String) -> String`) as parameters and return values; lifetime is then managed automatically via ``FinalizationRegistry`` and no `release()` is required. See . + +**When returning** a closure from Swift to JavaScript, we **recommend** using ``JSTypedClosure`` and managing lifetime explicitly with `release()`, rather than returning a plain closure type. Explicit release makes cleanup predictable and avoids relying solely on JavaScript GC. + +## See also + +- ``JSTypedClosure`` +- ``JSClosure`` +- +- +- 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 75f0fcca5..b14d2eebe 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 @@ -6,60 +6,11 @@ Learn how to make your Swift code callable from JavaScript. > Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS allows you to expose Swift functions, classes, and methods to JavaScript by using the `@JS` attribute. This enables JavaScript code to call into Swift code running in WebAssembly. - -## Configuring the BridgeJS plugin - -To use the BridgeJS feature, you need to enable the experimental `Extern` feature and add the BridgeJS plugin to your package. Here's an example of a `Package.swift` file: - -```swift -// swift-tools-version:6.0 - -import PackageDescription - -let package = Package( - name: "MyApp", - dependencies: [ - .package(url: "https://github.com/swiftwasm/JavaScriptKit.git", branch: "main") - ], - targets: [ - .executableTarget( - name: "MyApp", - dependencies: ["JavaScriptKit"], - swiftSettings: [ - // This is required because the generated code depends on @_extern(wasm) - .enableExperimentalFeature("Extern") - ], - plugins: [ - // Add build plugin for processing @JS and generate Swift glue code - .plugin(name: "BridgeJS", package: "JavaScriptKit") - ] - ) - ] -) -``` - -The `BridgeJS` plugin will process your Swift code to find declarations marked with `@JS` and generate the necessary bridge code to make them accessible from JavaScript. - -### Building your package for JavaScript - -After configuring your `Package.swift`, you can build your package for JavaScript using the following command: - -```bash -swift package --swift-sdk $SWIFT_SDK_ID js -``` - -This command will: - -1. Process all Swift files with `@JS` annotations -2. Generate JavaScript bindings and TypeScript type definitions (`.d.ts`) for your exported Swift code -3. Output everything to the `.build/plugins/PackageToJS/outputs/` directory - -> Note: For larger projects, you may want to generate the BridgeJS code ahead of time to improve build performance. See for more information. +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +BridgeJS allows you to expose Swift functions, classes, and methods to JavaScript by using the ``JS(namespace:enumStyle:)`` attribute. This enables JavaScript code to call into Swift code running in WebAssembly. +Configure your package and build for JavaScript as described in . Then use the topics below to expose Swift types and functions to JavaScript. ## Topics @@ -75,3 +26,7 @@ This command will: - - - + +## See Also + +- ``JS(namespace:enumStyle:)`` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md index fed56618f..e97bceefa 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Array.md @@ -4,7 +4,7 @@ Learn how to pass Swift arrays to and from JavaScript. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS allows you to pass Swift arrays as function parameters and return values. @@ -119,6 +119,8 @@ const result = exports.processNumbers(original); | Struct arrays: `[MyStruct]` | ✅ | | Class arrays: `[MyClass]` | ✅ | | Enum arrays (case, raw value, associated value) | ✅ | +| `JSObject` arrays: `[JSObject]` | ✅ | +| `@JSClass struct` arrays: `[Foo]` | ✅ | | Nested arrays: `[[Int]]` | ✅ | | Optional arrays: `[Int]?` | ✅ | | Arrays of optionals: `[Int?]` | ✅ | 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 3e44581fa..9cd4a2224 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Class.md @@ -4,7 +4,7 @@ Learn how to export Swift classes to JavaScript. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). To export a Swift class, mark both the class and any members you want to expose: @@ -51,6 +51,7 @@ cart.addItem("Laptop", 999.99, 1); cart.addItem("Mouse", 24.99, 2); console.log(`Items in cart: ${cart.getItemCount()}`); console.log(`Total: $${cart.getTotal().toFixed(2)}`); +cart.release(); // Call release() when done; don't rely on FinalizationRegistry as much as possible ``` The generated TypeScript declarations for this class would look like: @@ -83,7 +84,7 @@ Classes use **reference semantics** when crossing the Swift/JavaScript boundary: 1. **Object Creation**: When you create a class instance (via `new` in JS), the object lives on the Swift heap 2. **Reference Passing**: JavaScript receives a reference (handle) to the Swift object, not a copy 3. **Shared State**: Changes made through either Swift or JavaScript affect the same object -4. **Memory Management**: `FinalizationRegistry` automatically releases Swift objects when they're garbage collected in JavaScript. You can optionally call `release()` for deterministic cleanup. +4. **Memory Management**: `FinalizationRegistry` can release Swift objects when they're garbage collected in JavaScript, but you should **not rely on it** for cleanup. Call `release()` when an instance is no longer needed so that Swift memory is reclaimed deterministically. This is especially important for **short-lived instances**: GC may run late or not at all for objects that become unreachable quickly, so relying on `FinalizationRegistry` can delay or leak Swift-side resources. This differs from structs, which use copy semantics and transfer data by value. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md index fe934ddba..adb9ab33b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md @@ -4,9 +4,11 @@ Learn how to use closure/function types as parameters and return values in Bridg ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). -BridgeJS supports typed closure parameters and return values, allowing you to pass functions between Swift and JavaScript with full type safety. This enables functional programming patterns like callbacks, higher-order functions, and function composition across the language boundary. +BridgeJS supports typed closure parameters and return values, allowing you to pass or return Swift closures to JavaScript with full type safety. **Lifetime is automatic**: you use plain Swift closure types (e.g. `(String) -> String`); the runtime releases them when no longer needed-no manual `release()` required. This enables callbacks, higher-order functions, and function composition across the boundary. + +**Recommendation:** When **returning** a closure from Swift to JavaScript, prefer returning a ``JSTypedClosure`` and managing its lifetime explicitly (see ). Explicit `release()` makes cleanup predictable and avoids relying solely on JavaScript garbage collection. Use plain closure types (this article) when you want fully automatic lifetime or when passing closures only as parameters into your exported API. ## Example @@ -99,6 +101,8 @@ Closures use **reference semantics** when crossing the Swift/JavaScript boundary This differs from structs and arrays, which use copy semantics and transfer data by value. +When you **return** a closure to JavaScript, we recommend using ``JSTypedClosure`` and calling `release()` when the closure is no longer needed, instead of returning a plain closure type. See . + ## Supported Features | Swift Feature | Status | @@ -113,4 +117,5 @@ This differs from structs and arrays, which use copy semantics and transfer data ## See Also +- - passing or returning closures with ``JSTypedClosure`` and explicit `release()` - diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Default-Parameters.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Default-Parameters.md index f6115f063..e6f4b8e9a 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Default-Parameters.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Default-Parameters.md @@ -4,7 +4,7 @@ Learn how to use default parameter values in Swift functions and constructors ex ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS supports default parameter values for Swift functions and class constructors exported to JavaScript. When you specify default values in your Swift code, they are automatically applied in the generated JavaScript bindings. @@ -64,7 +64,7 @@ Constructor parameters also support default values, making it easy to create ins @JS var name: String @JS var timeout: Int @JS var retries: Int - + @JS init(name: String = "default", timeout: Int = 30, retries: Int = 3) { self.name = name self.timeout = timeout 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 3dda2b9c5..2220d457c 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Enum.md @@ -4,7 +4,7 @@ Learn how to export Swift enums to JavaScript. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS supports two output styles for enums, controlled by the `enumStyle` parameter: @@ -509,8 +509,9 @@ This differs from classes, which use reference semantics and share state across | Static functions | ✅ | | Static properties | ✅ | | Associated values: `String`, `Int`, `Bool`, `Float`, `Double` | ✅ | -| Associated values: Custom classes/structs | ❌ | -| Associated values: Other enums | ❌ | -| Associated values: Arrays/Collections | ❌ | -| Associated values: Optionals | ❌ | +| Associated values: Custom classes/structs | ✅ | +| Associated values: Other enums (case, raw value, and associated value) | ✅ | +| Associated values: `JSObject` | ✅ | +| Associated values: Arrays | ✅ | +| Associated values: Optionals of all supported types | ✅ | | Generics | ❌ | 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 ebc8037c4..c26841041 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 @@ -4,7 +4,7 @@ Learn how to export Swift functions to JavaScript. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). To export a Swift function to JavaScript, mark it with the `@JS` attribute and make it `public`: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Optional.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Optional.md index 91fdc3472..be15b762f 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Optional.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Optional.md @@ -4,14 +4,12 @@ Learn how to use Swift optionals in functions, classes, and enums exported to Ja ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS provides comprehensive support for Swift optionals across all bridged types. When you use `Optional` or `T?` in Swift, it automatically maps to `T | null` in TypeScript/JavaScript. Swift optionals are translated to union types with `null` (not `undefined`) because `null` represents an explicit "no value" state that aligns semantically with Swift's `nil`. This design choice ensures consistent null handling across the Swift-JavaScript bridge and avoids the ambiguity that comes with JavaScript's `undefined`. -> Important: BridgeJS optional support is **Swift → JavaScript only**. TypeScript → Swift optional imports are not currently supported. - ## Supported Optional Syntax BridgeJS recognizes all Swift optional syntax variants: @@ -35,7 +33,7 @@ All parameter types can be made optional, including primitives, objects, and enu ```swift @JS public func processOptionalData( text: String?, // Optional string - count: Int?, // Optional integer + count: Int?, // Optional integer flag: Bool?, // Optional boolean rate: Double?, // Optional double user: User? // Optional Swift class @@ -85,7 +83,7 @@ Constructors can accept optional parameters. @JS public var email: String? @JS public var age: Int? @JS public var avatar: User? - + @JS public init(name: String?) @JS public func updateProfile(email: String?, age: Int?) } @@ -100,7 +98,7 @@ export interface UserProfile extends SwiftHeapObject { email: string | null; age: number | null; avatar: User | null; - + updateProfile(email: string | null, age: number | null): void; } export type UserProfile = { diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md index 111b1f052..3b2ec1526 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Protocols.md @@ -4,7 +4,7 @@ Learn how to expose Swift protocols to JavaScript as TypeScript interfaces. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS allows you to export Swift protocols as TypeScript interfaces. JavaScript objects implementing these interfaces can be passed to Swift code, enabling protocol-oriented design across the Swift-JavaScript boundary. @@ -31,28 +31,28 @@ import JavaScriptKit @JS class CounterManager { var delegate: Counter - + @JS init(delegate: Counter) { self.delegate = delegate } - + @JS func incrementTwice() { delegate.increment(by: 1) delegate.increment(by: 1) } - + @JS func getCurrentValue() -> Int { return delegate.getValue() } - + @JS func getCounterName() -> String { return delegate.name } - + @JS func setCountValue(_ value: Int) { delegate.count = value } - + @JS func updateLabel(_ newLabel: String?) { delegate.label = newLabel } @@ -130,15 +130,15 @@ You can also implement protocols in Swift and use them from JavaScript: final class SwiftCounter: Counter { var count = 0 let name = "SwiftCounter" - + func increment(by amount: Int) { count += amount } - + func reset() { count = 0 } - + func getValue() -> Int { return count } 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 00e7c1f22..1c4b22abe 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 @@ -4,7 +4,7 @@ Learn how to export Swift static and class functions as JavaScript static method ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS supports exporting Swift `static func` and `class func` to JavaScript static methods. Both generate identical JavaScript output but differ in Swift inheritance behavior. @@ -17,15 +17,15 @@ Classes can export both `static` and `class` functions: ```swift @JS class MathUtils { @JS init() {} - + @JS static func add(a: Int, b: Int) -> Int { return a + b } - + @JS class func subtract(a: Int, b: Int) -> Int { return a - b } - + @JS func multiply(x: Int, y: Int) -> Int { return x * y } @@ -79,11 +79,11 @@ Enums can contain static functions that are exported as properties: @JS enum Calculator { case scientific case basic - + @JS static func square(value: Int) -> Int { return value * value } - + @JS static func cube(value: Int) -> Int { return value * value * value } @@ -140,7 +140,7 @@ Generated TypeScript definitions: declare global { namespace Utils { namespace String { - uppercase(text: string): string; + function uppercase(text: string): string; } } } diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Properties.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Properties.md index 4110e6166..4898535c8 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Properties.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Static-Properties.md @@ -4,7 +4,7 @@ Learn how to export Swift static and class properties as JavaScript static prope ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). BridgeJS supports exporting Swift `static var`, `static let`, and `class var` properties to JavaScript static properties. Both stored and computed properties are supported. @@ -15,16 +15,16 @@ Classes can export both stored and computed static properties: ```swift @JS class Configuration { @JS init() {} - + @JS static let version = "1.0.0" @JS static var debugMode = false @JS class var defaultTimeout = 30 - + @JS static var timestamp: Double { get { return Date().timeIntervalSince1970 } set { /* custom setter logic */ } } - + @JS static var buildNumber: Int { return 12345 } @@ -81,7 +81,7 @@ Enums can contain static properties that are exported alongside enum cases: @JS enum PropertyEnum { case value1 case value2 - + @JS static var enumProperty = "mutable" @JS static let enumConstant = 42 @JS static var computedEnum: String { 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 236b822ab..32bb79ed3 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Struct.md @@ -4,7 +4,7 @@ Learn how to export Swift structs to JavaScript. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). To export a Swift struct, mark it with `@JS`: @@ -91,7 +91,7 @@ export type Exports = { ```swift @JS struct Config { var name: String - + @JS nonisolated(unsafe) static var defaultTimeout: Double = 30.0 @JS static let maxRetries: Int = 3 } @@ -160,6 +160,8 @@ This differs from classes, which use reference semantics and share state across | Stored fields with supported types | ✅ | | Optional fields | ✅ | | Nested structs | ✅ | +| `JSObject` fields | ✅ | +| `@JSClass struct` fields | ✅ | | Instance methods | ✅ | | Static methods | ✅ | | Static properties | ✅ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md index 057b5f030..1aff82f65 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Using-Namespace.md @@ -4,7 +4,7 @@ Learn how to organize exported Swift code into JavaScript namespaces. ## Overview -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). The `@JS` macro supports organizing your exported Swift code into namespaces using dot-separated strings. This allows you to create hierarchical structures in JavaScript that mirror your Swift code organization. @@ -121,7 +121,3 @@ export interface Greeter extends SwiftHeapObject { ``` Using namespaces can be preferable for projects with many global functions, as they help prevent naming collisions. Namespaces also provide intuitive hierarchies for organizing your exported Swift code, and they do not affect the code generated by `@JS` declarations without namespaces. - -## See Also - -- - Namespace enums section diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md new file mode 100644 index 000000000..9c0a80dc1 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md @@ -0,0 +1,419 @@ +# Generating bindings from TypeScript + +How to generate macro-annotated Swift bindings from a TypeScript declaration file (`bridge-js.d.ts`) so you don't have to write the Swift by hand. + +## Overview + +The BridgeJS plugin can read a `bridge-js.d.ts` file in your target and generate Swift code that uses the same macros as hand-written bindings (see ). + +The output is macro-annotated Swift; you can inspect the generated file at the following path to see exactly what was produced: + +``` +./build/plugins/outputs///destination/BridgeJS/BridgeJS.Macros.swift +``` + +Use this workflow when you have existing TypeScript definitions or many APIs to bind. + +> Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. + +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). + +## How to generate bindings from TypeScript + +### Step 1: Configure your package + +Add the BridgeJS plugin and enable the Extern feature as described in . + +### Step 2: Create TypeScript definitions + +Create a file named `bridge-js.d.ts` in your target source directory (e.g. `Sources//bridge-js.d.ts`). Declare the JavaScript APIs you want to use in Swift: + +```typescript +export function consoleLog(message: string): void; +``` + +### Step 3: Build your package + +Run: + +```bash +swift package --swift-sdk $SWIFT_SDK_ID js +``` + +The plugin processes `bridge-js.d.ts`, generates Swift bindings (using the same macros as in ), compiles to WebAssembly, and produces JavaScript glue in `.build/plugins/PackageToJS/outputs/`. + +> Note: For larger projects, see . + +## Declaration mappings + +### Functions + +Each exported function becomes a top-level Swift function with `@JSFunction` and `throws(JSException)`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + + /** Returns the sum of two numbers. */ + export function sum(a: number, b: number): number; + /** + * Sets the document title. + * @param title - The new title string + */ + export function setDocumentTitle(title: string): void; + ``` + } + @Column { + ```swift + // Generated Swift + + /// Returns the sum of two numbers. + @JSFunction func sum(a: Double, b: Double) throws(JSException) -> Double + + + /// Sets the document title. + /// - Parameter title: The new title string + @JSFunction func setDocumentTitle(title: String) throws(JSException) + ``` + } +} + +### Global getters + +Module-level `declare const` or top-level readonly bindings that reference a bridged type become a Swift global property with `@JSGetter`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document) */ + export const document: Document; + ``` + } + @Column { + ```swift + // Generated Swift + /// [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document) + @JSGetter var document: Document + ``` + } +} + +### Classes + +A class becomes a Swift struct with `@JSClass`. The constructor becomes `init(...)` with `@JSFunction`. Properties become `@JSGetter`; writable properties also get `@JSSetter` as `set(_:)`. Methods become `@JSFunction`. Static methods become `static func` on the struct. All thunks throw `JSException` if the underlying JavaScript throws. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export class Greeter { + /** A readonly field is translated with `@JSGetter` */ + readonly id: number; + + /** A read-writable field is translated with `@JSGetter` and `@JSSetter` */ + message: string; + + /** A constructor */ + constructor(id: string, name: string); + /** A method */ + greet(): string; + /** A static method */ + static createDefault(greetingId: number, locale: string): string; + } + ``` + } + @Column { + ```swift + // Generated Swift + @JSClass struct Greeter { + /// A readonly field is translated with `@JSGetter` + @JSGetter var id: Double + + /// A read-writable field is translated with `@JSGetter` and `@JSSetter` + @JSGetter var message: String + @JSSetter func setMessage(_ newValue: String) throws(JSException) + + /// A constructor + @JSFunction init(id: String, name: String) throws(JSException) + /// A method + @JSFunction func greet() throws(JSException) -> String + @JSFunction static func createDefault(_ greetingId: Double, _ locale: String) throws(JSException) -> String + } + ``` + } +} + +### Interfaces + +An interface becomes a Swift struct with `@JSClass`. No constructor. Properties and methods are bridged the same way as for classes (`@JSGetter`, `@JSSetter`, `@JSFunction`). Instances are obtained from other calls (e.g. a function that returns the interface type). + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export interface HTMLElement { + readonly innerText: string; + className: string; + + appendChild(child: HTMLElement): void; + } + ``` + } + @Column { + ```swift + // Generated Swift + @JSClass struct HTMLElement { + @JSGetter var innerText: String + @JSGetter var className: String + @JSSetter func setClassName(_ newValue: String) throws(JSException) + @JSFunction func appendChild(_ child: HTMLElement) throws(JSException) + } + ``` + } +} + +### Type aliases + +Type aliases are resolved when generating Swift; the resolved shape is emitted, not a separate alias type. + +- **Primitive alias** (e.g. `type UserId = string`): Replaced by the underlying Swift type (e.g. `String`) everywhere it is used. +- **Object-shaped alias** (e.g. `type User = { id: string; name: string }`): The generator emits a named Swift struct with that name and the corresponding `@JSClass` / getters / setters. No constructor; use is the same as for interfaces. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export type UserId = string; + export type User = { + readonly id: UserId; + name: string; + }; + export function getUser(): User; + ``` + } + @Column { + ```swift + // Generated Swift (UserId inlined as String) + @JSClass struct User { + @JSGetter var id: String + @JSGetter var name: String + @JSSetter func setName(_ newValue: String) throws(JSException) + } + @JSFunction func getUser() throws(JSException) -> User + ``` + } +} + +### String enums + +TypeScript enums with string literal values become Swift enums with `String` raw value and the appropriate BridgeJS protocol conformances. Usable as parameter and return types. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export enum Theme { + light = "light", + dark = "dark", + } + + + export function setTheme(theme: Theme): void; + export function getTheme(): Theme; + ``` + } + @Column { + ```swift + // Generated Swift + enum Theme: String { + case light = "light" + case dark = "dark" + } + extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} + + @JSFunction func setTheme(_ theme: Theme) throws(JSException) -> Void + @JSFunction func getTheme() throws(JSException) -> Theme + ``` + } +} + +## Type mappings + +The following mappings apply to function parameters, return types, and class/interface properties. + +### Primitives + +| TypeScript | Swift | +|------------|-------| +| `number` | `Double` | +| `string` | `String` | +| `boolean` | `Bool` | + +These appear in the function and class examples above. + +### Arrays + +`T[]` and `Array` → `[T]`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export function sumAll(values: number[]): number; + export function getScores(): number[]; + export function getLabels(): string[]; + export function normalize(values: Array): Array; + ``` + } + @Column { + ```swift + // Generated Swift + @JSFunction func sumAll(_ values: [Double]) throws(JSException) -> Double + @JSFunction func getScores() throws(JSException) -> [Double] + @JSFunction func getLabels() throws(JSException) -> [String] + @JSFunction func normalize(_ values: [Double]) throws(JSException) -> [Double] + ``` + } +} + +### Optional and undefined + +- **`T | null`** → Swift `Optional` (e.g. `Optional`, `Optional`, `Optional`). +- **`T | undefined`** or optional parameters → Swift `JSUndefinedOr`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export function parseCount(value: number | null): number | null; + export function parseLimit(value: number | undefined): number | undefined; + export function scale(factor: number, offset: number | null): number; + + export interface Payload {} + export class RequestOptions { + body: Payload | null; + + headers: Payload | undefined; + + } + ``` + } + @Column { + ```swift + // Generated Swift + @JSFunction func parseCount(_ value: Optional) throws(JSException) -> Optional + @JSFunction func parseLimit(_ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr + @JSFunction func scale(_ factor: Double, _ offset: Optional) throws(JSException) -> Double + + @JSClass struct Payload {} + @JSClass struct RequestOptions { + @JSGetter var body: Optional + @JSSetter func setBody(_ value: Optional) throws(JSException) + @JSGetter var headers: JSUndefinedOr + @JSSetter func setHeaders(_ value: JSUndefinedOr) throws(JSException) + } + ``` + } +} + +### Records (dictionaries) + +`Record` → Swift `[String: V]`. Supported value types: primitives, arrays, nested records, optional object types. Keys other than `string` (e.g. `Record`) are unsupported; such parameters become `JSObject`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + export function applyScores(scores: Record): void; + export function getMetadata(): Record; + export function getMatrix(value: Record>): Record>; + export function getSeries(values: Record): Record; + export function lookupByIndex(values: Record): void; + ``` + } + @Column { + ```swift + // Generated Swift + @JSFunction func applyScores(_ scores: [String: Double]) throws(JSException) -> Void + @JSFunction func getMetadata() throws(JSException) -> [String: String] + @JSFunction func getMatrix(_ value: [String: [String: Double]]) throws(JSException) -> [String: [String: Double]] + @JSFunction func getSeries(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] + @JSFunction func lookupByIndex(_ values: JSObject) throws(JSException) -> Void + ``` + } +} + +### Unbridged types (JSValue, JSObject) + +Types that cannot be expressed in the bridge (e.g. `any`, unsupported generics, or `Record`) are emitted as `JSValue` or `JSObject`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + interface Animatable { + animate(keyframes: any, options: any): any; + } + export function getAnimatable(): Animatable; + ``` + } + @Column { + ```swift + // Generated Swift + @JSClass struct Animatable { + @JSFunction func animate(_ keyframes: JSValue, _ options: JSValue) throws(JSException) -> JSValue + } + @JSFunction func getAnimatable() throws(JSException) -> Animatable + ``` + } +} + +## Name mapping + +### Invalid or special property and type names + +When a TypeScript name is not a valid Swift identifier (e.g. contains dashes, spaces, or starts with a number), or is a Swift keyword, the generator emits a Swift-safe name and uses `jsName` so the JavaScript binding remains correct. Classes whose names start with `$` are prefixed with `_` in Swift and get `@JSClass(jsName: "...")`. + +@Row { + @Column { + ```typescript + // TypeScript (bridge-js.d.ts) + interface DOMTokenList { + "data-attrib": number; + + "0": boolean; + + for: string; + + as(): void; + } + export class $jQuery { + "call-plugin"(): void; + } + ``` + } + @Column { + ```swift + // Generated Swift + @JSClass struct DOMTokenList { + @JSGetter(jsName: "data-attrib") var data_attrib: Double + @JSSetter(jsName: "data-attrib") func setData_attrib(_ value: Double) throws(JSException) + @JSGetter(jsName: "0") var _0: Bool + @JSSetter(jsName: "0") func set_0(_ value: Bool) throws(JSException) + @JSGetter var `for`: String + @JSSetter func setFor(_ value: String) throws(JSException) + @JSFunction func `as`() throws(JSException) -> Void + } + @JSClass(jsName: "$jQuery") struct _jQuery { + @JSFunction(jsName: "call-plugin") func call_plugin() throws(JSException) -> Void + } + ``` + } +} + +## Limitations + +- No first-class support for async/Promise-returning functions;. +- No generic type parameter can appear on a bridged function signature. \ No newline at end of file diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md new file mode 100644 index 000000000..14fccbfc1 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md @@ -0,0 +1,98 @@ +# Importing JavaScript into Swift + +Learn how to make JavaScript APIs callable from your Swift code using macro-annotated bindings. + +## Overview + +> Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. + +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). + +You can import JavaScript APIs into Swift in two ways: + +1. **Annotate Swift with macros** - Use `@JSFunction`, `@JSClass`, `@JSGetter`, and `@JSSetter` to declare bindings directly in Swift. No TypeScript required. Prefer this to get started. +2. **Generate bindings from TypeScript** - Use a `bridge-js.d.ts` file; the BridgeJS plugin generates the same macro-annotated Swift. See when you have existing `.d.ts` definitions or many APIs to bind. + +This guide covers the macro-based path. + +## How to import JavaScript APIs (macro path) + +### Step 1: Configure your package + +Add the BridgeJS plugin and enable the Extern feature as described in . + +### Step 2: Declare bindings in Swift with macros + +Create Swift declarations that mirror the JavaScript API you want to call. + +You can bring JavaScript into Swift in two ways: + +- **Inject at initialization**: Declare in Swift and supply the implementation in `getImports()` (e.g. a `today()` function). +- **Import from `globalThis`**: For APIs on the JavaScript global object (e.g. `console`, `document`), use `@JSGetter(from: .global)` so they are read from `globalThis` and you don't pass them in `getImports()`. + +```swift +import JavaScriptKit + +@JSFunction func today() -> String + +@JSClass struct JSConsole { + @JSFunction func log(_ message: String) throws(JSException) +} +@JSGetter(from: .global) var console: JSConsole + +@JSClass struct Document { + @JSFunction func getElementById(_ id: String) throws(JSException) -> HTMLElement + @JSFunction func createElement(_ tagName: String) throws(JSException) -> HTMLElement +} +@JSGetter(from: .global) var document: Document + +@JSClass struct HTMLElement { + @JSGetter var innerText: String + @JSSetter func setInnerText(_ newValue: String) throws(JSException) + @JSFunction func appendChild(_ child: HTMLElement) throws(JSException) +} +``` + +For full details, see , , and . + +### Step 3: Use the bindings in Swift + +Call the bound APIs from Swift: + +```swift +import JavaScriptKit + +@JS func run() { + try console.log("Hello from Swift! (\(today()))") + + let button = document.createElement("button")! + try button.setInnerText("Click Me") + let container = document.getElementById("app")! + container.appendChild(button) +} +``` + +### Step 5: Inject JavaScript implementations (if needed) + +Bindings imported from globalThis (e.g. `console`, `document`) are read at runtime and do not go in `getImports()`. Only APIs you inject at initialization must be supplied there: + +```javascript +// index.js +import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; + +const { exports } = await init({ + getImports() { + return { + today: () => new Date().toString() + }; + } +}); + +exports.run(); +``` + +## Topics + +- +- +- \ No newline at end of file diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md new file mode 100644 index 000000000..4302e0e49 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md @@ -0,0 +1,54 @@ +# Importing a JavaScript class or object into Swift + +This guide shows how to bind a JavaScript class (or object shape) so you can construct and use it from Swift with `@JSClass`. + +## Steps + +### 1. Declare a Swift struct with `@JSClass` + +Add a struct that mirrors the JavaScript class. Use `@JSFunction` for the initializer and for methods, and `@JSGetter` / `@JSSetter` for properties. Property setters are exposed as functions (e.g. `setMessage(_:)`) because Swift property setters cannot `throw`. + +```swift +import JavaScriptKit + +@JSClass struct Greeter { + @JSFunction init(id: String, name: String) throws(JSException) + + @JSGetter var id: String + @JSGetter var message: String + @JSSetter func setMessage(_ newValue: String) throws(JSException) + + @JSFunction func greet() throws(JSException) -> String +} +``` + +If the class is on `globalThis`, add `from: .global` to `@JSClass` and omit the type from `getImports()` in the next step. + +### 2. Wire the JavaScript side + +**If you chose injection:** Implement the class in JavaScript and pass it in `getImports()`. + +```javascript +// index.js +import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; + +class Greeter { + constructor(id, name) { /* ... */ } + get id() { /* ... */ } + get message() { /* ... */ } + set message(value) { /* ... */ } + greet() { /* ... */ } +} + +const { exports } = await init({ + getImports() { + return { Greeter }; + } +}); +``` + +**If you chose global:** Do not pass the class in `getImports()`; the runtime will resolve it from `globalThis`. + +## Macro options + +For optional parameters (`jsName`, `from`, etc.), see the API reference: ``JSClass(jsName:from:)``, ``JSFunction(jsName:from:)``, ``JSGetter(jsName:from:)``, and ``JSSetter(jsName:from:)``. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md new file mode 100644 index 000000000..64475acfa --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md @@ -0,0 +1,51 @@ +# Importing a JavaScript function into Swift + +This guide shows how to bind a JavaScript function so it is callable from Swift using `@JSFunction`. + +## Steps + +### 1. Declare the function in Swift with `@JSFunction` + +Match the JavaScript name and signature. Use Swift types that bridge to the JS types you need (see ). + +```swift +import JavaScriptKit + +@JSFunction func add(_ a: Double, _ b: Double) throws(JSException) -> Double +@JSFunction func setTitle(_ title: String) throws(JSException) +``` + +To bind a function that lives on the JavaScript global object (e.g. `parseInt`, `setTimeout`), add `from: .global`. Use `jsName` when the Swift name differs from the JavaScript name - see the ``JSFunction(jsName:from:)`` API reference for options. + +### 2. Provide the implementation at initialization + +Return the corresponding function(s) in the object passed to `getImports()` when initializing the WebAssembly module. + +```javascript +// index.js +import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; + +const { exports } = await init({ + getImports() { + return { + add: (a, b) => a + b, + setTitle: (title) => { document.title = title }, + }; + } +}); +``` + +If you used `from: .global`, do not pass the function in `getImports()`; the runtime resolves it from `globalThis`. + +### 3. Handle errors + +Bound functions are `throws(JSException)`. Call them with `try` or `try?`; they throw when the JavaScript implementation throws. + +## Supported features + +| Feature | Status | +|:--|:--| +| Primitive parameter/result types (e.g. `Double`, `Bool`) | ✅ | +| `String` parameter/result type | ✅ | +| Async function | ❌ | +| Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md new file mode 100644 index 000000000..044ebbe52 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md @@ -0,0 +1,59 @@ +# Importing a global JavaScript variable into Swift + +This guide shows how to bind a JavaScript global variable (or any property you provide at initialization) so you can read and optionally write it from Swift using `@JSGetter` and `@JSSetter`. + +## Steps + +### 1. Declare the variable in Swift with `@JSGetter` + +Use a type that bridges to the JavaScript value (see ). For object-shaped values, use a struct conforming to the bridged type (e.g. a `@JSClass` struct). + +```swift +import JavaScriptKit + +@JSGetter(from: .global) var document: Document +@JSGetter(from: .global) var myConfig: String +``` + +To bind a variable that is not on `globalThis`, omit `from: .global` and supply the value in `getImports()` in the next step. Use `jsName` when the Swift name differs from the JavaScript property name - see the ``JSGetter(jsName:from:)`` API reference. + +### 2. Add a setter for writable variables (optional) + +If the JavaScript property is writable and you need to set it from Swift, add a corresponding `@JSSetter` function. Property setters are exposed as functions (e.g. `setMyConfig(_:)`) because Swift property setters cannot `throw`. + +```swift +@JSGetter(from: .global) var myConfig: String +@JSSetter(from: .global) func setMyConfig(_ newValue: String) throws(JSException) +``` + +### 3. Provide the value at initialization (injected only) + +If you did **not** use `from: .global`, pass the value in the object returned by `getImports()` when initializing the WebAssembly module. + +```javascript +// index.js +import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; + +const { exports } = await init({ + getImports() { + return { + myConfig: "production", + }; + } +}); +``` + +If you used `from: .global`, do not pass the variable in `getImports()`; the runtime reads it from `globalThis`. + +## Supported features + +| Feature | Status | +|:--|:--| +| Read-only global (e.g. `document`, `console`) | ✅ | +| Writable global | ✅ (`@JSSetter`) | +| Injected variable (via `getImports()`) | ✅ | + +## See also + +- ``JSGetter(jsName:from:)`` +- ``JSSetter(jsName:from:)`` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript-into-Swift.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript-into-Swift.md deleted file mode 100644 index b091f714b..000000000 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript-into-Swift.md +++ /dev/null @@ -1,185 +0,0 @@ -# Importing TypeScript into Swift - -Learn how to leverage TypeScript definitions to create type-safe bindings for JavaScript APIs in your Swift code. - -## Overview - -> Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. - -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS enables seamless integration between Swift and JavaScript by automatically generating Swift bindings from TypeScript declaration files (`.d.ts`). This provides type-safe access to JavaScript APIs directly from your Swift code. - -The key benefits of this approach over `@dynamicMemberLookup`-based APIs include: - -- **Type Safety**: Catch errors at compile-time rather than runtime -- **IDE Support**: Get autocompletion and documentation in your Swift editor -- **Performance**: Eliminating dynamism allows us to optimize the glue code - -If you prefer keeping your project simple, you can continue using `@dynamicMemberLookup`-based APIs. - -## Getting Started - -### Step 1: Configure Your Package - -First, add the BridgeJS plugin to your Swift package by modifying your `Package.swift` file: - -```swift -// swift-tools-version:6.0 - -import PackageDescription - -let package = Package( - name: "MyApp", - dependencies: [ - .package(url: "https://github.com/swiftwasm/JavaScriptKit.git", branch: "main") - ], - targets: [ - .executableTarget( - name: "MyApp", - dependencies: ["JavaScriptKit"], - swiftSettings: [ - // This is required because the generated code depends on @_extern(wasm) - .enableExperimentalFeature("Extern") - ], - plugins: [ - // Add build plugin for processing @JS and generate Swift glue code - .plugin(name: "BridgeJS", package: "JavaScriptKit") - ] - ) - ] -) -``` - -### Step 2: Create TypeScript Definitions - -Create a file named `bridge-js.d.ts` in your target source directory (e.g. `Sources//bridge-js.d.ts`). This file defines the JavaScript APIs you want to use in Swift: - -```typescript -// Simple function -export function consoleLog(message: string): void; - -// Define a subset of DOM API you want to use -interface Document { - // Properties - title: string; - readonly body: HTMLElement; - - // Methods - getElementById(id: string): HTMLElement; - createElement(tagName: string): HTMLElement; -} - -// You can use type-level operations like `Pick` to reuse -// type definitions provided by `lib.dom.d.ts`. -interface HTMLElement extends Pick { - appendChild(child: HTMLElement): void; - // TODO: Function types on function signatures are not supported yet. - // addEventListener(event: string, handler: (event: any) => void): void; -} - -// Provide access to `document` -export function getDocument(): Document; -``` - -BridgeJS will generate Swift code that matches these TypeScript declarations. For example: - -```swift -func consoleLog(message: String) - -struct Document { - var title: String { get set } - var body: HTMLElement { get } - - func getElementById(_ id: String) -> HTMLElement - func createElement(_ tagName: String) -> HTMLElement -} - -struct HTMLElement { - var innerText: String { get set } - var className: String { get set } - - func appendChild(_ child: HTMLElement) -} - -func getDocument() -> Document -``` - -### Step 3: Build Your Package - -Build your package with the following command: - -```bash -swift package --swift-sdk $SWIFT_SDK_ID js -``` - -This command: -1. Processes your TypeScript definition files -2. Generates corresponding Swift bindings -3. Compiles your Swift code to WebAssembly -4. Produces JavaScript glue code in `.build/plugins/PackageToJS/outputs/` - -> Note: For larger projects, you may want to generate the BridgeJS code ahead of time to improve build performance. See for more information. - -### Step 4: Use the Generated Swift Bindings - -The BridgeJS plugin automatically generates Swift bindings that match your TypeScript definitions. You can now use these APIs directly in your Swift code: - -```swift -import JavaScriptKit - -@JS func run() { - // Simple function call - consoleLog("Hello from Swift!") - - // Get `document` - let document = getDocument() - - // Property access - document.title = "My Swift App" - - // Method calls - let button = document.createElement("button") - button.innerText = "Click Me" - - // TODO: Function types on function signatures are not supported yet. - // buttion.addEventListener("click") { _ in - // print("On click!") - // } - - // DOM manipulation - let container = document.getElementById("app") - container.appendChild(button) -} -``` - -### Step 5: Inject JavaScript Implementations - -The final step is to provide the actual JavaScript implementations for the TypeScript declarations you defined. You need to create a JavaScript file that initializes your WebAssembly module with the appropriate implementations: - -```javascript -// index.js -import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; - -// Initialize the WebAssembly module with JavaScript implementations -const { exports } = await init({ - getImports() { - return { - consoleLog: (message) => { - console.log(message); - }, - getDocument: () => document, - } - } -}); - -// Call the entry point of your Swift application -exports.run(); -``` - -## Topics - -- -- -- -- diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Class.md deleted file mode 100644 index e04bb9e75..000000000 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Class.md +++ /dev/null @@ -1,64 +0,0 @@ -# Importing TypeScript Classes into Swift - -Learn how TypeScript classes map to Swift when importing APIs. - -## Overview - -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS reads class declarations in your `bridge-js.d.ts` and generates Swift structs that represent JS objects. Constructors, methods, and properties are bridged via thunks that call into your JavaScript implementations at runtime. - -## Example - -TypeScript definition (`bridge-js.d.ts`): - -```typescript -export class Greeter { - readonly id: string; - message: string; - constructor(id: string, name: string); - greet(): string; -} -``` - -Generated Swift API: - -```swift -struct Greeter { - init(id: String, name: String) throws(JSException) - - // Properties - // Readonly property - var id: String { get throws(JSException) } - // Writable property - var message: String { get throws(JSException) } - func setMessage(_ newValue: String) throws(JSException) - - // Methods - func greet() throws(JSException) -> String -} -``` - -Notes: -- Property setters are emitted as `set(_:)` functions, not Swift `set` accessors since `set` accessors can't have `throws` -- All thunks throw `JSException` if the underlying JS throws. - -JavaScript implementation wiring (provided by your app): - -```javascript -// index.js -import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; - -class Greeter { - readonly id: string; - message: string; - constructor(id: string, name: string) { ... } - greet(): string { ... } -} - -const { exports } = await init({ - getImports() { - return { Greeter }; - } -}); -``` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Function.md deleted file mode 100644 index 060ac390f..000000000 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Function.md +++ /dev/null @@ -1,60 +0,0 @@ -# Importing TypeScript Functions into Swift - -Learn how functions declared in TypeScript become callable Swift functions. - -## Overview - -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS reads your `bridge-js.d.ts` and generates Swift thunks that call into JavaScript implementations provided at runtime. Each imported function becomes a top-level Swift function with the same name and a throwing signature. - -### Example - -TypeScript definition (`bridge-js.d.ts`): - -```typescript -export function add(a: number, b: number): number; -export function setTitle(title: string): void; -export function fetchUser(id: string): Promise; -``` - -Generated Swift signatures: - -```swift -func add(a: Double, b: Double) throws(JSException) -> Double -func setTitle(title: String) throws(JSException) -func fetchUser(id: String) throws(JSException) -> JSPromise -``` - -JavaScript implementation wiring (provided by your app): - -```javascript -// index.js -import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; - -const { exports } = await init({ - getImports() { - return { - add: (a, b) => a + b, - setTitle: (title) => { document.title = title }, - fetchUser: (id) => fetch(`/api/users/${id}`).then(r => r.json()), - }; - } -}); -``` - -### Error handling - -- All imported Swift functions are generated as `throws(JSException)` and will throw if the underlying JS implementation throws. - -## Supported features - -| Feature | Status | -|:--|:--| -| Primitive parameter/result types: (e.g. `boolean`, `number`) | ✅ | -| `string` parameter/result type | ✅ | -| Enums in signatures | ❌ | -| Async function | ✅ | -| Generics | ❌ | - - diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Interface.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Interface.md deleted file mode 100644 index 0e0aed0de..000000000 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-Interface.md +++ /dev/null @@ -1,34 +0,0 @@ -# Importing TypeScript Interfaces into Swift - -Learn how TypeScript interfaces become Swift value types with methods and properties. - -## Overview - -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS converts TS interfaces to Swift structs conforming to an internal bridging protocol and provides thunks for methods and properties that call into your JavaScript implementations. - -> Note: Interfaces are bridged very similarly to classes. Methods and properties map the same way. See for more details. - -### Example - -TypeScript definition (`bridge-js.d.ts`): - -```typescript -export interface HTMLElement { - readonly innerText: string; - className: string; - appendChild(child: HTMLElement): void; -} -``` - -Generated Swift API: - -```swift -struct HTMLElement { - var innerText: String { get throws(JSException) } - var className: String { get throws(JSException) } - func setClassName(_ newValue: String) throws(JSException) - func appendChild(_ child: HTMLElement) throws(JSException) -} -``` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-TypeAlias.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-TypeAlias.md deleted file mode 100644 index b5242ee33..000000000 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-TypeScript/Importing-TS-TypeAlias.md +++ /dev/null @@ -1,47 +0,0 @@ -# Importing TypeScript Type Aliases into Swift - -Understand how TypeScript type aliases are handled when generating Swift bindings. - -## Overview - -> Tip: You can quickly preview what interfaces will be exposed on the Swift/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). - -BridgeJS resolves TypeScript aliases while importing. If an alias names an anonymous object type, Swift will generate a corresponding bridged struct using that name. - -> Note: When a type alias names an anonymous object type, its bridging behavior (constructors not applicable, but methods/properties if referenced) mirrors class/interface importing. See for more details. - -### Examples - -```typescript -// Primitive alias → maps to the underlying primitive -export type Price = number; - -// Object-shaped alias with a name → becomes a named bridged type when referenced -export type User = { - readonly id: string; - name: string; - age: Price; -} - -export function getUser(): User; -``` - -Generated Swift (simplified): - -```swift -// Price → Double - -struct User { - // Readonly property - var id: String { get throws(JSException) } - - // Writable properties - var name: String { get throws(JSException) } - func setName(_ newValue: String) throws(JSException) - - var age: Double { get throws(JSException) } - func setAge(_ newValue: Double) throws(JSException) -} - -func getUser() throws(JSException) -> User -``` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Introducing-BridgeJS.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Introducing-BridgeJS.md new file mode 100644 index 000000000..43f778f0c --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Introducing-BridgeJS.md @@ -0,0 +1,32 @@ +# Introducing BridgeJS + +Faster, easier Swift-JavaScript bridging for WebAssembly. + +## Overview + +**BridgeJS** is a layer underneath JavaScriptKit that makes Swift-JavaScript interop **faster and easier**: you declare the shape of the API in Swift (or in TypeScript, which generates Swift), and the tool generates glue code. + +Benefits over the dynamic `JSObject` / `JSValue` APIs include: + +- **Performance** - Generated code is specialized per interface, so crossing the bridge typically costs less than using generic dynamic APIs. +- **Type safety** - Mistakes are caught at compile time instead of at runtime. +- **Easier integration** - Declarative annotations and optional TypeScript input replace manual boilerplate (closures, serializers, cached strings). + +You can still use the dynamic APIs when you need them; BridgeJS is an additional option for boundaries where you want strong typing and better performance. + +## Two directions + +BridgeJS supports both directions of the bridge: + +1. **Export Swift to JavaScript** - Expose Swift functions, classes, and types to JavaScript using the ``JS(namespace:enumStyle:)`` macro. JavaScript can then call into your Swift code. See . +2. **Import JavaScript into Swift** - Make JavaScript APIs (functions, classes, globals like `document` or `console`) callable from Swift with macros such as ``JSClass(jsName:from:)``. Start with . You can also generate the same bindings from a TypeScript file; see . + +Many apps use both: import DOM or host APIs into Swift, and export an entry point or callbacks to JavaScript. + +## Getting started + +- To **call Swift from JavaScript**: +- To **call JavaScript from Swift**: +- To **generate bindings from TypeScript**: + +All require the same package and build setup; see for configuration. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md new file mode 100644 index 000000000..99a3d5b1c --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Setting-up-BridgeJS.md @@ -0,0 +1,60 @@ +# Setting up BridgeJS + +Package and build setup required for all BridgeJS workflows + +## Overview + +BridgeJS requires the JavaScriptKit package dependency, the experimental `Extern` Swift feature, and the BridgeJS build plugin. The same configuration applies whether you are exporting Swift to JavaScript, importing JavaScript into Swift with macros, and generating bindings from a TypeScript file. + +## Package.swift + +Add the JavaScriptKit dependency, enable the Extern feature on the target that uses BridgeJS, and register the BridgeJS plugin: + +```swift +// swift-tools-version:6.0 + +import PackageDescription + +let package = Package( + name: "MyApp", + dependencies: [ + .package(url: "https://github.com/swiftwasm/JavaScriptKit.git", branch: "main") + ], + targets: [ + .executableTarget( + name: "MyApp", + dependencies: ["JavaScriptKit"], + swiftSettings: [ + .enableExperimentalFeature("Extern") + ], + plugins: [ + .plugin(name: "BridgeJS", package: "JavaScriptKit") + ] + ) + ] +) +``` + +- **Dependency**: The target must depend on `"JavaScriptKit"`. +- **Extern feature**: Required because the generated bridge code uses `@_extern(wasm)`. +- **BridgeJS plugin**: Processes macro annotations to generate glue code and, [when present, `bridge-js.d.ts`; generates JS binding Swift code](). + +## Build command + +Build the package for the JavaScript/WebAssembly SDK: + +```bash +swift package --swift-sdk $SWIFT_SDK_ID js +``` + +This command: + +1. Runs the BridgeJS plugin +2. Compiles Swift to WebAssembly and generates JavaScript glue and TypeScript type definitions. +3. Writes output to `.build/plugins/PackageToJS/outputs/Package/`. + +For package layout and how to consume the output from JavaScript, see . + +## Larger projects + +The build plugin runs on every build. For larger projects, generating bridge code ahead of time can improve build performance. See . diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md index 668fe21b5..81a135af3 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md @@ -1,18 +1,22 @@ -# TypeScript and Swift Type Mapping +# Supported Types -Use this page as a quick reference for how common TypeScript types appear in Swift when importing, and how exported Swift types surface on the TypeScript side. +Swift types and their JavaScript/TypeScript equivalents at the BridgeJS boundary. -## Type mapping +## Swift and JavaScript type mapping -| TypeScript type | Swift type | -|:--|:--| -| `number` | `Double` | -| `string` | `String` | -| `boolean` | `Bool` | -| TODO | `Array` | -| TODO | `Dictionary` | -| `T \| undefined` | TODO | -| `T \| null` | `Optional` | -| `Promise` | `JSPromise` | -| `any` / `unknown` / `object` | `JSObject` | -| Other types | `JSObject` | +| Swift type | JavaScript | TypeScript | +|:--|:--|:--| +| `Int`, `UInt`, `Double`, `Float` | number | `number` | +| `String` | string | `string` | +| `Bool` | boolean | `boolean` | +| `Void` | - | `void` | +| `[T]` | array | `T[]` | +| `[String: T]` | object | `Record` | +| `Optional` | `null` or `T` | `T \| null` | +| ``JSUndefinedOr`` `` | `undefined` or `T` | `T \| undefined` | +| ``JSObject`` | object | `object` | +| ``JSValue`` | any | `any` | + +## See Also + +- diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md new file mode 100644 index 000000000..7ba25f7ae --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md @@ -0,0 +1,28 @@ +# Unsupported Features in BridgeJS + +Limitations and unsupported patterns when using BridgeJS. + +## Overview + +BridgeJS generates glue code per Swift target (module). Some patterns that are valid in Swift or TypeScript are not supported across the bridge today. This article summarizes the main limitations so you can design your APIs accordingly. + +## Type usage crossing module boundary + +BridgeJS does **not** support using a type across module boundaries in the following situations. + +### Exporting Swift: types from another Swift module + +If you have multiple Swift targets (e.g. a library and an app), you **cannot** use a type defined in one target in an exported API of another target. + +**Unsupported example:** Module `App` exports a function that takes or returns a type defined in module `Lib`: + +```swift +// In module Lib +@JS public struct LibPoint { + let x: Double + let y: Double +} + +// In module App (depends on Lib) - unsupported +@JS public func transform(_ p: LibPoint) -> LibPoint { ... } +``` diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/FAQ.md b/Sources/JavaScriptKit/Documentation.docc/Articles/FAQ.md new file mode 100644 index 000000000..c4f22a437 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/FAQ.md @@ -0,0 +1,28 @@ +# FAQ + +Common questions about JavaScriptKit and BridgeJS. + +## Why does the initialization need to be async? Why must I await it? + +Initialization is asynchronous because the runtime must **fetch and instantiate the WebAssembly module** before your Swift code can run. That means: + +1. **Fetching** the `.wasm` binary (e.g. over the network or from disk). +2. **Instantiating** it with `WebAssembly.instantiate()` (or `instantiateStreaming()`), which compiles the module and allocates the linear memory and table. + +Until that completes, there is no WebAssembly instance to call into, so the entry point that sets up the Swift-JavaScript bridge has to be `async` and must be `await`ed from the JavaScript host (e.g. in your `index.js` or HTML script). This matches the standard WebAssembly JavaScript API, which is promise-based. + +## Why does every imported JavaScript interface via BridgeJS declare `throws(JSException)`? + +This is a conservative, safety-oriented design. Calling into JavaScript can throw at any time. If the Swift call site does not expect errors (i.e. the call is not in a `throws` context and the compiler does not force handling), then when JavaScript throws: + +- Control leaves the WebAssembly call frames **without running function epilogues**. +- Even a `do { } catch { }` in Swift does not run its `catch` block in the way you might expect, because unwinding crosses the WASM/JS boundary. +- **`defer` blocks are not executed** in those frames. + +That can lead to **inconsistent memory state** and **resource leaks**. To avoid that, every call that might invoke JavaScript is modeled as throwing: all imported JS functions, property accessors, and related operations are marked with `throws(JSException)`. That way: + +- The compiler requires you to handle or propagate errors. +- You explicitly decide how to react to JavaScript exceptions (e.g. `try`/`catch`, or propagating `throws`). +- Epilogues and cleanup run in a well-defined way when you handle the error in Swift. + +So the “everything throws” rule is there to keep behavior predictable and safe when crossing the Swift-JavaScript boundary. diff --git a/Sources/JavaScriptKit/Documentation.docc/Documentation.md b/Sources/JavaScriptKit/Documentation.docc/Documentation.md index 51ee62539..097203f50 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Documentation.md +++ b/Sources/JavaScriptKit/Documentation.docc/Documentation.md @@ -59,14 +59,26 @@ Check out the [examples](https://github.com/swiftwasm/JavaScriptKit/tree/main/Ex - - - +- ### BridgeJS -- +- +- - +- +- +- - - - +- +- +- ``JS(namespace:enumStyle:)`` +- ``JSFunction(jsName:from:)`` +- ``JSClass(jsName:from:)`` +- ``JSGetter(jsName:from:)`` +- ``JSSetter(jsName:from:)`` ### Core APIs diff --git a/Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift b/Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift index 941b3f468..b3e80e66f 100644 --- a/Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift +++ b/Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift @@ -245,6 +245,97 @@ public class JSClosure: JSObject, JSClosureProtocol { #endif } +/// Heap storage for typed closures generated by BridgeJS. +/// +/// The storage is owned by the JavaScript closure and keeps the call-site metadata +/// so that calls after `release()` can report a helpful error. +@_spi(BridgeJS) public final class _BridgeJSTypedClosureBox: _BridgedSwiftClosureBox { + @_spi(BridgeJS) public var closure: Signature + var isManuallyReleased: Bool = false + + init(_ closure: Signature) { + self.closure = closure + } +} + +/// A typed handle to a JavaScript closure generated by BridgeJS. +/// +/// Use `JSTypedClosure` when you need to pass a Swift closure to JavaScript and then +/// manage its lifetime explicitly from Swift. You must call `release()` when the closure +/// is no longer needed. After releasing, any attempt to invoke the closure from JavaScript +/// throws a `JSException` (no crash), including a file/line message pointing to where the +/// typed closure was created. +/// +/// The underlying JavaScript function is also registered with a `FinalizationRegistry` as a +/// safety net to release the Swift closure storage if `release()` is forgotten, but this +/// is non-deterministic and should not be relied on for timely cleanup. +/// +/// ```swift +/// @JSFunction func someJSFunction(_ c: JSTypedClosure<(Int) -> Int>) throws(JSException) +/// let closure = JSTypedClosure<(Int) -> Int> { $0 + 1 } +/// defer { closure.release() } +/// try someJSFunction(closure) +/// ``` +public struct JSTypedClosure { + private let storage: _BridgeJSTypedClosureBox + private let _jsObject: JSObject + + @_spi(BridgeJS) + public init( + makeClosure: (_ pointer: UnsafeMutableRawPointer, _ fileID: UnsafePointer, _ line: UInt32) -> Int32, + body: Signature, + fileID: StaticString, + line: UInt32 + ) { + let storage = _BridgeJSTypedClosureBox(body) + // NOTE: Perform an unbalanced retain to give the closure box storage ownership + // to the JavaScript side. It will be balanced by two code paths: + // + // 1. When the JS closure made by `makeClosure` is GC'ed, the FinalizationRegistry + // will call `_bjs_release_swift_closure` to release the closure box storage. + // 2. When Swift side manually calls `release()` on the closure, it will release + // the closure box storage. + let pointer = Unmanaged.passRetained(storage).toOpaque() + let id = makeClosure(pointer, fileID.utf8Start, line) + self._jsObject = JSObject(id: UInt32(bitPattern: id)) + self.storage = storage + } + + @_spi(BridgeJS) + public func bridgeJSLowerParameter() -> Int32 { + return _jsObject.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) + public func bridgeJSLowerReturn() -> Int32 { + return _jsObject.bridgeJSLowerReturn() + } + + /// The underlying JavaScript function handle. + /// + /// Use this when you need to store or compare the JS function identity on the JavaScript side. + public var jsObject: JSObject { _jsObject } + + /// Releases the Swift closure storage owned by this typed closure. + /// + /// Call this exactly once when the closure is no longer needed by JavaScript. + /// After release, any attempt to invoke the closure from JavaScript throws a `JSException` + /// describing a call on a released `JSTypedClosure`. + /// Calling `release()` multiple times has no effect. + public func release() { + guard !storage.isManuallyReleased else { + // Already manually released + return + } + storage.isManuallyReleased = true + // Unregister the closure from the FinalizationRegistry because we here decrement + // the refcount of the storage, so the finalizer won't be responsible for releasing it. + _swift_js_closure_unregister(Int32(bitPattern: _jsObject.id)) + // Balance the retain given to the JavaScript side + Unmanaged.passUnretained(storage).release() + } +} + #if compiler(>=5.5) && (!hasFeature(Embedded) || os(WASI)) @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) private func makeAsyncClosure( diff --git a/Sources/JavaScriptKit/JSUndefinedOr.swift b/Sources/JavaScriptKit/JSUndefinedOr.swift new file mode 100644 index 000000000..de7be09b4 --- /dev/null +++ b/Sources/JavaScriptKit/JSUndefinedOr.swift @@ -0,0 +1,56 @@ +/// A wrapper that represents a JavaScript value of `Wrapped | undefined`. +/// +/// In BridgeJS, `Optional` is bridged as `Wrapped | null`. +/// Use `JSUndefinedOr` when the JavaScript API expects +/// `Wrapped | undefined` instead. +@frozen public enum JSUndefinedOr { + /// The JavaScript value is `undefined`. + case undefined + /// The JavaScript value is present and wrapped. + case value(Wrapped) + + /// Creates a wrapper from a Swift optional. + /// + /// - Parameter optional: The optional value to wrap. + /// `nil` becomes ``undefined`` and a non-`nil` value becomes ``value(_:)``. + @inlinable + public init(optional: Wrapped?) { + self = optional.map(Self.value) ?? .undefined + } + + /// Returns the wrapped value as a Swift optional. + /// + /// Returns `nil` when this value is ``undefined``. + @inlinable + public var asOptional: Wrapped? { + switch self { + case .undefined: + return nil + case .value(let wrapped): + return wrapped + } + } +} + +extension JSUndefinedOr: ConstructibleFromJSValue where Wrapped: ConstructibleFromJSValue { + public static func construct(from value: JSValue) -> Self? { + if value.isUndefined { return .undefined } + guard let wrapped = Wrapped.construct(from: value) else { return nil } + return .value(wrapped) + } +} + +extension JSUndefinedOr: ConvertibleToJSValue where Wrapped: ConvertibleToJSValue { + public var jsValue: JSValue { + switch self { + case .undefined: + return .undefined + case .value(let wrapped): + return wrapped.jsValue + } + } +} + +// MARK: - BridgeJS (via _BridgedAsOptional in BridgeJSIntrinsics) + +extension JSUndefinedOr: _BridgedAsOptional {} diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 329945f2f..67b3488bf 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -125,7 +125,7 @@ public macro JS(namespace: String? = nil, enumStyle: JSEnumStyle = .const) = Bui /// Example: /// /// ```swift -/// @_spi(Experimental) import JavaScriptKit +/// import JavaScriptKit /// /// @JSGetter var count: Int /// @@ -137,7 +137,6 @@ public macro JS(namespace: String? = nil, enumStyle: JSEnumStyle = .const) = Bui /// - Parameter from: Selects where the property is read from. /// Use `.global` to read from `globalThis` (e.g. `console`, `document`). @attached(accessor) -@_spi(Experimental) public macro JSGetter(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSGetterMacro") @@ -151,12 +150,11 @@ public macro JSGetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// Example: /// /// ```swift -/// @_spi(Experimental) import JavaScriptKit +/// import JavaScriptKit /// /// @JSSetter func setName(_ value: String) throws (JSException) /// ``` @attached(body) -@_spi(Experimental) public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSSetterMacro") @@ -167,7 +165,7 @@ public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// Example: /// /// ```swift -/// @_spi(Experimental) import JavaScriptKit +/// import JavaScriptKit /// /// @JSFunction func greet() throws (JSException) -> String /// @JSFunction init(_ name: String) throws (JSException) @@ -178,7 +176,6 @@ public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// - Parameter from: Selects where the function is looked up from. /// Use `.global` to call a function on `globalThis` (e.g. `setTimeout`). @attached(body) -@_spi(Experimental) public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSFunctionMacro") @@ -189,7 +186,7 @@ public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = /// Example: /// /// ```swift -/// @_spi(Experimental) import JavaScriptKit +/// import JavaScriptKit /// /// @JSClass /// struct JsGreeter { @@ -202,8 +199,7 @@ public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = /// /// - Parameter from: Selects where the constructor is looked up from. /// Use `.global` to construct globals like `WebSocket` via `globalThis`. -@attached(member, names: arbitrary) +@attached(member, names: named(jsObject), named(init(unsafelyWrapping:))) @attached(extension, conformances: _JSBridgedClass) -@_spi(Experimental) public macro JSClass(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSClassMacro") diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index aaa5f1b8a..b34b78bb0 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -50,10 +50,10 @@ extension GlobalNetworking.API.CallMethod: _BridgedSwiftCaseEnum { } } -extension GlobalConfiguration.PublicLogLevel: _BridgedSwiftEnumNoPayload { +extension GlobalConfiguration.PublicLogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension GlobalConfiguration.AvailablePort: _BridgedSwiftEnumNoPayload { +extension GlobalConfiguration.AvailablePort: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension Internal.SupportedServerMethod: _BridgedSwiftCaseEnum { @@ -215,12 +215,15 @@ extension GlobalNetworking.API.TestHTTPServer: ConvertibleToJSValue, _BridgedSwi #if arch(wasm32) @_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_TestHTTPServer_wrap") -fileprivate func _bjs_TestHTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestHTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TestHTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_TestHTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestHTTPServer_wrap_extern(pointer) +} @_expose(wasm, "bjs_TestInternalServer_init") @_cdecl("bjs_TestInternalServer_init") @@ -261,12 +264,15 @@ extension Internal.TestInternalServer: ConvertibleToJSValue, _BridgedSwiftHeapOb #if arch(wasm32) @_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_TestInternalServer_wrap") -fileprivate func _bjs_TestInternalServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestInternalServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TestInternalServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_TestInternalServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestInternalServer_wrap_extern(pointer) +} @_expose(wasm, "bjs_PublicConverter_init") @_cdecl("bjs_PublicConverter_init") @@ -308,9 +314,12 @@ extension GlobalUtils.PublicConverter: ConvertibleToJSValue, _BridgedSwiftHeapOb #if arch(wasm32) @_extern(wasm, module: "BridgeJSGlobalTests", name: "bjs_PublicConverter_wrap") -fileprivate func _bjs_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PublicConverter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } -#endif \ No newline at end of file +#endif +@inline(never) fileprivate func _bjs_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PublicConverter_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index 8b91ea964..e7bcf59b6 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -406,7 +406,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "GlobalStaticPropertyNamespace" } }, "type" : { @@ -424,7 +424,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "GlobalStaticPropertyNamespace" } }, "type" : { @@ -460,7 +460,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "GlobalStaticPropertyNamespace.NestedProperties" } }, "type" : { @@ -479,7 +479,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "GlobalStaticPropertyNamespace.NestedProperties" } }, "type" : { @@ -498,7 +498,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "GlobalStaticPropertyNamespace.NestedProperties" } }, "type" : { diff --git a/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift b/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift new file mode 100644 index 000000000..8078ed777 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ClosureSupportTests.swift @@ -0,0 +1,290 @@ +import XCTest +import JavaScriptKit + +@JSClass struct ClosureSupportImports { + + @JSFunction static func jsApplyVoid(_ callback: JSTypedClosure<() -> Void>) throws(JSException) + @JSFunction static func jsApplyBool(_ callback: JSTypedClosure<() -> Bool>) throws(JSException) -> Bool + @JSFunction static func jsApplyInt( + _ value: Int, + _ transform: JSTypedClosure<(Int) -> Int> + ) throws(JSException) -> Int + @JSFunction static func jsApplyDouble( + _ value: Double, + _ transform: JSTypedClosure<(Double) -> Double> + ) throws(JSException) -> Double + @JSFunction static func jsApplyString( + _ value: String, + _ transform: JSTypedClosure<(String) -> String> + ) throws(JSException) -> String + // @JSFunction static func jsApplyJSValue( + // _ value: JSValue, + // _ transform: JSTypedClosure<(JSValue) -> JSValue> + // ) throws(JSException) -> JSValue + @JSFunction static func jsApplyJSObject( + _ value: JSObject, + _ transform: JSTypedClosure<(JSObject) -> JSObject> + ) throws(JSException) -> JSObject + // @JSFunction static func jsApplyArrayInt( + // _ value: [Int], + // _ transform: JSTypedClosure<([Int]) -> [Int]> + // ) throws(JSException) -> [Int] + // @JSFunction static func jsApplyArrayDouble( + // _ value: [Double], + // _ transform: JSTypedClosure<([Double]) -> [Double]> + // ) throws(JSException) -> [Double] + // @JSFunction static func jsApplyArrayString( + // _ value: [String], + // _ transform: JSTypedClosure<([String]) -> [String]> + // ) throws(JSException) -> [String] + // @JSFunction static func jsApplyArrayJSValue( + // _ value: [JSValue], + // _ transform: JSTypedClosure<([JSValue]) -> [JSValue]> + // ) throws(JSException) -> [JSValue] + // @JSFunction static func jsApplyArrayJSObject( + // _ value: [JSObject], + // _ transform: JSTypedClosure<([JSObject]) -> [JSObject]> + // ) throws(JSException) -> [JSObject] + + @JSFunction static func jsMakeIntToInt(_ base: Int) throws(JSException) -> (Int) -> Int + @JSFunction static func jsMakeDoubleToDouble(_ base: Double) throws(JSException) -> (Double) -> Double + @JSFunction static func jsMakeStringToString(_ `prefix`: String) throws(JSException) -> (String) -> String + + @JSFunction static func jsCallTwice( + _ value: Int, + _ callback: JSTypedClosure<(Int) -> Void> + ) throws(JSException) -> Int + @JSFunction static func jsCallBinary(_ callback: JSTypedClosure<(Int, Int) -> Int>) throws(JSException) -> Int + @JSFunction static func jsCallTriple(_ callback: JSTypedClosure<(Int, Int, Int) -> Int>) throws(JSException) -> Int + @JSFunction static func jsCallAfterRelease(_ callback: JSTypedClosure<() -> Void>) throws(JSException) -> String + @JSFunction static func jsOptionalInvoke(_ callback: JSTypedClosure<() -> Bool>?) throws(JSException) -> Bool + @JSFunction static func jsStoreClosure(_ callback: JSTypedClosure<() -> Void>) throws(JSException) + @JSFunction static func jsCallStoredClosure() throws(JSException) + @JSFunction static func jsHeapCount() throws(JSException) -> Int + + @JSFunction static func runJsClosureSupportTests() throws(JSException) +} + +@JS class ClosureSupportExports { + @JS static func makeIntToInt(_ base: Int) -> (Int) -> Int { + return { $0 + base } + } + @JS static func makeDoubleToDouble(_ base: Double) -> (Double) -> Double { + return { $0 + base } + } + @JS static func makeStringToString(_ prefix: String) -> (String) -> String { + return { prefix + $0 } + } + + @JS static func makeJSIntToInt(_ base: Int) -> JSTypedClosure<(Int) -> Int> { + return JSTypedClosure { $0 + base } + } + @JS static func makeJSDoubleToDouble(_ base: Double) -> JSTypedClosure<(Double) -> Double> { + return JSTypedClosure { $0 + base } + } + @JS static func makeJSStringToString(_ prefix: String) -> JSTypedClosure<(String) -> String> { + return JSTypedClosure { prefix + $0 } + } +} + +final class ClosureSupportTests: XCTestCase { + + func testRunJsClosureSupportTests() throws { + try ClosureSupportImports.runJsClosureSupportTests() + } + + func testClosureParameterVoidToVoid() throws { + var called = false + let transform = JSTypedClosure<() -> Void> { + called = true + } + defer { transform.release() } + try ClosureSupportImports.jsApplyVoid(transform) + XCTAssertTrue(called) + } + + func testClosureParameterBoolToBool() throws { + let transform = JSTypedClosure<() -> Bool> { true } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyBool(transform) + XCTAssertTrue(result) + } + + func testClosureParameterIntToInt() throws { + let transform = JSTypedClosure { $0 * 2 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyInt(21, transform) + XCTAssertEqual(result, 42) + } + + func testClosureParameterDoubleToDouble() throws { + let transform = JSTypedClosure<(Double) -> Double> { $0 * 2 } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyDouble(21.0, transform) + XCTAssertEqual(result, 42.0) + } + + func testClosureParameterStringToString() throws { + let transform = JSTypedClosure { (value: String) in + value + ", world!" + } + defer { transform.release() } + let result = try ClosureSupportImports.jsApplyString("Hello", transform) + XCTAssertEqual(result, "Hello, world!") + } + + // func testClosureParameterJSValueToJSValue() throws { + // let transform = JSTypedClosure<(JSValue) -> JSValue> { $0 } + // defer { transform.release() } + // let result = try JSTypedClosureImports.jsApplyJSValue(.number(1), transform) + // XCTAssertEqual(result, .number(1)) + // } + + func testClosureParameterJSObjectToJSObject() throws { + let transform = JSTypedClosure<(JSObject) -> JSObject> { $0 } + defer { transform.release() } + let obj = JSObject() + let result = try ClosureSupportImports.jsApplyJSObject(obj, transform) + XCTAssertEqual(result, obj) + } + + // func testClosureParameterArrayIntToArrayInt() throws { + // let transform = JSTypedClosure<([Int]) -> [Int]> { $0 } + // defer { transform.release() } + // let result = try ClosureSupportImports.jsApplyArrayInt([1, 2, 3], transform) + // XCTAssertEqual(result, [1, 2, 3]) + // } + + // func testClosureParameterArrayDoubleToArrayDouble() throws { + // let transform = JSTypedClosure<([Double]) -> [Double]> { $0 } + // defer { transform.release() } + // let result = try ClosureSupportImports.jsApplyArrayDouble([1.0, 2.0, 3.0], transform) + // XCTAssertEqual(result, [1.0, 2.0, 3.0]) + // } + + // func testClosureParameterArrayStringToArrayString() throws { + // let transform = JSTypedClosure<([String]) -> [String]> { $0 } + // defer { transform.release() } + // let result = try ClosureSupportImports.jsApplyArrayString(["a", "b", "c"], transform) + // XCTAssertEqual(result, ["a", "b", "c"]) + // } + + // func testClosureParameterArrayJSValueToArrayJSValue() throws { + // let transform = JSTypedClosure<([JSValue]) -> [JSValue]> { $0 } + // defer { transform.release() } + // let result = try ClosureSupportImports.jsApplyArrayJSValue([.number(1), .number(2), .number(3)], transform) + // XCTAssertEqual(result, [.number(1), .number(2), .number(3)]) + // } + + // func testClosureParameterArrayJSObjectToArrayJSObject() throws { + // let transform = JSTypedClosure<([JSObject]) -> [JSObject]> { $0 } + // defer { transform.release() } + // let obj1 = JSObject() + // let obj2 = JSObject() + // let obj3 = JSObject() + // let result = try ClosureSupportImports.jsApplyArrayJSObject([obj1, obj2, obj3], transform) + // XCTAssertEqual(result, [obj1, obj2, obj3]) + // } + + func testClosureReturnIntToInt() throws { + let c = try ClosureSupportImports.jsMakeIntToInt(10) + XCTAssertEqual(c(0), 10) + XCTAssertEqual(c(32), 42) + } + + func testClosureReturnDoubleToDouble() throws { + let c = try ClosureSupportImports.jsMakeDoubleToDouble(10.0) + XCTAssertEqual(c(0.0), 10.0) + XCTAssertEqual(c(32.0), 42.0) + } + + func testClosureReturnStringToString() throws { + let c = try ClosureSupportImports.jsMakeStringToString("Hello, ") + XCTAssertEqual(c("world!"), "Hello, world!") + } + + func testClosureParameterIntToVoid() throws { + var total = 0 + let callback = JSTypedClosure<(Int) -> Void> { value in + total += value + } + defer { callback.release() } + let ret = try ClosureSupportImports.jsCallTwice(5, callback) + XCTAssertEqual(ret, 5) + XCTAssertEqual(total, 10) + } + + func testCallingReleasedClosureThrows() { + let transform = JSTypedClosure<(Int) -> Int> { $0 + 1 } + transform.release() + + do { + _ = try ClosureSupportImports.jsApplyInt(41, transform) + XCTFail("Expected JSException for released closure") + } catch let error { + let message = error.thrownValue.object?["message"].string + XCTAssertNotNil(message) + XCTAssertTrue(message?.contains(#fileID) ?? false, "message=\(message ?? "nil")") + } + } + + func testMultipleArity() throws { + let sum = JSTypedClosure<(Int, Int) -> Int> { $0 + $1 } + defer { sum.release() } + XCTAssertEqual(try ClosureSupportImports.jsCallBinary(sum), 3) + } + + func testTripleArity() throws { + let sum = JSTypedClosure<(Int, Int, Int) -> Int> { $0 + $1 + $2 } + defer { sum.release() } + XCTAssertEqual(try ClosureSupportImports.jsCallTriple(sum), 6) + } + + func testOptionalNoneSkipsCall() throws { + XCTAssertFalse(try ClosureSupportImports.jsOptionalInvoke(nil)) + } + + func testOptionalSomeCalls() throws { + var called = false + let closure = JSTypedClosure<() -> Bool> { + called = true + return true + } + defer { closure.release() } + XCTAssertTrue(try ClosureSupportImports.jsOptionalInvoke(closure)) + XCTAssertTrue(called) + } + + func testDropDuringCallThenThrows() throws { + var closure: JSTypedClosure<() -> Void>! = nil + closure = JSTypedClosure { + closure.release() + } + let message = try ClosureSupportImports.jsCallAfterRelease(closure) + XCTAssertTrue( + message.contains(#fileID), + "\"\(message)\" does not contain expected file name" + ) + } + + func testStoredClosureAfterReleaseThrows() throws { + let closure = JSTypedClosure<() -> Void> {} + try ClosureSupportImports.jsStoreClosure(closure) + closure.release() + XCTAssertThrowsError(try ClosureSupportImports.jsCallStoredClosure()) + } + + func testClosuresDoNotLeakHeapEntries() throws { + let baseline = try ClosureSupportImports.jsHeapCount() + + for _ in 0..<50 { + let closure: JSTypedClosure<(Int) -> Void> = JSTypedClosure { _ in } + _ = try? ClosureSupportImports.jsCallTwice(0, closure) + } + + // Trigger GC and read heap size from JS side + let after = try ClosureSupportImports.jsHeapCount() + XCTAssertEqual(after, baseline, "Heap entry count should return to baseline after GC") + } + +} diff --git a/Tests/BridgeJSRuntimeTests/DictionaryTests.swift b/Tests/BridgeJSRuntimeTests/DictionaryTests.swift new file mode 100644 index 000000000..95f2706e6 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/DictionaryTests.swift @@ -0,0 +1,96 @@ +@_spi(BridgeJS) import JavaScriptKit +import XCTest + +final class DictionaryTests: XCTestCase { + func testRoundTripDictionary() throws { + let input: [String: Int] = ["a": 1, "b": 2] + let result = try jsRoundTripDictionary(input) + XCTAssertEqual(result, input) + } + + func testRoundTripDictionaryBool() throws { + let input: [String: Bool] = ["yes": true, "no": false] + let result = try jsRoundTripDictionaryBool(input) + XCTAssertEqual(result, input) + } + + func testRoundTripDictionaryDouble() throws { + let input: [String: Double] = ["pi": 3.14, "tau": 6.28] + let result = try jsRoundTripDictionaryDouble(input) + XCTAssertEqual(result, input) + } + + func testRoundTripDictionaryJSObject() throws { + let global = JSObject.global + let input: [String: JSObject] = [ + "global": global + ] + let result = try jsRoundTripDictionaryJSObject(input) + XCTAssertEqual(result, input) + } + + func testRoundTripDictionaryJSValue() throws { + let input: [String: JSValue] = [ + "number": .number(123.5), + "boolean": .boolean(true), + "string": .string("hello"), + "null": .null, + ] + let result = try jsRoundTripDictionaryJSValue(input) + XCTAssertEqual(result, input) + } + + func testRoundTripNestedDictionary() throws { + let input: [String: [Double]] = [ + "xs": [1.0, 2.5], + "ys": [], + ] + let result = try jsRoundTripNestedDictionary(input) + XCTAssertEqual(result, input) + } + + func testRoundTripOptionalDictionaryNull() throws { + let some: [String: String]? = ["k": "v"] + XCTAssertEqual(try jsRoundTripOptionalDictionary(some), some) + XCTAssertNil(try jsRoundTripOptionalDictionary(nil)) + } + + func testRoundTripOptionalDictionaryUndefined() throws { + let some: JSUndefinedOr<[String: Int]> = .value(["n": 42]) + let undefined: JSUndefinedOr<[String: Int]> = .undefined + + let returnedSome = try jsRoundTripUndefinedDictionary(some) + switch returnedSome { + case .value(let dict): + XCTAssertEqual(dict, ["n": 42]) + case .undefined: + XCTFail("Expected defined dictionary") + } + + let returnedUndefined = try jsRoundTripUndefinedDictionary(undefined) + switch returnedUndefined { + case .value: + XCTFail("Expected undefined") + case .undefined: + break + } + } +} + +@JSFunction func jsRoundTripDictionary(_ values: [String: Int]) throws(JSException) -> [String: Int] + +@JSFunction func jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] + +@JSFunction func jsRoundTripDictionaryDouble(_ values: [String: Double]) throws(JSException) -> [String: Double] + +@JSFunction func jsRoundTripDictionaryJSObject(_ values: [String: JSObject]) throws(JSException) -> [String: JSObject] + +@JSFunction func jsRoundTripDictionaryJSValue(_ values: [String: JSValue]) throws(JSException) -> [String: JSValue] + +@JSFunction func jsRoundTripNestedDictionary(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] + +@JSFunction func jsRoundTripOptionalDictionary(_ values: [String: String]?) throws(JSException) -> [String: String]? + +@JSFunction func jsRoundTripUndefinedDictionary( + _ values: JSUndefinedOr<[String: Int]> +) throws(JSException) -> JSUndefinedOr<[String: Int]> diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 2aee862c6..97c2d5fbf 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1,5 +1,5 @@ import XCTest -@_spi(Experimental) import JavaScriptKit +import JavaScriptKit import JavaScriptEventLoop @_extern(wasm, module: "BridgeJSRuntimeTests", name: "runJsWorks") @@ -52,6 +52,30 @@ func runJsWorks() -> Void return v } +@JS func roundTripDictionaryExport(v: [String: Int]) -> [String: Int] { + return v +} + +@JS func roundTripOptionalDictionaryExport(v: [String: String]?) -> [String: String]? { + return v +} + +@JS func roundTripJSValue(v: JSValue) -> JSValue { + return v +} + +@JS func roundTripOptionalJSValue(v: JSValue?) -> JSValue? { + return v +} + +@JS func roundTripJSValueArray(v: [JSValue]) -> [JSValue] { + return v +} + +@JS func roundTripOptionalJSValueArray(v: [JSValue]?) -> [JSValue]? { + return v +} + @JSClass struct Foo { @JSGetter var value: String @JSFunction init(_ value: String) throws(JSException) @@ -295,6 +319,16 @@ struct TestError: Error { return String(value) } } + + @JS enum StringUtils { + @JS static func uppercase(_ text: String) -> String { + return text.uppercased() + } + + @JS static func lowercase(_ text: String) -> String { + return text.lowercased() + } + } } @JS enum Networking { @@ -497,128 +531,31 @@ enum ComplexResult { return result } -// MARK: - Optionals - -@JS func roundTripOptionalString(name: String?) -> String? { - return name -} - -@JS func roundTripOptionalInt(value: Int?) -> Int? { - return value -} - -@JS func roundTripOptionalBool(flag: Bool?) -> Bool? { - return flag -} - -@JS func roundTripOptionalFloat(number: Float?) -> Float? { - return number -} - -@JS func roundTripOptionalDouble(precision: Double?) -> Double? { - return precision -} - -@JS func roundTripOptionalSyntax(name: Optional) -> Optional { - return name -} - -@JS func roundTripOptionalMixSyntax(name: String?) -> Optional { - return name -} - -@JS func roundTripOptionalSwiftSyntax(name: Swift.Optional) -> Swift.Optional { - return name -} - -@JS func roundTripOptionalWithSpaces(value: Optional) -> Optional { - return value -} - -typealias OptionalAge = Int? -@JS func roundTripOptionalTypeAlias(age: OptionalAge) -> OptionalAge { - return age -} - -@JS func roundTripOptionalStatus(value: Status?) -> Status? { - return value -} - -@JS func roundTripOptionalTheme(value: Theme?) -> Theme? { - return value -} - -@JS func roundTripOptionalHttpStatus(value: HttpStatus?) -> HttpStatus? { - return value -} - -@JS func roundTripOptionalTSDirection(value: TSDirection?) -> TSDirection? { - return value -} - -@JS func roundTripOptionalTSTheme(value: TSTheme?) -> TSTheme? { - return value -} - -@JS func roundTripOptionalNetworkingAPIMethod(_ method: Networking.API.Method?) -> Networking.API.Method? { - return method -} - -@JS func roundTripOptionalAPIResult(value: APIResult?) -> APIResult? { - return value -} - -@JS func compareAPIResults(_ r1: APIResult?, _ r2: APIResult?) -> String { - let r1Str: String - switch r1 { - case .none: r1Str = "nil" - case .some(.success(let msg)): r1Str = "success:\(msg)" - case .some(.failure(let code)): r1Str = "failure:\(code)" - case .some(.info): r1Str = "info" - case .some(.flag(let b)): r1Str = "flag:\(b)" - case .some(.rate(let r)): r1Str = "rate:\(r)" - case .some(.precise(let p)): r1Str = "precise:\(p)" - } - - let r2Str: String - switch r2 { - case .none: r2Str = "nil" - case .some(.success(let msg)): r2Str = "success:\(msg)" - case .some(.failure(let code)): r2Str = "failure:\(code)" - case .some(.info): r2Str = "info" - case .some(.flag(let b)): r2Str = "flag:\(b)" - case .some(.rate(let r)): r2Str = "rate:\(r)" - case .some(.precise(let p)): r2Str = "precise:\(p)" - } - - return "r1:\(r1Str),r2:\(r2Str)" -} - -@JS func roundTripOptionalComplexResult(_ result: ComplexResult?) -> ComplexResult? { - return result +@JS +enum AllTypesResult { + case structPayload(Address) + case classPayload(Greeter) + case jsObjectPayload(JSObject) + case nestedEnum(APIResult) + case arrayPayload([Int]) + case jsClassPayload(Foo) + case empty } -@JS func roundTripOptionalClass(value: Greeter?) -> Greeter? { - return value +@JS func roundTripAllTypesResult(_ result: AllTypesResult) -> AllTypesResult { + result } -@JS class OptionalPropertyHolder { - @JS var optionalName: String? - @JS var optionalAge: Int? = nil - @JS var optionalGreeter: Greeter? = nil - @JS init(optionalName: String?) { - self.optionalName = optionalName - } +@JS enum TypedPayloadResult { + case precision(Precision) + case direction(Direction) + case optPrecision(Precision?) + case optDirection(Direction?) + case empty } -@JS -enum APIOptionalResult { - case success(String?) - case failure(Int?, Bool?) - case status(Bool?, Int?, String?) -} -@JS func roundTripOptionalAPIOptionalResult(result: APIOptionalResult?) -> APIOptionalResult? { - return result +@JS func roundTripTypedPayloadResult(_ result: TypedPayloadResult) -> TypedPayloadResult { + result } // MARK: - Property Tests @@ -788,6 +725,17 @@ enum APIOptionalResult { } } +@JS(namespace: "Services.Graph") +enum GraphOperations { + @JS static func createGraph(rootId: Int) -> Int { + return rootId * 10 + } + + @JS static func nodeCount(graphId: Int) -> Int { + return graphId + } +} + // MARK: - Default Parameters @JS func testStringDefault(message: String = "Hello World") -> String { @@ -1407,6 +1355,12 @@ enum APIOptionalResult { @JS func roundTripOpaquePointerArray(_ values: [OpaquePointer]) -> [OpaquePointer] { return values } +@JS func roundTripUnsafePointerArray(_ values: [UnsafePointer]) -> [UnsafePointer] { + return values +} +@JS func roundTripUnsafeMutablePointerArray(_ values: [UnsafeMutablePointer]) -> [UnsafeMutablePointer] { + return values +} @JS func consumeDataProcessorArrayType(_ processors: [DataProcessor]) -> Int { return processors.count @@ -1416,6 +1370,22 @@ enum APIOptionalResult { return processors } +@JS func roundTripJSObjectArray(_ objects: [JSObject]) -> [JSObject] { + return objects +} + +@JS func roundTripOptionalJSObjectArray(_ objects: [JSObject?]) -> [JSObject?] { + return objects +} + +@JS func roundTripFooArray(_ foos: [Foo]) -> [Foo] { + return foos +} + +@JS func roundTripOptionalFooArray(_ foos: [Foo?]) -> [Foo?] { + return foos +} + class ExportAPITests: XCTestCase { func testAll() { var hasDeinitGreeter = false diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift index b0b24137a..c63a421e0 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift @@ -4,62 +4,87 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -@_spi(Experimental) import JavaScriptKit +@_spi(BridgeJS) import JavaScriptKit -@JSFunction func jsRoundTripVoid() throws (JSException) -> Void +@JSFunction func jsRoundTripVoid() throws(JSException) -> Void -@JSFunction func jsRoundTripNumber(_ v: Double) throws (JSException) -> Double +@JSFunction func jsRoundTripNumber(_ v: Double) throws(JSException) -> Double -@JSFunction func jsRoundTripBool(_ v: Bool) throws (JSException) -> Bool +@JSFunction func jsRoundTripBool(_ v: Bool) throws(JSException) -> Bool -@JSFunction func jsRoundTripString(_ v: String) throws (JSException) -> String +@JSFunction func jsRoundTripString(_ v: String) throws(JSException) -> String -@JSFunction func jsThrowOrVoid(_ shouldThrow: Bool) throws (JSException) -> Void +@JSFunction func jsRoundTripJSValue(_ v: JSValue) throws(JSException) -> JSValue -@JSFunction func jsThrowOrNumber(_ shouldThrow: Bool) throws (JSException) -> Double +@JSFunction func jsRoundTripJSValueArray(_ v: [JSValue]) throws(JSException) -> [JSValue] -@JSFunction func jsThrowOrBool(_ shouldThrow: Bool) throws (JSException) -> Bool +@JSFunction func jsRoundTripOptionalJSValueArray(_ v: Optional<[JSValue]>) throws(JSException) -> Optional<[JSValue]> -@JSFunction func jsThrowOrString(_ shouldThrow: Bool) throws (JSException) -> String +@JSFunction func jsThrowOrVoid(_ shouldThrow: Bool) throws(JSException) -> Void + +@JSFunction func jsThrowOrNumber(_ shouldThrow: Bool) throws(JSException) -> Double + +@JSFunction func jsThrowOrBool(_ shouldThrow: Bool) throws(JSException) -> Bool + +@JSFunction func jsThrowOrString(_ shouldThrow: Bool) throws(JSException) -> String enum FeatureFlag: String { case foo = "foo" case bar = "bar" } -extension FeatureFlag: _BridgedSwiftEnumNoPayload {} +extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} -@JSFunction func jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws (JSException) -> FeatureFlag +@JSFunction func jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> FeatureFlag @JSClass struct JsGreeter { @JSGetter var name: String - @JSSetter func setName(_ value: String) throws (JSException) + @JSSetter func setName(_ value: String) throws(JSException) @JSGetter var `prefix`: String - @JSFunction init(_ name: String, _ `prefix`: String) throws (JSException) - @JSFunction func greet() throws (JSException) -> String - @JSFunction func changeName(_ name: String) throws (JSException) -> Void + @JSFunction init(_ name: String, _ `prefix`: String) throws(JSException) + @JSFunction func greet() throws(JSException) -> String + @JSFunction func changeName(_ name: String) throws(JSException) -> Void } -@JSFunction func runAsyncWorks() throws (JSException) -> JSPromise +@JSFunction func runAsyncWorks() throws(JSException) -> JSPromise -@JSFunction(jsName: "$jsWeirdFunction") func _jsWeirdFunction() throws (JSException) -> Double +@JSFunction(jsName: "$jsWeirdFunction") func _jsWeirdFunction() throws(JSException) -> Double @JSClass(jsName: "$WeirdClass") struct _WeirdClass { - @JSFunction init() throws (JSException) - @JSFunction(jsName: "method-with-dashes") func method_with_dashes() throws (JSException) -> String + @JSFunction init() throws(JSException) + @JSFunction(jsName: "method-with-dashes") func method_with_dashes() throws(JSException) -> String +} + +@JSClass struct StaticBox { + @JSFunction init(_ value: Double) throws(JSException) + @JSFunction func value() throws(JSException) -> Double + @JSFunction static func create(_ value: Double) throws(JSException) -> StaticBox + @JSFunction static func value() throws(JSException) -> Double + @JSFunction static func makeDefault() throws(JSException) -> StaticBox + @JSFunction(jsName: "with-dashes") static func with_dashes() throws(JSException) -> StaticBox } -@JSFunction(from: .global) func parseInt(_ string: String) throws (JSException) -> Double +@JSFunction func jsRoundTripNumberArray(_ values: [Double]) throws(JSException) -> [Double] + +@JSFunction func jsRoundTripStringArray(_ values: [String]) throws(JSException) -> [String] + +@JSFunction func jsRoundTripBoolArray(_ values: [Bool]) throws(JSException) -> [Bool] + +@JSFunction func jsSumNumberArray(_ values: [Double]) throws(JSException) -> Double + +@JSFunction func jsCreateNumberArray() throws(JSException) -> [Double] + +@JSFunction(from: .global) func parseInt(_ string: String) throws(JSException) -> Double @JSClass(from: .global) struct Animal { @JSGetter var name: String - @JSSetter func setName(_ value: String) throws (JSException) + @JSSetter func setName(_ value: String) throws(JSException) @JSGetter var age: Double - @JSSetter func setAge(_ value: Double) throws (JSException) + @JSSetter func setAge(_ value: Double) throws(JSException) @JSGetter var isCat: Bool - @JSSetter func setIsCat(_ value: Bool) throws (JSException) - @JSFunction init(_ name: String, _ age: Double, _ isCat: Bool) throws (JSException) - @JSFunction func bark() throws (JSException) -> String - @JSFunction func getIsCat() throws (JSException) -> Bool + @JSSetter func setIsCat(_ value: Bool) throws(JSException) + @JSFunction init(_ name: String, _ age: Double, _ isCat: Bool) throws(JSException) + @JSFunction func bark() throws(JSException) -> String + @JSFunction func getIsCat() throws(JSException) -> Bool } -@JSGetter(from: .global) var globalObject1: JSObject +@JSGetter(from: .global) var globalObject1: JSValue diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 35a53805d..8a775c150 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -9,25 +9,29 @@ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests10HttpStatusO_Si: _BridgedSwiftClosureBox { - let closure: (HttpStatus) -> Int - init(_ closure: @escaping (HttpStatus) -> Int) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si { - static func bridgeJSLower(_ closure: @escaping (HttpStatus) -> Int) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests10HttpStatusO_Si(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (HttpStatus) -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -43,12 +47,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si { } } +extension JSTypedClosure where Signature == (HttpStatus) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (HttpStatus) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests10HttpStatusO_Si>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(HttpStatus.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(HttpStatus) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(HttpStatus.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -57,25 +72,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10H #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_SS: _BridgedSwiftClosureBox { - let closure: (Theme) -> String - init(_ closure: @escaping (Theme) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS { - static func bridgeJSLower(_ closure: @escaping (Theme) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Theme) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -91,12 +110,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS { } } +extension JSTypedClosure where Signature == (Theme) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Theme) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -105,25 +135,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5Th #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_Sb: _BridgedSwiftClosureBox { - let closure: (Theme) -> Bool - init(_ closure: @escaping (Theme) -> Bool) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb { - static func bridgeJSLower(_ closure: @escaping (Theme) -> Bool) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_Sb(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Theme) -> Bool { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -139,12 +173,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb { } } +extension JSTypedClosure where Signature == (Theme) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Theme) -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests5ThemeO_Sb>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Theme) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Theme.bridgeJSLiftParameter(param0Bytes, param0Length)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -153,25 +198,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5Th #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests7GreeterC_SS: _BridgedSwiftClosureBox { - let closure: (Greeter) -> String - init(_ closure: @escaping (Greeter) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS { - static func bridgeJSLower(_ closure: @escaping (Greeter) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests7GreeterC_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Greeter) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -187,12 +236,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS { } } +extension JSTypedClosure where Signature == (Greeter) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Greeter) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests7GreeterC_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Greeter.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Greeter) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Greeter.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -200,26 +260,93 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7Gr } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ callback: Int32, _ param0: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC_extern(boxPtr, file, line) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests9APIResultO_SS: _BridgedSwiftClosureBox { - let closure: (APIResult) -> String - init(_ closure: @escaping (APIResult) -> String) { - self.closure = closure +private enum _BJS_Closure_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC { + static func bridgeJSLift(_ callbackId: Int32) -> (JSObject) -> JSObject { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(callbackValue, param0Value) + return JSObject.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } } } -private enum _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS { - static func bridgeJSLower(_ closure: @escaping (APIResult) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests9APIResultO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() +extension JSTypedClosure where Signature == (JSObject) -> JSObject { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (JSObject) -> JSObject) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC, + body: body, + fileID: fileID, + line: line + ) } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(JSObject) -> JSObject>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(JSObject.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS { static func bridgeJSLift(_ callbackId: Int32) -> (APIResult) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -235,12 +362,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS { } } +extension JSTypedClosure where Signature == (APIResult) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (APIResult) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests9APIResultO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(APIResult.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(APIResult) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(APIResult.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -249,25 +387,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9AP #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_SS: _BridgedSwiftClosureBox { - let closure: (Direction) -> String - init(_ closure: @escaping (Direction) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS { - static func bridgeJSLower(_ closure: @escaping (Direction) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Direction) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -283,12 +425,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS { } } +extension JSTypedClosure where Signature == (Direction) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Direction) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Direction.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Direction.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -297,25 +450,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9Di #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_Sb: _BridgedSwiftClosureBox { - let closure: (Direction) -> Bool - init(_ closure: @escaping (Direction) -> Bool) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_Sb { - static func bridgeJSLower(_ closure: @escaping (Direction) -> Bool) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_Sb(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Direction) -> Bool { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -331,12 +488,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_Sb { } } +extension JSTypedClosure where Signature == (Direction) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Direction) -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTests9DirectionO_Sb>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Direction.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Direction) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Direction.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -345,25 +513,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9Di #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ callback: Int32, _ param0: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSS_7GreeterC: _BridgedSwiftClosureBox { - let closure: (String) -> Greeter - init(_ closure: @escaping (String) -> Greeter) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { - static func bridgeJSLower(_ closure: @escaping (String) -> Greeter) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSS_7GreeterC(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (String) -> Greeter { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -379,12 +551,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { } } +extension JSTypedClosure where Signature == (String) -> Greeter { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> Greeter) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSS_7GreeterC>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> Greeter>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -393,25 +576,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSS_SS: _BridgedSwiftClosureBox { - let closure: (String) -> String - init(_ closure: @escaping (String) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { - static func bridgeJSLower(_ closure: @escaping (String) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSS_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (String) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -427,12 +614,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { } } +extension JSTypedClosure where Signature == (String) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSS_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -440,36 +638,38 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_ } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(_ callback: Int32, _ param0: Float64) -> Float64 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(_ callback: Int32, _ param0: Float64) -> Float64 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(_ callback: Int32, _ param0: Float64) -> Float64 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSiSSSd_SS: _BridgedSwiftClosureBox { - let closure: (Int, String, Double) -> String - init(_ closure: @escaping (Int, String, Double) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { - static func bridgeJSLower(_ closure: @escaping (Int, String, Double) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSiSSSd_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Int, String, Double) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_Sd { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) -> Double { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0, param1, param2 in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() - let param1Value = param1.bridgeJSLowerParameter() - let param2Value = param2.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Value, param2Value) - return String.bridgeJSLiftReturn(ret) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(callbackValue, param0Value) + return Double.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -477,12 +677,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Void { +extension JSTypedClosure where Signature == (Double) -> Double { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) -> Double) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Float64 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSiSSSd_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Int.bridgeJSLiftParameter(param0), String.bridgeJSLiftParameter(param1Bytes, param1Length), Double.bridgeJSLiftParameter(param2)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) -> Double>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Double.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -490,34 +701,40 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiS } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Float64) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(callback, param0, param1, param2) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSi_Si: _BridgedSwiftClosureBox { - let closure: (Int) -> Int - init(_ closure: @escaping (Int) -> Int) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_Si { - static func bridgeJSLower(_ closure: @escaping (Int) -> Int) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSi_Si(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Int { +private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (Int, String, Double) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0, param1, param2) in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(callbackValue, param0Value) - return Int.bridgeJSLiftReturn(ret) + let param1Value = param1.bridgeJSLowerParameter() + let param2Value = param2.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Value, param2Value) + return String.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -525,12 +742,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_Si { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { +extension JSTypedClosure where Signature == (Int, String, Double) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int, String, Double) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1Bytes: Int32, _ param1Length: Int32, _ param2: Float64) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSi_Si>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Int.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, String, Double) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0), String.bridgeJSLiftParameter(param1Bytes, param1Length), Double.bridgeJSLiftParameter(param2)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -538,33 +766,40 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_ } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(_ callback: Int32, _ param0: Int32, _ param1: Int32, _ param2: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(callback, param0, param1, param2) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSi_y: _BridgedSwiftClosureBox { - let closure: (Int) -> Void - init(_ closure: @escaping (Int) -> Void) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_y { - static func bridgeJSLower(_ closure: @escaping (Int) -> Void) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSi_y(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSiSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Int, Int, Int) -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0, param1, param2) in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(callbackValue, param0Value) + let param1Value = param1.bridgeJSLowerParameter() + let param2Value = param2.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(callbackValue, param0Value, param1Value, param2Value) + return Int.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -572,46 +807,63 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_y { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +extension JSTypedClosure where Signature == (Int, Int, Int) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int, Int, Int) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1: Int32, _ param2: Int32) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSi_y>.fromOpaque(boxPtr).takeUnretainedValue() - box.closure(Int.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, Int, Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0), Int.bridgeJSLiftParameter(param1), Int.bridgeJSLiftParameter(param2)) + return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(_ callback: Int32, _ param0: Int32, _ param1: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(_ callback: Int32, _ param0: Int32, _ param1: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(callback, param0, param1) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSq5ThemeO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSq5ThemeO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Int, Int) -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0, param1) in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Value) - return String.bridgeJSLiftReturn(ret) + let param0Value = param0.bridgeJSLowerParameter() + let param1Value = param1.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(callbackValue, param0Value, param1Value) + return Int.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -619,12 +871,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +extension JSTypedClosure where Signature == (Int, Int) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int, Int) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32, _ param1: Int32) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSq5ThemeO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int, Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0), Int.bridgeJSLiftParameter(param1)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -632,34 +895,38 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5 } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ callback: Int32, _ param0: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(callback, param0) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSq7GreeterC_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSq7GreeterC_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(callbackValue, param0IsSome, param0Pointer) - return String.bridgeJSLiftReturn(ret) + let param0Value = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(callbackValue, param0Value) + return Int.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -667,12 +934,210 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") +extension JSTypedClosure where Signature == (Int) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Int.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_y { + static func bridgeJSLift(_ callbackId: Int32) -> (Int) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Int) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Int) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Int) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Int.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Value) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(callback, param0IsSome, param0Pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(callbackValue, param0IsSome, param0Pointer) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSq7GreeterC_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -680,26 +1145,93 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7 } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC(_ callback: Int32, _ param0IsSome: Int32, _ param0Pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(callback, param0IsSome, param0Pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC_extern(boxPtr, file, line) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSq9APIResultO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure +private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC(callbackValue, param0IsSome, param0Pointer) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } } } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSq9APIResultO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() +extension JSTypedClosure where Signature == (Optional) -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> Optional) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC, + body: body, + fileID: fileID, + line: line + ) } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(callback, param0IsSome, param0CaseId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS { static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -715,12 +1247,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS { } } +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSq9APIResultO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -729,25 +1272,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9 #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(callback, param0IsSome, param0Value) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSq9DirectionO_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSq9DirectionO_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -763,12 +1310,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS { } } +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSq9DirectionO_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -777,25 +1335,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9 #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(callback, param0IsSome, param0Value) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSqSS_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSqSS_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -811,12 +1373,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { } } +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSqSS_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -825,25 +1398,29 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(callback, param0IsSome, param0Value) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsSqSi_SS: _BridgedSwiftClosureBox { - let closure: (Optional) -> String - init(_ closure: @escaping (Optional) -> String) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(boxPtr, file, line) } private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { - static func bridgeJSLower(_ closure: @escaping (Optional) -> String) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsSqSi_SS(closure) - return Unmanaged.passRetained(box).toOpaque() - } static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in @@ -859,12 +1436,23 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { } } +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + @_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") @_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsSqSi_SS>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -872,33 +1460,37 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ callback: Int32) -> UnsafeMutableRawPointer +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ callback: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(callback) +} -private final class _BJS_ClosureBox_20BridgeJSRuntimeTestsy_Sq7GreeterC: _BridgedSwiftClosureBox { - let closure: () -> Optional - init(_ closure: @escaping () -> Optional) { - self.closure = closure - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { - static func bridgeJSLower(_ closure: @escaping () -> Optional) -> UnsafeMutableRawPointer { - let box = _BJS_ClosureBox_20BridgeJSRuntimeTestsy_Sq7GreeterC(closure) - return Unmanaged.passRetained(box).toOpaque() - } - static func bridgeJSLift(_ callbackId: Int32) -> () -> Optional { +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Bool { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(callbackValue) - return Optional.bridgeJSLiftReturn(ret) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(callbackValue) + return Bool.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -906,26 +1498,159 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer) -> Void { +extension JSTypedClosure where Signature == () -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let box = Unmanaged<_BJS_ClosureBox_20BridgeJSRuntimeTestsy_Sq7GreeterC>.fromOpaque(boxPtr).takeUnretainedValue() - let result = box.closure() + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ callback: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(callback) +} - func increment(by amount: Int) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let amountValue = amount.bridgeJSLowerParameter() - _extern_increment(jsObjectValue, amountValue) - } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(callbackValue) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Optional) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_y { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else + fatalError("Only available on WebAssembly") + #endif +} + +struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + func increment(by amount: Int) -> Void { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let amountValue = amount.bridgeJSLowerParameter() + _extern_increment(jsObjectValue, amountValue) + } func getValue() -> Int { let jsObjectValue = jsObject.bridgeJSLowerParameter() @@ -1120,95 +1845,365 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } } +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_increment") -fileprivate func _extern_increment(_ jsObject: Int32, _ amount: Int32) -> Void +fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void +#else +fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_increment(_ jsObject: Int32, _ amount: Int32) -> Void { + return _extern_increment_extern(jsObject, amount) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getValue") -fileprivate func _extern_getValue(_ jsObject: Int32) -> Int32 +fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getValue(_ jsObject: Int32) -> Int32 { + return _extern_getValue_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_setLabelElements") -fileprivate func _extern_setLabelElements(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void +fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void +#else +fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_setLabelElements(_ jsObject: Int32, _ labelPrefix: Int32, _ labelSuffix: Int32) -> Void { + return _extern_setLabelElements_extern(jsObject, labelPrefix, labelSuffix) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getLabel") -fileprivate func _extern_getLabel(_ jsObject: Int32) -> Int32 +fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getLabel(_ jsObject: Int32) -> Int32 { + return _extern_getLabel_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_isEven") -fileprivate func _extern_isEven(_ jsObject: Int32) -> Int32 +fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_isEven(_ jsObject: Int32) -> Int32 { + return _extern_isEven_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processGreeter") -fileprivate func _extern_processGreeter(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 +fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_processGreeter(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { + return _extern_processGreeter_extern(jsObject, greeter) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createGreeter") -fileprivate func _extern_createGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createGreeter_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processOptionalGreeter") -fileprivate func _extern_processOptionalGreeter(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_processOptionalGreeter(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { + return _extern_processOptionalGreeter_extern(jsObject, greeterIsSome, greeterPointer) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createOptionalGreeter") -fileprivate func _extern_createOptionalGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createOptionalGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createOptionalGreeter_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_handleAPIResult") -fileprivate func _extern_handleAPIResult(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void +fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void +#else +fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_handleAPIResult(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + return _extern_handleAPIResult_extern(jsObject, resultIsSome, resultCaseId) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getAPIResult") -fileprivate func _extern_getAPIResult(_ jsObject: Int32) -> Int32 +fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getAPIResult(_ jsObject: Int32) -> Int32 { + return _extern_getAPIResult_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_get") -fileprivate func bjs_DataProcessor_count_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_count_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_count_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_set") -fileprivate func bjs_DataProcessor_count_set(_ jsObject: Int32, _ newValue: Int32) -> Void +fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_count_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_DataProcessor_count_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_name_get") -fileprivate func bjs_DataProcessor_name_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_name_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_name_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_get") -fileprivate func bjs_DataProcessor_optionalTag_get(_ jsObject: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTag_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalTag_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_set") -fileprivate func bjs_DataProcessor_optionalTag_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTag_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_optionalTag_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_get") -fileprivate func bjs_DataProcessor_optionalCount_get(_ jsObject: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalCount_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalCount_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_set") -fileprivate func bjs_DataProcessor_optionalCount_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalCount_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_optionalCount_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_get") -fileprivate func bjs_DataProcessor_direction_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_direction_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_direction_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_set") -fileprivate func bjs_DataProcessor_direction_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_direction_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_direction_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_get") -fileprivate func bjs_DataProcessor_optionalTheme_get(_ jsObject: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalTheme_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_set") -fileprivate func bjs_DataProcessor_optionalTheme_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_optionalTheme_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_get") -fileprivate func bjs_DataProcessor_httpStatus_get(_ jsObject: Int32) -> Void +fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_httpStatus_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_httpStatus_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_set") -fileprivate func bjs_DataProcessor_httpStatus_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_httpStatus_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_httpStatus_set_extern(jsObject, newValueIsSome, newValueValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_get") -fileprivate func bjs_DataProcessor_apiResult_get(_ jsObject: Int32) -> Int32 +fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_apiResult_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_apiResult_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_set") -fileprivate func bjs_DataProcessor_apiResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void +fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_apiResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + return bjs_DataProcessor_apiResult_set_extern(jsObject, newValueIsSome, newValueCaseId) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_get") -fileprivate func bjs_DataProcessor_helper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_helper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_helper_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_set") -fileprivate func bjs_DataProcessor_helper_set(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void +fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void +#else +fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_helper_set(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { + return bjs_DataProcessor_helper_set_extern(jsObject, newValue) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_get") -fileprivate func bjs_DataProcessor_optionalHelper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer +fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_optionalHelper_get_extern(jsObject) +} +#if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_set") -fileprivate func bjs_DataProcessor_optionalHelper_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void +fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void +#else +fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { + return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) +} extension Direction: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { @@ -1292,16 +2287,16 @@ extension Status: _BridgedSwiftCaseEnum { } } -extension Theme: _BridgedSwiftEnumNoPayload { +extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension HttpStatus: _BridgedSwiftEnumNoPayload { +extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Precision: _BridgedSwiftEnumNoPayload { +extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Ratio: _BridgedSwiftEnumNoPayload { +extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension TSDirection: _BridgedSwiftCaseEnum { @@ -1347,14 +2342,36 @@ extension TSDirection: _BridgedSwiftCaseEnum { } } -extension TSTheme: _BridgedSwiftEnumNoPayload { +extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Networking.API.Method: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Networking.API.Method { +@_expose(wasm, "bjs_Utils_StringUtils_static_uppercase") +@_cdecl("bjs_Utils_StringUtils_static_uppercase") +public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { + #if arch(wasm32) + let ret = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Utils_StringUtils_static_lowercase") +@_cdecl("bjs_Utils_StringUtils_static_lowercase") +public func _bjs_Utils_StringUtils_static_lowercase(_ textBytes: Int32, _ textLength: Int32) -> Void { + #if arch(wasm32) + let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Networking.API.Method: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Networking.API.Method { return bridgeJSLiftParameter(value) } @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Networking.API.Method { @@ -1393,10 +2410,10 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { } } -extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload { +extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Configuration.Port: _BridgedSwiftEnumNoPayload { +extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @@ -1435,18 +2452,18 @@ extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { } extension APIResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(Int.bridgeJSStackPop()) case 2: - return .flag(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .flag(Bool.bridgeJSStackPop()) case 3: - return .rate(Float.bridgeJSLiftParameter(_swift_js_pop_f32())) + return .rate(Float.bridgeJSStackPop()) case 4: - return .precise(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) + return .precise(Double.bridgeJSStackPop()) case 5: return .info default: @@ -1454,84 +2471,44 @@ extension APIResult: _BridgedSwiftAssociatedValueEnum { } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0): - _swift_js_push_i32(Int32(param0)) + param0.bridgeJSStackPush() return Int32(1) case .flag(let param0): - _swift_js_push_i32(param0 ? 1 : 0) + param0.bridgeJSStackPush() return Int32(2) case .rate(let param0): - _swift_js_push_f32(param0) + param0.bridgeJSStackPush() return Int32(3) case .precise(let param0): - _swift_js_push_f64(param0) + param0.bridgeJSStackPush() return Int32(4) case .info: return Int32(5) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0): - _swift_js_push_tag(Int32(1)) - _swift_js_push_i32(Int32(param0)) - case .flag(let param0): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - case .rate(let param0): - _swift_js_push_tag(Int32(3)) - _swift_js_push_f32(param0) - case .precise(let param0): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - case .info: - _swift_js_push_tag(Int32(5)) - } - } } extension ComplexResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> ComplexResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ComplexResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .error(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .error(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) case 2: - return .location(Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .location(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop()) case 3: - return .status(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) case 4: - return .coordinates(Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64())) + return .coordinates(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop()) case 5: - return .comprehensive(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), Double.bridgeJSLiftParameter(_swift_js_pop_f64()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .comprehensive(Bool.bridgeJSStackPop(), Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), Int.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop()) case 6: return .info default: @@ -1539,398 +2516,194 @@ extension ComplexResult: _BridgedSwiftAssociatedValueEnum { } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .error(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) case .location(let param0, let param1, let param2): - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(2) case .status(let param0, let param1, let param2): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(3) case .coordinates(let param0, let param1, let param2): - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(4) case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + param3.bridgeJSStackPush() + param4.bridgeJSStackPush() + param5.bridgeJSStackPush() + param6.bridgeJSStackPush() + param7.bridgeJSStackPush() + param8.bridgeJSStackPush() return Int32(5) case .info: return Int32(6) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> ComplexResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .error(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - case .location(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(3)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .coordinates(let param0, let param1, let param2): - _swift_js_push_tag(Int32(4)) - _swift_js_push_f64(param0) - _swift_js_push_f64(param1) - _swift_js_push_f64(param2) - case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - _swift_js_push_tag(Int32(5)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(param1 ? 1 : 0) - _swift_js_push_i32(Int32(param2)) - _swift_js_push_i32(Int32(param3)) - _swift_js_push_f64(param4) - _swift_js_push_f64(param5) - var __bjs_param6 = param6 - __bjs_param6.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param7 = param7 - __bjs_param7.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_param8 = param8 - __bjs_param8.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .info: - _swift_js_push_tag(Int32(6)) - } - } } extension Utilities.Result: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> Utilities.Result { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Utilities.Result { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) case 2: - return .status(Bool.bridgeJSLiftParameter(_swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32()), String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) default: fatalError("Unknown Utilities.Result case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) case .status(let param0, let param1, let param2): - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() return Int32(2) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> Utilities.Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> Utilities.Result { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) - _swift_js_push_i32(param0 ? 1 : 0) - _swift_js_push_i32(Int32(param1)) - var __bjs_param2 = param2 - __bjs_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - } } extension API.NetworkingResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> API.NetworkingResult { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> API.NetworkingResult { switch caseId { case 0: - return .success(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .success(String.bridgeJSStackPop()) case 1: - return .failure(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) default: fatalError("Unknown API.NetworkingResult case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .success(let param0): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + param0.bridgeJSStackPush() return Int32(0) case .failure(let param0, let param1): - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() return Int32(1) } } - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> API.NetworkingResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> API.NetworkingResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) - var __bjs_param0 = param0 - __bjs_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(param1)) - } - } } -extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { - private static func _bridgeJSLiftFromCaseId(_ caseId: Int32) -> APIOptionalResult { +extension AllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AllTypesResult { switch caseId { case 0: - return .success(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) + return .structPayload(Address.bridgeJSStackPop()) case 1: - return .failure(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + return .classPayload(Greeter.bridgeJSStackPop()) case 2: - return .status(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()), Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) + return .jsObjectPayload(JSObject.bridgeJSStackPop()) + case 3: + return .nestedEnum(APIResult.bridgeJSStackPop()) + case 4: + return .arrayPayload([Int].bridgeJSStackPop()) + case 5: + return .jsClassPayload(Foo(unsafelyWrapping: JSObject.bridgeJSStackPop())) + case 6: + return .empty default: - fatalError("Unknown APIOptionalResult case ID: \(caseId)") + fatalError("Unknown AllTypesResult case ID: \(caseId)") } } - // MARK: Protocol Export - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { - case .success(let param0): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - var __bjs_str_param0 = __bjs_unwrapped_param0 - __bjs_str_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + case .structPayload(let param0): + param0.bridgeJSStackPush() return Int32(0) - case .failure(let param0, let param1): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param0)) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(__bjs_unwrapped_param1 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + case .classPayload(let param0): + param0.bridgeJSStackPush() return Int32(1) - case .status(let param0, let param1, let param2): - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(__bjs_unwrapped_param0 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param1)) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - var __bjs_str_param2 = __bjs_unwrapped_param2 - __bjs_str_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + case .jsObjectPayload(let param0): + param0.bridgeJSStackPush() return Int32(2) + case .nestedEnum(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .arrayPayload(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .jsClassPayload(let param0): + param0.jsObject.bridgeJSStackPush() + return Int32(5) + case .empty: + return Int32(6) } } +} - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ caseId: Int32) -> APIOptionalResult { - return _bridgeJSLiftFromCaseId(caseId) - } - - // MARK: ExportSwift - - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ caseId: Int32) -> APIOptionalResult { - return _bridgeJSLiftFromCaseId(caseId) +extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> TypedPayloadResult { + switch caseId { + case 0: + return .precision(Precision.bridgeJSStackPop()) + case 1: + return .direction(Direction.bridgeJSStackPop()) + case 2: + return .optPrecision(Optional.bridgeJSStackPop()) + case 3: + return .optDirection(Optional.bridgeJSStackPop()) + case 4: + return .empty + default: + fatalError("Unknown TypedPayloadResult case ID: \(caseId)") + } } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { - case .success(let param0): - _swift_js_push_tag(Int32(0)) - let __bjs_isSome_param0 = param0 != nil - if let __bjs_unwrapped_param0 = param0 { - var __bjs_str_param0 = __bjs_unwrapped_param0 - __bjs_str_param0.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - case .failure(let param0, let param1): - _swift_js_push_tag(Int32(1)) + case .precision(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .direction(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .optPrecision(let param0): let __bjs_isSome_param0 = param0 != nil if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param0)) + __bjs_unwrapped_param0.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(__bjs_unwrapped_param1 ? 1 : 0) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - case .status(let param0, let param1, let param2): - _swift_js_push_tag(Int32(2)) + return Int32(2) + case .optDirection(let param0): let __bjs_isSome_param0 = param0 != nil if let __bjs_unwrapped_param0 = param0 { - _swift_js_push_i32(__bjs_unwrapped_param0 ? 1 : 0) + __bjs_unwrapped_param0.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) - let __bjs_isSome_param1 = param1 != nil - if let __bjs_unwrapped_param1 = param1 { - _swift_js_push_i32(Int32(__bjs_unwrapped_param1)) - } - _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) - let __bjs_isSome_param2 = param2 != nil - if let __bjs_unwrapped_param2 = param2 { - var __bjs_str_param2 = __bjs_unwrapped_param2 - __bjs_str_param2.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - } - _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + return Int32(3) + case .empty: + return Int32(4) } } } @@ -1992,6 +2765,28 @@ public func _bjs_StaticUtils_Nested_static_roundtrip(_ valueBytes: Int32, _ valu #endif } +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_createGraph") +@_cdecl("bjs_Services_Graph_GraphOperations_static_createGraph") +public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.createGraph(rootId: Int.bridgeJSLiftParameter(rootId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_nodeCount") +@_cdecl("bjs_Services_Graph_GraphOperations_static_nodeCount") +public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.nodeCount(graphId: Int.bridgeJSLiftParameter(graphId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension StaticPropertyEnum: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -2218,101 +3013,227 @@ public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_se #endif } -extension Point: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Point { - let y = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let x = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - return Point(x: x, y: y) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.x)) - _swift_js_push_i32(Int32(self.y)) - } - - init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) +extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> OptionalAllTypesResult { + switch caseId { + case 0: + return .optStruct(Optional
.bridgeJSStackPop()) + case 1: + return .optClass(Optional.bridgeJSStackPop()) + case 2: + return .optJSObject(Optional.bridgeJSStackPop()) + case 3: + return .optNestedEnum(Optional.bridgeJSStackPop()) + case 4: + return .optArray(Optional<[Int]>.bridgeJSStackPop()) + case 5: + return .optJsClass(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) + case 6: + return .empty + default: + fatalError("Unknown OptionalAllTypesResult case ID: \(caseId)") } - self = Self.bridgeJSLiftParameter() } - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .optStruct(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .optClass(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(1) + case .optJSObject(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(2) + case .optNestedEnum(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(3) + case .optArray(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .optJsClass(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.jsObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(5) + case .empty: + return Int32(6) + } } } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 -#else -fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif +extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIOptionalResult { + switch caseId { + case 0: + return .success(Optional.bridgeJSStackPop()) + case 1: + return .failure(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + case 2: + return .status(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + default: + fatalError("Unknown APIOptionalResult case ID: \(caseId)") + } + } -#if arch(wasm32) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + return Int32(0) + case .failure(let param0, let param1): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + let __bjs_isSome_param1 = param1 != nil + if let __bjs_unwrapped_param1 = param1 { + __bjs_unwrapped_param1.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + return Int32(1) + case .status(let param0, let param1, let param2): + let __bjs_isSome_param0 = param0 != nil + if let __bjs_unwrapped_param0 = param0 { + __bjs_unwrapped_param0.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param0 ? 1 : 0) + let __bjs_isSome_param1 = param1 != nil + if let __bjs_unwrapped_param1 = param1 { + __bjs_unwrapped_param1.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param1 ? 1 : 0) + let __bjs_isSome_param2 = param2 != nil + if let __bjs_unwrapped_param2 = param2 { + __bjs_unwrapped_param2.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_param2 ? 1 : 0) + return Int32(2) + } + } +} + +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} + +#if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") -fileprivate func _bjs_struct_lift_Point() -> Int32 +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Point() -> Int32 { +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} extension PointerFields: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> PointerFields { - let mutPtr = UnsafeMutablePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let ptr = UnsafePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let opaque = OpaquePointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let mutRaw = UnsafeMutableRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) - let raw = UnsafeRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PointerFields { + let mutPtr = UnsafeMutablePointer.bridgeJSStackPop() + let ptr = UnsafePointer.bridgeJSStackPop() + let opaque = OpaquePointer.bridgeJSStackPop() + let mutRaw = UnsafeMutableRawPointer.bridgeJSStackPop() + let raw = UnsafeRawPointer.bridgeJSStackPop() return PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_pointer(self.raw.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.mutRaw.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.opaque.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.ptr.bridgeJSLowerReturn()) - _swift_js_push_pointer(self.mutPtr.bridgeJSLowerReturn()) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.raw.bridgeJSStackPush() + self.mutRaw.bridgeJSStackPush() + self.opaque.bridgeJSStackPush() + self.ptr.bridgeJSStackPush() + self.mutPtr.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PointerFields())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PointerFields") -fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PointerFields_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PointerFields") -fileprivate func _bjs_struct_lift_PointerFields() -> Int32 +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { + return _bjs_struct_lift_PointerFields_extern() +} @_expose(wasm, "bjs_PointerFields_init") @_cdecl("bjs_PointerFields_init") @@ -2326,66 +3247,66 @@ public func _bjs_PointerFields_init(_ raw: UnsafeMutableRawPointer, _ mutRaw: Un } extension DataPoint: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> DataPoint { - let optFlag = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let optCount = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let label = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let y = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) - let x = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> DataPoint { + let optFlag = Optional.bridgeJSStackPop() + let optCount = Optional.bridgeJSStackPop() + let label = String.bridgeJSStackPop() + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() return DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.x) - _swift_js_push_f64(self.y) - var __bjs_label = self.label - __bjs_label.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + self.label.bridgeJSStackPush() let __bjs_isSome_optCount = self.optCount != nil if let __bjs_unwrapped_optCount = self.optCount { - _swift_js_push_i32(Int32(__bjs_unwrapped_optCount)) + __bjs_unwrapped_optCount.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optCount ? 1 : 0) let __bjs_isSome_optFlag = self.optFlag != nil if let __bjs_unwrapped_optFlag = self.optFlag { - _swift_js_push_i32(__bjs_unwrapped_optFlag ? 1 : 0) + __bjs_unwrapped_optFlag.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optFlag ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_DataPoint())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_DataPoint") -fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_DataPoint_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_DataPoint") -fileprivate func _bjs_struct_lift_DataPoint() -> Int32 +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { + return _bjs_struct_lift_DataPoint_extern() +} @_expose(wasm, "bjs_DataPoint_init") @_cdecl("bjs_DataPoint_init") @@ -2398,479 +3319,526 @@ public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, #endif } +extension PublicPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return PublicPoint(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PublicPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + public func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PublicPoint())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PublicPoint") +fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PublicPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PublicPoint_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PublicPoint") +fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PublicPoint() -> Int32 { + return _bjs_struct_lift_PublicPoint_extern() +} + +@_expose(wasm, "bjs_PublicPoint_init") +@_cdecl("bjs_PublicPoint_init") +public func _bjs_PublicPoint_init(_ x: Int32, _ y: Int32) -> Void { + #if arch(wasm32) + let ret = PublicPoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension Address: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Address { - let zipCode = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let city = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let street = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { + let zipCode = Optional.bridgeJSStackPop() + let city = String.bridgeJSStackPop() + let street = String.bridgeJSStackPop() return Address(street: street, city: city, zipCode: zipCode) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_street = self.street - __bjs_street.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - var __bjs_city = self.city - __bjs_city.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.street.bridgeJSStackPush() + self.city.bridgeJSStackPush() let __bjs_isSome_zipCode = self.zipCode != nil if let __bjs_unwrapped_zipCode = self.zipCode { - _swift_js_push_i32(Int32(__bjs_unwrapped_zipCode)) + __bjs_unwrapped_zipCode.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_zipCode ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Address())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Address") -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Address_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Address") -fileprivate func _bjs_struct_lift_Address() -> Int32 +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Address() -> Int32 { +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Address() -> Int32 { + return _bjs_struct_lift_Address_extern() +} extension Contact: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Contact { - let secondaryAddress = Optional
.bridgeJSLiftParameter(_swift_js_pop_i32()) - let email = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32()) - let address = Address.bridgeJSLiftParameter() - let age = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Contact { + let secondaryAddress = Optional
.bridgeJSStackPop() + let email = Optional.bridgeJSStackPop() + let address = Address.bridgeJSStackPop() + let age = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return Contact(name: name, age: age, address: address, email: email, secondaryAddress: secondaryAddress) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.age)) - self.address.bridgeJSLowerReturn() + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.age.bridgeJSStackPush() + self.address.bridgeJSStackPush() let __bjs_isSome_email = self.email != nil if let __bjs_unwrapped_email = self.email { - var __bjs_str_email = __bjs_unwrapped_email - __bjs_str_email.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + __bjs_unwrapped_email.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_email ? 1 : 0) - let __bjs_isSome_secondaryAddress = self.secondaryAddress != nil - if let __bjs_unwrapped_secondaryAddress = self.secondaryAddress { - __bjs_unwrapped_secondaryAddress.bridgeJSLowerReturn() - } - _swift_js_push_i32(__bjs_isSome_secondaryAddress ? 1 : 0) + self.secondaryAddress.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Contact(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Contact(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Contact())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Contact") -fileprivate func _bjs_struct_lower_Contact(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Contact(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Contact(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Contact_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Contact") -fileprivate func _bjs_struct_lift_Contact() -> Int32 +fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Contact() -> Int32 { +fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Contact() -> Int32 { + return _bjs_struct_lift_Contact_extern() +} extension Config: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> Config { - let status = Status.bridgeJSLiftParameter(_swift_js_pop_i32()) - let direction = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let theme = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Config { + let status = Status.bridgeJSStackPop() + let direction = Optional.bridgeJSStackPop() + let theme = Optional.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return Config(name: name, theme: theme, direction: direction, status: status) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() let __bjs_isSome_theme = self.theme != nil if let __bjs_unwrapped_theme = self.theme { - var __bjs_str_theme = __bjs_unwrapped_theme.rawValue - __bjs_str_theme.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + __bjs_unwrapped_theme.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_theme ? 1 : 0) let __bjs_isSome_direction = self.direction != nil if let __bjs_unwrapped_direction = self.direction { - _swift_js_push_i32(__bjs_unwrapped_direction.bridgeJSLowerParameter()) + __bjs_unwrapped_direction.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_direction ? 1 : 0) - _swift_js_push_i32(Int32(self.status.bridgeJSLowerParameter())) + self.status.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Config())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Config") -fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Config_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Config") -fileprivate func _bjs_struct_lift_Config() -> Int32 +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Config() -> Int32 { +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_Config() -> Int32 { + return _bjs_struct_lift_Config_extern() +} extension SessionData: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> SessionData { - let owner = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_pointer()) - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SessionData { + let owner = Optional.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return SessionData(id: id, owner: owner) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() let __bjs_isSome_owner = self.owner != nil if let __bjs_unwrapped_owner = self.owner { - _swift_js_push_pointer(__bjs_unwrapped_owner.bridgeJSLowerReturn()) + __bjs_unwrapped_owner.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_owner ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_SessionData(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_SessionData(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SessionData())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SessionData") -fileprivate func _bjs_struct_lower_SessionData(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_SessionData(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_SessionData(_ objectId: Int32) -> Void { + return _bjs_struct_lower_SessionData_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SessionData") -fileprivate func _bjs_struct_lift_SessionData() -> Int32 +fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_SessionData() -> Int32 { +fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_SessionData() -> Int32 { + return _bjs_struct_lift_SessionData_extern() +} extension ValidationReport: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> ValidationReport { - let outcome = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let status = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let result = APIResult.bridgeJSLiftParameter(_swift_js_pop_i32()) - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ValidationReport { + let outcome = Optional.bridgeJSStackPop() + let status = Optional.bridgeJSStackPop() + let result = APIResult.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return ValidationReport(id: id, result: result, status: status, outcome: outcome) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) - self.result.bridgeJSLowerReturn() + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.result.bridgeJSStackPush() let __bjs_isSome_status = self.status != nil if let __bjs_unwrapped_status = self.status { - _swift_js_push_i32(__bjs_unwrapped_status.bridgeJSLowerParameter()) + __bjs_unwrapped_status.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_status ? 1 : 0) let __bjs_isSome_outcome = self.outcome != nil if let __bjs_unwrapped_outcome = self.outcome { - _swift_js_push_i32(__bjs_unwrapped_outcome.bridgeJSLowerParameter()) + __bjs_unwrapped_outcome.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_outcome ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_ValidationReport(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_ValidationReport(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ValidationReport())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ValidationReport") -fileprivate func _bjs_struct_lower_ValidationReport(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_ValidationReport(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_ValidationReport(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ValidationReport_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ValidationReport") -fileprivate func _bjs_struct_lift_ValidationReport() -> Int32 +fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_ValidationReport() -> Int32 { +fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_ValidationReport() -> Int32 { + return _bjs_struct_lift_ValidationReport_extern() +} extension AdvancedConfig: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> AdvancedConfig { - let overrideDefaults = Optional.bridgeJSLiftParameter(_swift_js_pop_i32()) - let defaults = ConfigStruct.bridgeJSLiftParameter() - let location = Optional.bridgeJSLiftParameter(_swift_js_pop_i32()) - let metadata = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let result = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let status = Status.bridgeJSLiftParameter(_swift_js_pop_i32()) - let theme = Theme.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let enabled = Bool.bridgeJSLiftParameter(_swift_js_pop_i32()) - let title = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> AdvancedConfig { + let overrideDefaults = Optional.bridgeJSStackPop() + let defaults = ConfigStruct.bridgeJSStackPop() + let location = Optional.bridgeJSStackPop() + let metadata = Optional.bridgeJSStackPop() + let result = Optional.bridgeJSStackPop() + let status = Status.bridgeJSStackPop() + let theme = Theme.bridgeJSStackPop() + let enabled = Bool.bridgeJSStackPop() + let title = String.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return AdvancedConfig(id: id, title: title, enabled: enabled, theme: theme, status: status, result: result, metadata: metadata, location: location, defaults: defaults, overrideDefaults: overrideDefaults) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) - var __bjs_title = self.title - __bjs_title.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(self.enabled ? 1 : 0) - var __bjs_theme = self.theme.rawValue - __bjs_theme.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.status.bridgeJSLowerParameter())) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.title.bridgeJSStackPush() + self.enabled.bridgeJSStackPush() + self.theme.bridgeJSStackPush() + self.status.bridgeJSStackPush() let __bjs_isSome_result = self.result != nil if let __bjs_unwrapped_result = self.result { - _swift_js_push_i32(__bjs_unwrapped_result.bridgeJSLowerParameter()) + __bjs_unwrapped_result.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_result ? 1 : 0) let __bjs_isSome_metadata = self.metadata != nil if let __bjs_unwrapped_metadata = self.metadata { - _swift_js_push_i32(__bjs_unwrapped_metadata.bridgeJSLowerReturn()) + __bjs_unwrapped_metadata.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_metadata ? 1 : 0) - let __bjs_isSome_location = self.location != nil - if let __bjs_unwrapped_location = self.location { - __bjs_unwrapped_location.bridgeJSLowerReturn() - } - _swift_js_push_i32(__bjs_isSome_location ? 1 : 0) - self.defaults.bridgeJSLowerReturn() - let __bjs_isSome_overrideDefaults = self.overrideDefaults != nil - if let __bjs_unwrapped_overrideDefaults = self.overrideDefaults { - __bjs_unwrapped_overrideDefaults.bridgeJSLowerReturn() - } - _swift_js_push_i32(__bjs_isSome_overrideDefaults ? 1 : 0) + self.location.bridgeJSStackPush() + self.defaults.bridgeJSStackPush() + self.overrideDefaults.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_AdvancedConfig(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_AdvancedConfig(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_AdvancedConfig())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_AdvancedConfig") -fileprivate func _bjs_struct_lower_AdvancedConfig(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_AdvancedConfig(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_AdvancedConfig(_ objectId: Int32) -> Void { + return _bjs_struct_lower_AdvancedConfig_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_AdvancedConfig") -fileprivate func _bjs_struct_lift_AdvancedConfig() -> Int32 +fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_AdvancedConfig() -> Int32 { +fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_AdvancedConfig() -> Int32 { + return _bjs_struct_lift_AdvancedConfig_extern() +} extension MeasurementConfig: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> MeasurementConfig { - let optionalRatio = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f64()) - let optionalPrecision = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_f32()) - let ratio = Ratio.bridgeJSLiftParameter(_swift_js_pop_f64()) - let precision = Precision.bridgeJSLiftParameter(_swift_js_pop_f32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MeasurementConfig { + let optionalRatio = Optional.bridgeJSStackPop() + let optionalPrecision = Optional.bridgeJSStackPop() + let ratio = Ratio.bridgeJSStackPop() + let precision = Precision.bridgeJSStackPop() return MeasurementConfig(precision: precision, ratio: ratio, optionalPrecision: optionalPrecision, optionalRatio: optionalRatio) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f32(self.precision.bridgeJSLowerParameter()) - _swift_js_push_f64(self.ratio.bridgeJSLowerParameter()) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.precision.bridgeJSStackPush() + self.ratio.bridgeJSStackPush() let __bjs_isSome_optionalPrecision = self.optionalPrecision != nil if let __bjs_unwrapped_optionalPrecision = self.optionalPrecision { - _swift_js_push_f32(__bjs_unwrapped_optionalPrecision.bridgeJSLowerParameter()) + __bjs_unwrapped_optionalPrecision.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optionalPrecision ? 1 : 0) let __bjs_isSome_optionalRatio = self.optionalRatio != nil if let __bjs_unwrapped_optionalRatio = self.optionalRatio { - _swift_js_push_f64(__bjs_unwrapped_optionalRatio.bridgeJSLowerParameter()) + __bjs_unwrapped_optionalRatio.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_optionalRatio ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_MeasurementConfig(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_MeasurementConfig(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MeasurementConfig())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MeasurementConfig") -fileprivate func _bjs_struct_lower_MeasurementConfig(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_MeasurementConfig(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_MeasurementConfig(_ objectId: Int32) -> Void { + return _bjs_struct_lower_MeasurementConfig_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MeasurementConfig") -fileprivate func _bjs_struct_lift_MeasurementConfig() -> Int32 +fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_MeasurementConfig() -> Int32 { +fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_MeasurementConfig() -> Int32 { + return _bjs_struct_lift_MeasurementConfig_extern() +} extension MathOperations: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> MathOperations { - let baseValue = Double.bridgeJSLiftParameter(_swift_js_pop_f64()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MathOperations { + let baseValue = Double.bridgeJSStackPop() return MathOperations(baseValue: baseValue) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_f64(self.baseValue) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.baseValue.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MathOperations())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MathOperations") -fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Void { + return _bjs_struct_lower_MathOperations_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MathOperations") -fileprivate func _bjs_struct_lift_MathOperations() -> Int32 +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { + return _bjs_struct_lift_MathOperations_extern() +} @_expose(wasm, "bjs_MathOperations_init") @_cdecl("bjs_MathOperations_init") @@ -2917,56 +3885,56 @@ public func _bjs_MathOperations_static_subtract(_ a: Float64, _ b: Float64) -> F } extension CopyableCart: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> CopyableCart { - let note = Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32()) - let x = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCart { + let note = Optional.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() return CopyableCart(x: x, note: note) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.x)) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() let __bjs_isSome_note = self.note != nil if let __bjs_unwrapped_note = self.note { - var __bjs_str_note = __bjs_unwrapped_note - __bjs_str_note.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } + __bjs_unwrapped_note.bridgeJSStackPush() } _swift_js_push_i32(__bjs_isSome_note ? 1 : 0) } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_CopyableCart(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_CopyableCart(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCart())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCart") -fileprivate func _bjs_struct_lower_CopyableCart(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_CopyableCart(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_CopyableCart(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableCart_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCart") -fileprivate func _bjs_struct_lift_CopyableCart() -> Int32 +fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_CopyableCart() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_CopyableCart() -> Int32 { + return _bjs_struct_lift_CopyableCart_extern() +} @_expose(wasm, "bjs_CopyableCart_static_fromJSObject") @_cdecl("bjs_CopyableCart_static_fromJSObject") @@ -2980,103 +3948,102 @@ public func _bjs_CopyableCart_static_fromJSObject(_ object: Int32) -> Void { } extension CopyableCartItem: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> CopyableCartItem { - let quantity = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let sku = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCartItem { + let quantity = Int.bridgeJSStackPop() + let sku = String.bridgeJSStackPop() return CopyableCartItem(sku: sku, quantity: quantity) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_sku = self.sku - __bjs_sku.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.quantity)) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.sku.bridgeJSStackPush() + self.quantity.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_CopyableCartItem(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_CopyableCartItem(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCartItem())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCartItem") -fileprivate func _bjs_struct_lower_CopyableCartItem(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_CopyableCartItem(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_CopyableCartItem(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableCartItem_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCartItem") -fileprivate func _bjs_struct_lift_CopyableCartItem() -> Int32 +fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_CopyableCartItem() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_CopyableCartItem() -> Int32 { + return _bjs_struct_lift_CopyableCartItem_extern() +} extension CopyableNestedCart: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> CopyableNestedCart { - let shippingAddress = Optional
.bridgeJSLiftParameter(_swift_js_pop_i32()) - let item = CopyableCartItem.bridgeJSLiftParameter() - let id = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableNestedCart { + let shippingAddress = Optional
.bridgeJSStackPop() + let item = CopyableCartItem.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() return CopyableNestedCart(id: id, item: item, shippingAddress: shippingAddress) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - _swift_js_push_i32(Int32(self.id)) - self.item.bridgeJSLowerReturn() - let __bjs_isSome_shippingAddress = self.shippingAddress != nil - if let __bjs_unwrapped_shippingAddress = self.shippingAddress { - __bjs_unwrapped_shippingAddress.bridgeJSLowerReturn() - } - _swift_js_push_i32(__bjs_isSome_shippingAddress ? 1 : 0) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.id.bridgeJSStackPush() + self.item.bridgeJSStackPush() + self.shippingAddress.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_CopyableNestedCart(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_CopyableNestedCart(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableNestedCart())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableNestedCart") -fileprivate func _bjs_struct_lower_CopyableNestedCart(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_CopyableNestedCart(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_CopyableNestedCart(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableNestedCart_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableNestedCart") -fileprivate func _bjs_struct_lift_CopyableNestedCart() -> Int32 +fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_CopyableNestedCart() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_CopyableNestedCart() -> Int32 { + return _bjs_struct_lift_CopyableNestedCart_extern() +} @_expose(wasm, "bjs_CopyableNestedCart_static_fromJSObject") @_cdecl("bjs_CopyableNestedCart_static_fromJSObject") @@ -3090,52 +4057,52 @@ public func _bjs_CopyableNestedCart_static_fromJSObject(_ object: Int32) -> Void } extension ConfigStruct: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter() -> ConfigStruct { - let value = Int.bridgeJSLiftParameter(_swift_js_pop_i32()) - let name = String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32()) + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ConfigStruct { + let value = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() return ConfigStruct(name: name, value: value) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() { - var __bjs_name = self.name - __bjs_name.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - } - _swift_js_push_i32(Int32(self.value)) + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.value.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - let __bjs_cleanupId = _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) - defer { - _swift_js_struct_cleanup(__bjs_cleanupId) - } - self = Self.bridgeJSLiftParameter() + _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self - __bjs_self.bridgeJSLowerReturn() + __bjs_self.bridgeJSStackPush() return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ConfigStruct())) } } #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ConfigStruct") -fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Int32 +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Int32 { +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ConfigStruct_extern(objectId) +} #if arch(wasm32) @_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ConfigStruct") -fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { + return _bjs_struct_lift_ConfigStruct_extern() +} @_expose(wasm, "bjs_ConfigStruct_static_defaultConfig_get") @_cdecl("bjs_ConfigStruct_static_defaultConfig_get") @@ -3201,6 +4168,180 @@ public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { #endif } +extension JSObjectContainer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSObjectContainer { + let optionalObject = Optional.bridgeJSStackPop() + let object = JSObject.bridgeJSStackPop() + return JSObjectContainer(object: object, optionalObject: optionalObject) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.object.bridgeJSStackPush() + let __bjs_isSome_optionalObject = self.optionalObject != nil + if let __bjs_unwrapped_optionalObject = self.optionalObject { + __bjs_unwrapped_optionalObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_optionalObject ? 1 : 0) + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_JSObjectContainer(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSObjectContainer())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSObjectContainer") +fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_JSObjectContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSObjectContainer_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSObjectContainer") +fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_JSObjectContainer() -> Int32 { + return _bjs_struct_lift_JSObjectContainer_extern() +} + +extension FooContainer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> FooContainer { + let optionalFoo = Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) } + let foo = Foo(unsafelyWrapping: JSObject.bridgeJSStackPop()) + return FooContainer(foo: foo, optionalFoo: optionalFoo) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.foo.jsObject.bridgeJSStackPush() + let __bjs_isSome_optionalFoo = self.optionalFoo != nil + if let __bjs_unwrapped_optionalFoo = self.optionalFoo { + __bjs_unwrapped_optionalFoo.jsObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_optionalFoo ? 1 : 0) + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_FooContainer(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_FooContainer())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_FooContainer") +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_FooContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_FooContainer_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_FooContainer") +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_FooContainer() -> Int32 { + return _bjs_struct_lift_FooContainer_extern() +} + +extension ArrayMembers: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ArrayMembers { + let optStrings = Optional<[String]>.bridgeJSStackPop() + let ints = [Int].bridgeJSStackPop() + return ArrayMembers(ints: ints, optStrings: optStrings) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.ints.bridgeJSStackPush() + self.optStrings.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ArrayMembers(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ArrayMembers())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ArrayMembers") +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ArrayMembers(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ArrayMembers_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ArrayMembers") +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ArrayMembers() -> Int32 { + return _bjs_struct_lift_ArrayMembers_extern() +} + +@_expose(wasm, "bjs_ArrayMembers_sumValues") +@_cdecl("bjs_ArrayMembers_sumValues") +public func _bjs_ArrayMembers_sumValues() -> Int32 { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayMembers_firstString") +@_cdecl("bjs_ArrayMembers_firstString") +public func _bjs_ArrayMembers_firstString() -> Void { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripVoid") @_cdecl("bjs_roundTripVoid") public func _bjs_roundTripVoid() -> Void { @@ -3354,20 +4495,86 @@ public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { #endif } -@_expose(wasm, "bjs_makeImportedFoo") -@_cdecl("bjs_makeImportedFoo") -public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { +@_expose(wasm, "bjs_roundTripDictionaryExport") +@_cdecl("bjs_roundTripDictionaryExport") +public func _bjs_roundTripDictionaryExport() -> Void { #if arch(wasm32) - do { - let ret = try makeImportedFoo(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) + let ret = roundTripDictionaryExport(v: [String: Int].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalDictionaryExport") +@_cdecl("bjs_roundTripOptionalDictionaryExport") +public func _bjs_roundTripOptionalDictionaryExport() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalDictionaryExport(v: Optional<[String: String]>.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripJSValue") +@_cdecl("bjs_roundTripJSValue") +public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalJSValue") +@_cdecl("bjs_roundTripOptionalJSValue") +public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripJSValueArray") +@_cdecl("bjs_roundTripJSValueArray") +public func _bjs_roundTripJSValueArray() -> Void { + #if arch(wasm32) + let ret = roundTripJSValueArray(v: [JSValue].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalJSValueArray") +@_cdecl("bjs_roundTripOptionalJSValueArray") +public func _bjs_roundTripOptionalJSValueArray() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeImportedFoo") +@_cdecl("bjs_makeImportedFoo") +public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { + #if arch(wasm32) + do { + let ret = try makeImportedFoo(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -3584,7 +4791,7 @@ public func _bjs_asyncRoundTripVoid() -> Int32 { #if arch(wasm32) let ret = JSPromise.async { await asyncRoundTripVoid() - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3597,7 +4804,7 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3610,7 +4817,7 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3623,7 +4830,7 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3636,7 +4843,7 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3649,7 +4856,7 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3662,7 +4869,7 @@ public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -3675,7 +4882,7 @@ public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) let ret = JSPromise.async { return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)).jsValue - } .jsObject + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -4176,1278 +5383,1066 @@ public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { #endif } -@_expose(wasm, "bjs_roundTripOptionalString") -@_cdecl("bjs_roundTripOptionalString") -public func _bjs_roundTripOptionalString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripAllTypesResult") +@_cdecl("bjs_roundTripAllTypesResult") +public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalInt") -@_cdecl("bjs_roundTripOptionalInt") -public func _bjs_roundTripOptionalInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_roundTripTypedPayloadResult") +@_cdecl("bjs_roundTripTypedPayloadResult") +public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalBool") -@_cdecl("bjs_roundTripOptionalBool") -public func _bjs_roundTripOptionalBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { +@_expose(wasm, "bjs_createPropertyHolder") +@_cdecl("bjs_createPropertyHolder") +public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripOptionalBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) + let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalFloat") -@_cdecl("bjs_roundTripOptionalFloat") -public func _bjs_roundTripOptionalFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { +@_expose(wasm, "bjs_testPropertyHolder") +@_cdecl("bjs_testPropertyHolder") +public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripOptionalFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) + let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDouble") -@_cdecl("bjs_roundTripOptionalDouble") -public func _bjs_roundTripOptionalDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { +@_expose(wasm, "bjs_resetObserverCounts") +@_cdecl("bjs_resetObserverCounts") +public func _bjs_resetObserverCounts() -> Void { #if arch(wasm32) - let ret = roundTripOptionalDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) - return ret.bridgeJSLowerReturn() + resetObserverCounts() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalSyntax") -@_cdecl("bjs_roundTripOptionalSyntax") -public func _bjs_roundTripOptionalSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_getObserverStats") +@_cdecl("bjs_getObserverStats") +public func _bjs_getObserverStats() -> Void { #if arch(wasm32) - let ret = roundTripOptionalSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let ret = getObserverStats() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalMixSyntax") -@_cdecl("bjs_roundTripOptionalMixSyntax") -public func _bjs_roundTripOptionalMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_testStringDefault") +@_cdecl("bjs_testStringDefault") +public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalSwiftSyntax") -@_cdecl("bjs_roundTripOptionalSwiftSyntax") -public func _bjs_roundTripOptionalSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_testIntDefault") +@_cdecl("bjs_testIntDefault") +public func _bjs_testIntDefault(_ count: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + let ret = testIntDefault(count: Int.bridgeJSLiftParameter(count)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalWithSpaces") -@_cdecl("bjs_roundTripOptionalWithSpaces") -public func _bjs_roundTripOptionalWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { +@_expose(wasm, "bjs_testBoolDefault") +@_cdecl("bjs_testBoolDefault") +public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalTypeAlias") -@_cdecl("bjs_roundTripOptionalTypeAlias") -public func _bjs_roundTripOptionalTypeAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { +@_expose(wasm, "bjs_testOptionalDefault") +@_cdecl("bjs_testOptionalDefault") +public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTypeAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) + let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStatus") -@_cdecl("bjs_roundTripOptionalStatus") -public func _bjs_roundTripOptionalStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_testMultipleDefaults") +@_cdecl("bjs_testMultipleDefaults") +public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalTheme") -@_cdecl("bjs_roundTripOptionalTheme") -public func _bjs_roundTripOptionalTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_testSimpleEnumDefault") +@_cdecl("bjs_testSimpleEnumDefault") +public func _bjs_testSimpleEnumDefault(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) + let ret = testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalHttpStatus") -@_cdecl("bjs_roundTripOptionalHttpStatus") -public func _bjs_roundTripOptionalHttpStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_testDirectionDefault") +@_cdecl("bjs_testDirectionDefault") +public func _bjs_testDirectionDefault(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalHttpStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalTSDirection") -@_cdecl("bjs_roundTripOptionalTSDirection") -public func _bjs_roundTripOptionalTSDirection(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_testRawStringEnumDefault") +@_cdecl("bjs_testRawStringEnumDefault") +public func _bjs_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTSDirection(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalTSTheme") -@_cdecl("bjs_roundTripOptionalTSTheme") -public func _bjs_roundTripOptionalTSTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_testComplexInit") +@_cdecl("bjs_testComplexInit") +public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripOptionalTSTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) + let ret = testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalNetworkingAPIMethod") -@_cdecl("bjs_roundTripOptionalNetworkingAPIMethod") -public func _bjs_roundTripOptionalNetworkingAPIMethod(_ methodIsSome: Int32, _ methodValue: Int32) -> Void { +@_expose(wasm, "bjs_testEmptyInit") +@_cdecl("bjs_testEmptyInit") +public func _bjs_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripOptionalNetworkingAPIMethod(_: Optional.bridgeJSLiftParameter(methodIsSome, methodValue)) + let ret = testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalAPIResult") -@_cdecl("bjs_roundTripOptionalAPIResult") -public func _bjs_roundTripOptionalAPIResult(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { +@_expose(wasm, "bjs_arrayWithDefault") +@_cdecl("bjs_arrayWithDefault") +public func _bjs_arrayWithDefault() -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalAPIResult(value: Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId)) + let ret = arrayWithDefault(_: [Int].bridgeJSStackPop()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_compareAPIResults") -@_cdecl("bjs_compareAPIResults") -public func _bjs_compareAPIResults(_ r1IsSome: Int32, _ r1CaseId: Int32, _ r2IsSome: Int32, _ r2CaseId: Int32) -> Void { +@_expose(wasm, "bjs_arrayWithOptionalDefault") +@_cdecl("bjs_arrayWithOptionalDefault") +public func _bjs_arrayWithOptionalDefault() -> Int32 { #if arch(wasm32) - let _tmp_r2 = Optional.bridgeJSLiftParameter(r2IsSome, r2CaseId) - let _tmp_r1 = Optional.bridgeJSLiftParameter(r1IsSome, r1CaseId) - let ret = compareAPIResults(_: _tmp_r1, _: _tmp_r2) + let ret = arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalComplexResult") -@_cdecl("bjs_roundTripOptionalComplexResult") -public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_arrayMixedDefaults") +@_cdecl("bjs_arrayMixedDefaults") +public func _bjs_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let ret = arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalClass") -@_cdecl("bjs_roundTripOptionalClass") -public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_formatName") +@_cdecl("bjs_formatName") +public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalAPIOptionalResult") -@_cdecl("bjs_roundTripOptionalAPIOptionalResult") -public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_makeFormatter") +@_cdecl("bjs_makeFormatter") +public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) - return ret.bridgeJSLowerReturn() + let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_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_makeAdder") +@_cdecl("bjs_makeAdder") +public func _bjs_makeAdder(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) - return ret.bridgeJSLowerReturn() + let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(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_roundTripIntArray") +@_cdecl("bjs_roundTripIntArray") +public func _bjs_roundTripIntArray() -> Void { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) - return ret.bridgeJSLowerReturn() + let ret = roundTripIntArray(_: [Int].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_resetObserverCounts") -@_cdecl("bjs_resetObserverCounts") -public func _bjs_resetObserverCounts() -> Void { +@_expose(wasm, "bjs_roundTripStringArray") +@_cdecl("bjs_roundTripStringArray") +public func _bjs_roundTripStringArray() -> Void { #if arch(wasm32) - resetObserverCounts() + let ret = roundTripStringArray(_: [String].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getObserverStats") -@_cdecl("bjs_getObserverStats") -public func _bjs_getObserverStats() -> Void { +@_expose(wasm, "bjs_roundTripDoubleArray") +@_cdecl("bjs_roundTripDoubleArray") +public func _bjs_roundTripDoubleArray() -> Void { #if arch(wasm32) - let ret = getObserverStats() - return ret.bridgeJSLowerReturn() + let ret = roundTripDoubleArray(_: [Double].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testStringDefault") -@_cdecl("bjs_testStringDefault") -public func _bjs_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripBoolArray") +@_cdecl("bjs_roundTripBoolArray") +public func _bjs_roundTripBoolArray() -> Void { #if arch(wasm32) - let ret = testStringDefault(message: String.bridgeJSLiftParameter(messageBytes, messageLength)) - return ret.bridgeJSLowerReturn() + let ret = roundTripBoolArray(_: [Bool].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testIntDefault") -@_cdecl("bjs_testIntDefault") -public func _bjs_testIntDefault(_ count: Int32) -> Int32 { - #if arch(wasm32) - let ret = testIntDefault(count: Int.bridgeJSLiftParameter(count)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testBoolDefault") -@_cdecl("bjs_testBoolDefault") -public func _bjs_testBoolDefault(_ flag: Int32) -> Int32 { +@_expose(wasm, "bjs_roundTripDirectionArray") +@_cdecl("bjs_roundTripDirectionArray") +public func _bjs_roundTripDirectionArray() -> Void { #if arch(wasm32) - let ret = testBoolDefault(flag: Bool.bridgeJSLiftParameter(flag)) - return ret.bridgeJSLowerReturn() + let ret = roundTripDirectionArray(_: [Direction].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testOptionalDefault") -@_cdecl("bjs_testOptionalDefault") -public func _bjs_testOptionalDefault(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripStatusArray") +@_cdecl("bjs_roundTripStatusArray") +public func _bjs_roundTripStatusArray() -> Void { #if arch(wasm32) - let ret = testOptionalDefault(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() + let ret = roundTripStatusArray(_: [Status].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testMultipleDefaults") -@_cdecl("bjs_testMultipleDefaults") -public func _bjs_testMultipleDefaults(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32, _ enabled: Int32) -> Void { +@_expose(wasm, "bjs_roundTripThemeArray") +@_cdecl("bjs_roundTripThemeArray") +public func _bjs_roundTripThemeArray() -> Void { #if arch(wasm32) - let ret = testMultipleDefaults(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled)) - return ret.bridgeJSLowerReturn() + let ret = roundTripThemeArray(_: [Theme].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testSimpleEnumDefault") -@_cdecl("bjs_testSimpleEnumDefault") -public func _bjs_testSimpleEnumDefault(_ status: Int32) -> Int32 { +@_expose(wasm, "bjs_roundTripHttpStatusArray") +@_cdecl("bjs_roundTripHttpStatusArray") +public func _bjs_roundTripHttpStatusArray() -> Void { #if arch(wasm32) - let ret = testSimpleEnumDefault(status: Status.bridgeJSLiftParameter(status)) - return ret.bridgeJSLowerReturn() + let ret = roundTripHttpStatusArray(_: [HttpStatus].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testDirectionDefault") -@_cdecl("bjs_testDirectionDefault") -public func _bjs_testDirectionDefault(_ direction: Int32) -> Int32 { +@_expose(wasm, "bjs_roundTripDataPointArray") +@_cdecl("bjs_roundTripDataPointArray") +public func _bjs_roundTripDataPointArray() -> Void { #if arch(wasm32) - let ret = testDirectionDefault(direction: Direction.bridgeJSLiftParameter(direction)) - return ret.bridgeJSLowerReturn() + let ret = roundTripDataPointArray(_: [DataPoint].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testRawStringEnumDefault") -@_cdecl("bjs_testRawStringEnumDefault") -public func _bjs_testRawStringEnumDefault(_ themeBytes: Int32, _ themeLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripGreeterArray") +@_cdecl("bjs_roundTripGreeterArray") +public func _bjs_roundTripGreeterArray() -> Void { #if arch(wasm32) - let ret = testRawStringEnumDefault(theme: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) - return ret.bridgeJSLowerReturn() + let ret = roundTripGreeterArray(_: [Greeter].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testComplexInit") -@_cdecl("bjs_testComplexInit") -public func _bjs_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_roundTripOptionalIntArray") +@_cdecl("bjs_roundTripOptionalIntArray") +public func _bjs_roundTripOptionalIntArray() -> Void { #if arch(wasm32) - let ret = testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) - return ret.bridgeJSLowerReturn() + let ret = roundTripOptionalIntArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testEmptyInit") -@_cdecl("bjs_testEmptyInit") -public func _bjs_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripOptionalStringArray") +@_cdecl("bjs_roundTripOptionalStringArray") +public func _bjs_roundTripOptionalStringArray() -> Void { #if arch(wasm32) - let ret = testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) - return ret.bridgeJSLowerReturn() + let ret = roundTripOptionalStringArray(_: { + let __count = Int(_swift_js_pop_i32()) + var __result: [Optional] = [] + __result.reserveCapacity(__count) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) + } + __result.reverse() + return __result + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayWithDefault") -@_cdecl("bjs_arrayWithDefault") -public func _bjs_arrayWithDefault() -> Int32 { +@_expose(wasm, "bjs_roundTripOptionalDataPointArray") +@_cdecl("bjs_roundTripOptionalDataPointArray") +public func _bjs_roundTripOptionalDataPointArray() -> Void { #if arch(wasm32) - let ret = arrayWithDefault(_: { + let ret = roundTripOptionalDataPointArray(_: { let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] + var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) - return ret.bridgeJSLowerReturn() + }()) + for __bjs_elem_ret in ret { + __bjs_elem_ret.bridgeJSStackPush() + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayWithOptionalDefault") -@_cdecl("bjs_arrayWithOptionalDefault") -public func _bjs_arrayWithOptionalDefault(_ values: Int32) -> Int32 { +@_expose(wasm, "bjs_roundTripOptionalDirectionArray") +@_cdecl("bjs_roundTripOptionalDirectionArray") +public func _bjs_roundTripOptionalDirectionArray() -> Void { #if arch(wasm32) - let ret = arrayWithOptionalDefault(_: { - if values == 0 { - return Optional<[Int]>.none - } else { - return { + let ret = roundTripOptionalDirectionArray(_: { let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] + var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }() - } - }()) - return ret.bridgeJSLowerReturn() + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMixedDefaults") -@_cdecl("bjs_arrayMixedDefaults") -public func _bjs_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalStatusArray") +@_cdecl("bjs_roundTripOptionalStatusArray") +public func _bjs_roundTripOptionalStatusArray() -> Void { #if arch(wasm32) - let ret = arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: { + let ret = roundTripOptionalStatusArray(_: { let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] + var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) - return ret.bridgeJSLowerReturn() + }()) + for __bjs_elem_ret in ret { + let __bjs_isSome_ret_elem = __bjs_elem_ret != nil + if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_formatName") -@_cdecl("bjs_formatName") -public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalIntArrayType") +@_cdecl("bjs_roundTripOptionalIntArrayType") +public func _bjs_roundTripOptionalIntArrayType() -> Void { #if arch(wasm32) - let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) - return ret.bridgeJSLowerReturn() + let ret = roundTripOptionalIntArrayType(_: Optional<[Int]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeFormatter") -@_cdecl("bjs_makeFormatter") -public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripOptionalStringArrayType") +@_cdecl("bjs_roundTripOptionalStringArrayType") +public func _bjs_roundTripOptionalStringArrayType() -> Void { #if arch(wasm32) - let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) - return _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLower(ret) + let ret = roundTripOptionalStringArrayType(_: Optional<[String]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAdder") -@_cdecl("bjs_makeAdder") -public func _bjs_makeAdder(_ base: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripOptionalGreeterArrayType") +@_cdecl("bjs_roundTripOptionalGreeterArrayType") +public func _bjs_roundTripOptionalGreeterArrayType() -> Void { #if arch(wasm32) - let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) - return _BJS_Closure_20BridgeJSRuntimeTestsSi_Si.bridgeJSLower(ret) + let ret = roundTripOptionalGreeterArrayType(_: Optional<[Greeter]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripIntArray") -@_cdecl("bjs_roundTripIntArray") -public func _bjs_roundTripIntArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedIntArray") +@_cdecl("bjs_roundTripNestedIntArray") +public func _bjs_roundTripNestedIntArray() -> Void { #if arch(wasm32) - let ret = roundTripIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedIntArray(_: [[Int]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripStringArray") -@_cdecl("bjs_roundTripStringArray") -public func _bjs_roundTripStringArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedStringArray") +@_cdecl("bjs_roundTripNestedStringArray") +public func _bjs_roundTripNestedStringArray() -> Void { #if arch(wasm32) - let ret = roundTripStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedStringArray(_: [[String]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDoubleArray") -@_cdecl("bjs_roundTripDoubleArray") -public func _bjs_roundTripDoubleArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedDoubleArray") +@_cdecl("bjs_roundTripNestedDoubleArray") +public func _bjs_roundTripNestedDoubleArray() -> Void { #if arch(wasm32) - let ret = roundTripDoubleArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_f64(__bjs_elem_ret)} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedDoubleArray(_: [[Double]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripBoolArray") -@_cdecl("bjs_roundTripBoolArray") -public func _bjs_roundTripBoolArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedBoolArray") +@_cdecl("bjs_roundTripNestedBoolArray") +public func _bjs_roundTripNestedBoolArray() -> Void { #if arch(wasm32) - let ret = roundTripBoolArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Bool] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(__bjs_elem_ret ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedBoolArray(_: [[Bool]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDirectionArray") -@_cdecl("bjs_roundTripDirectionArray") -public func _bjs_roundTripDirectionArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedDataPointArray") +@_cdecl("bjs_roundTripNestedDataPointArray") +public func _bjs_roundTripNestedDataPointArray() -> Void { #if arch(wasm32) - let ret = roundTripDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Direction] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Direction.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedDataPointArray(_: [[DataPoint]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripStatusArray") -@_cdecl("bjs_roundTripStatusArray") -public func _bjs_roundTripStatusArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedDirectionArray") +@_cdecl("bjs_roundTripNestedDirectionArray") +public func _bjs_roundTripNestedDirectionArray() -> Void { #if arch(wasm32) - let ret = roundTripStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Status] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Status.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedDirectionArray(_: [[Direction]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripThemeArray") -@_cdecl("bjs_roundTripThemeArray") -public func _bjs_roundTripThemeArray() -> Void { +@_expose(wasm, "bjs_roundTripNestedGreeterArray") +@_cdecl("bjs_roundTripNestedGreeterArray") +public func _bjs_roundTripNestedGreeterArray() -> Void { #if arch(wasm32) - let ret = roundTripThemeArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Theme] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Theme.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - var __bjs_ret_elem = __bjs_elem_ret.rawValue - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripNestedGreeterArray(_: [[Greeter]].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripHttpStatusArray") -@_cdecl("bjs_roundTripHttpStatusArray") -public func _bjs_roundTripHttpStatusArray() -> Void { +@_expose(wasm, "bjs_roundTripUnsafeRawPointerArray") +@_cdecl("bjs_roundTripUnsafeRawPointerArray") +public func _bjs_roundTripUnsafeRawPointerArray() -> Void { #if arch(wasm32) - let ret = roundTripHttpStatusArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [HttpStatus] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(HttpStatus.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32(Int32(__bjs_elem_ret.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripUnsafeRawPointerArray(_: [UnsafeRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataPointArray") -@_cdecl("bjs_roundTripDataPointArray") -public func _bjs_roundTripDataPointArray() -> Void { +@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointerArray") +@_cdecl("bjs_roundTripUnsafeMutableRawPointerArray") +public func _bjs_roundTripUnsafeMutableRawPointerArray() -> Void { #if arch(wasm32) - let ret = roundTripDataPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [DataPoint] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(DataPoint.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - __bjs_elem_ret.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripUnsafeMutableRawPointerArray(_: [UnsafeMutableRawPointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripGreeterArray") -@_cdecl("bjs_roundTripGreeterArray") -public func _bjs_roundTripGreeterArray() -> Void { +@_expose(wasm, "bjs_roundTripOpaquePointerArray") +@_cdecl("bjs_roundTripOpaquePointerArray") +public func _bjs_roundTripOpaquePointerArray() -> Void { #if arch(wasm32) - let ret = roundTripGreeterArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Greeter] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Greeter.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOpaquePointerArray(_: [OpaquePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalIntArray") -@_cdecl("bjs_roundTripOptionalIntArray") -public func _bjs_roundTripOptionalIntArray() -> Void { +@_expose(wasm, "bjs_roundTripUnsafePointerArray") +@_cdecl("bjs_roundTripUnsafePointerArray") +public func _bjs_roundTripUnsafePointerArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_unwrapped_ret_elem))} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripUnsafePointerArray(_: [UnsafePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStringArray") -@_cdecl("bjs_roundTripOptionalStringArray") -public func _bjs_roundTripOptionalStringArray() -> Void { +@_expose(wasm, "bjs_roundTripUnsafeMutablePointerArray") +@_cdecl("bjs_roundTripUnsafeMutablePointerArray") +public func _bjs_roundTripUnsafeMutablePointerArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - var __bjs_str_ret_elem = __bjs_unwrapped_ret_elem - __bjs_str_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripUnsafeMutablePointerArray(_: [UnsafeMutablePointer].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDataPointArray") -@_cdecl("bjs_roundTripOptionalDataPointArray") -public func _bjs_roundTripOptionalDataPointArray() -> Void { +@_expose(wasm, "bjs_consumeDataProcessorArrayType") +@_cdecl("bjs_consumeDataProcessorArrayType") +public func _bjs_consumeDataProcessorArrayType() -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalDataPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - let __bjs_isSome_ret_elem = __bjs_elem_ret != nil - if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - __bjs_unwrapped_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(ret.count)) + let ret = consumeDataProcessorArrayType(_: [AnyDataProcessor].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDirectionArray") -@_cdecl("bjs_roundTripOptionalDirectionArray") -public func _bjs_roundTripOptionalDirectionArray() -> Void { +@_expose(wasm, "bjs_roundTripDataProcessorArrayType") +@_cdecl("bjs_roundTripDataProcessorArrayType") +public func _bjs_roundTripDataProcessorArrayType() -> Void { #if arch(wasm32) - let ret = roundTripOptionalDirectionArray(_: { + let ret = roundTripDataProcessorArrayType(_: [AnyDataProcessor].bridgeJSStackPop()) + ret.map { $0 as! AnyDataProcessor }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripJSObjectArray") +@_cdecl("bjs_roundTripJSObjectArray") +public func _bjs_roundTripJSObjectArray() -> Void { + #if arch(wasm32) + let ret = roundTripJSObjectArray(_: [JSObject].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalJSObjectArray") +@_cdecl("bjs_roundTripOptionalJSObjectArray") +public func _bjs_roundTripOptionalJSObjectArray() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalJSObjectArray(_: { let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] + var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop()) } __result.reverse() return __result - }()) + }()) for __bjs_elem_ret in ret { let __bjs_isSome_ret_elem = __bjs_elem_ret != nil if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(__bjs_unwrapped_ret_elem.bridgeJSLowerParameter())} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_unwrapped_ret_elem.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStatusArray") -@_cdecl("bjs_roundTripOptionalStatusArray") -public func _bjs_roundTripOptionalStatusArray() -> Void { +@_expose(wasm, "bjs_roundTripFooArray") +@_cdecl("bjs_roundTripFooArray") +public func _bjs_roundTripFooArray() -> Void { #if arch(wasm32) - let ret = roundTripOptionalStatusArray(_: { + let ret = roundTripFooArray(_: [JSObject].bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) + ret.map { $0.jsObject }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalFooArray") +@_cdecl("bjs_roundTripOptionalFooArray") +public func _bjs_roundTripOptionalFooArray() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalFooArray(_: { let __count = Int(_swift_js_pop_i32()) - var __result: [Optional] = [] + var __result: [Optional] = [] __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Optional.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) + for _ in 0..<__count { + __result.append(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) } __result.reverse() return __result - }()) + }()) for __bjs_elem_ret in ret { let __bjs_isSome_ret_elem = __bjs_elem_ret != nil if let __bjs_unwrapped_ret_elem = __bjs_elem_ret { - _swift_js_push_i32(__bjs_unwrapped_ret_elem.bridgeJSLowerParameter())} - _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0)} + __bjs_unwrapped_ret_elem.jsObject.bridgeJSStackPush() + } + _swift_js_push_i32(__bjs_isSome_ret_elem ? 1 : 0) + } _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalIntArrayType") -@_cdecl("bjs_roundTripOptionalIntArrayType") -public func _bjs_roundTripOptionalIntArrayType(_ values: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalString") +@_cdecl("bjs_roundTripOptionalString") +public func _bjs_roundTripOptionalString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalIntArrayType(_: { - if values == 0 { - return Optional<[Int]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }() - } - }()) - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret))} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + let ret = roundTripOptionalString(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalStringArrayType") -@_cdecl("bjs_roundTripOptionalStringArrayType") -public func _bjs_roundTripOptionalStringArrayType(_ values: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalInt") +@_cdecl("bjs_roundTripOptionalInt") +public func _bjs_roundTripOptionalInt(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalStringArrayType(_: { - if values == 0 { - return Optional<[String]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }() - } - }()) - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - var __bjs_ret_elem = __bjs_elem_ret - __bjs_ret_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + let ret = roundTripOptionalInt(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalGreeterArrayType") -@_cdecl("bjs_roundTripOptionalGreeterArrayType") -public func _bjs_roundTripOptionalGreeterArrayType(_ greeters: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalBool") +@_cdecl("bjs_roundTripOptionalBool") +public func _bjs_roundTripOptionalBool(_ flagIsSome: Int32, _ flagValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOptionalGreeterArrayType(_: { - if greeters == 0 { - return Optional<[Greeter]>.none - } else { - return { - let __count = Int(_swift_js_pop_i32()) - var __result: [Greeter] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Greeter.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }() - } - }()) - let __bjs_isSome_ret = ret != nil - if let __bjs_unwrapped_ret = ret { - for __bjs_elem_ret in __bjs_unwrapped_ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(__bjs_unwrapped_ret.count))} - _swift_js_push_i32(__bjs_isSome_ret ? 1 : 0) + let ret = roundTripOptionalBool(flag: Optional.bridgeJSLiftParameter(flagIsSome, flagValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedIntArray") -@_cdecl("bjs_roundTripNestedIntArray") -public func _bjs_roundTripNestedIntArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalFloat") +@_cdecl("bjs_roundTripOptionalFloat") +public func _bjs_roundTripOptionalFloat(_ numberIsSome: Int32, _ numberValue: Float32) -> Void { #if arch(wasm32) - let ret = roundTripNestedIntArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Int]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Int] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Int.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret_elem))} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalFloat(number: Optional.bridgeJSLiftParameter(numberIsSome, numberValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedStringArray") -@_cdecl("bjs_roundTripNestedStringArray") -public func _bjs_roundTripNestedStringArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalDouble") +@_cdecl("bjs_roundTripOptionalDouble") +public func _bjs_roundTripOptionalDouble(_ precisionIsSome: Int32, _ precisionValue: Float64) -> Void { #if arch(wasm32) - let ret = roundTripNestedStringArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[String]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [String] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(String.bridgeJSLiftParameter(_swift_js_pop_i32(), _swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - var __bjs_ret_elem_elem = __bjs_elem_ret_elem - __bjs_ret_elem_elem.withUTF8 { ptr in - _swift_js_push_string(ptr.baseAddress, Int32(ptr.count)) - }} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalDouble(precision: Optional.bridgeJSLiftParameter(precisionIsSome, precisionValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDoubleArray") -@_cdecl("bjs_roundTripNestedDoubleArray") -public func _bjs_roundTripNestedDoubleArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalSyntax") +@_cdecl("bjs_roundTripOptionalSyntax") +public func _bjs_roundTripOptionalSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedDoubleArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Double]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Double] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Double.bridgeJSLiftParameter(_swift_js_pop_f64())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_f64(__bjs_elem_ret_elem)} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedBoolArray") -@_cdecl("bjs_roundTripNestedBoolArray") -public func _bjs_roundTripNestedBoolArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalMixSyntax") +@_cdecl("bjs_roundTripOptionalMixSyntax") +public func _bjs_roundTripOptionalMixSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedBoolArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Bool]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Bool] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Bool.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(__bjs_elem_ret_elem ? 1 : 0)} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalMixSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDataPointArray") -@_cdecl("bjs_roundTripNestedDataPointArray") -public func _bjs_roundTripNestedDataPointArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalSwiftSyntax") +@_cdecl("bjs_roundTripOptionalSwiftSyntax") +public func _bjs_roundTripOptionalSwiftSyntax(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedDataPointArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[DataPoint]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [DataPoint] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(DataPoint.bridgeJSLiftParameter()) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - __bjs_elem_ret_elem.bridgeJSLowerReturn()} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalSwiftSyntax(name: Optional.bridgeJSLiftParameter(nameIsSome, nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedDirectionArray") -@_cdecl("bjs_roundTripNestedDirectionArray") -public func _bjs_roundTripNestedDirectionArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalWithSpaces") +@_cdecl("bjs_roundTripOptionalWithSpaces") +public func _bjs_roundTripOptionalWithSpaces(_ valueIsSome: Int32, _ valueValue: Float64) -> Void { #if arch(wasm32) - let ret = roundTripNestedDirectionArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Direction]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Direction] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Direction.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_i32(Int32(__bjs_elem_ret_elem.bridgeJSLowerParameter()))} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalWithSpaces(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripNestedGreeterArray") -@_cdecl("bjs_roundTripNestedGreeterArray") -public func _bjs_roundTripNestedGreeterArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalTypeAlias") +@_cdecl("bjs_roundTripOptionalTypeAlias") +public func _bjs_roundTripOptionalTypeAlias(_ ageIsSome: Int32, _ ageValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripNestedGreeterArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [[Greeter]] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append({ - let __count = Int(_swift_js_pop_i32()) - var __result: [Greeter] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(Greeter.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - for __bjs_elem_ret_elem in __bjs_elem_ret { - _swift_js_push_pointer(__bjs_elem_ret_elem.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(__bjs_elem_ret.count))} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalTypeAlias(age: Optional.bridgeJSLiftParameter(ageIsSome, ageValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeRawPointerArray") -@_cdecl("bjs_roundTripUnsafeRawPointerArray") -public func _bjs_roundTripUnsafeRawPointerArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalStatus") +@_cdecl("bjs_roundTripOptionalStatus") +public func _bjs_roundTripOptionalStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUnsafeRawPointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [UnsafeRawPointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(UnsafeRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointerArray") -@_cdecl("bjs_roundTripUnsafeMutableRawPointerArray") -public func _bjs_roundTripUnsafeMutableRawPointerArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalTheme") +@_cdecl("bjs_roundTripOptionalTheme") +public func _bjs_roundTripOptionalTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripUnsafeMutableRawPointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [UnsafeMutableRawPointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(UnsafeMutableRawPointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOpaquePointerArray") -@_cdecl("bjs_roundTripOpaquePointerArray") -public func _bjs_roundTripOpaquePointerArray() -> Void { +@_expose(wasm, "bjs_roundTripOptionalHttpStatus") +@_cdecl("bjs_roundTripOptionalHttpStatus") +public func _bjs_roundTripOptionalHttpStatus(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = roundTripOpaquePointerArray(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [OpaquePointer] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(OpaquePointer.bridgeJSLiftParameter(_swift_js_pop_pointer())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_pointer(__bjs_elem_ret.bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalHttpStatus(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_consumeDataProcessorArrayType") -@_cdecl("bjs_consumeDataProcessorArrayType") -public func _bjs_consumeDataProcessorArrayType() -> Int32 { +@_expose(wasm, "bjs_roundTripOptionalTSDirection") +@_cdecl("bjs_roundTripOptionalTSDirection") +public func _bjs_roundTripOptionalTSDirection(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = consumeDataProcessorArrayType(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [AnyDataProcessor] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(AnyDataProcessor.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) + let ret = roundTripOptionalTSDirection(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataProcessorArrayType") -@_cdecl("bjs_roundTripDataProcessorArrayType") -public func _bjs_roundTripDataProcessorArrayType() -> Void { +@_expose(wasm, "bjs_roundTripOptionalTSTheme") +@_cdecl("bjs_roundTripOptionalTSTheme") +public func _bjs_roundTripOptionalTSTheme(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripDataProcessorArrayType(_: { - let __count = Int(_swift_js_pop_i32()) - var __result: [AnyDataProcessor] = [] - __result.reserveCapacity(__count) - for _ in 0 ..< __count { - __result.append(AnyDataProcessor.bridgeJSLiftParameter(_swift_js_pop_i32())) - } - __result.reverse() - return __result - }()) - for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! AnyDataProcessor).bridgeJSLowerReturn())} - _swift_js_push_i32(Int32(ret.count)) + let ret = roundTripOptionalTSTheme(value: Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalNetworkingAPIMethod") +@_cdecl("bjs_roundTripOptionalNetworkingAPIMethod") +public func _bjs_roundTripOptionalNetworkingAPIMethod(_ methodIsSome: Int32, _ methodValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalNetworkingAPIMethod(_: Optional.bridgeJSLiftParameter(methodIsSome, methodValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAPIResult") +@_cdecl("bjs_roundTripOptionalAPIResult") +public func _bjs_roundTripOptionalAPIResult(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAPIResult(value: Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalTypedPayloadResult") +@_cdecl("bjs_roundTripOptionalTypedPayloadResult") +public func _bjs_roundTripOptionalTypedPayloadResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_takeOptionalJSObject") +@_cdecl("bjs_takeOptionalJSObject") +public func _bjs_takeOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + takeOptionalJSObject(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_compareAPIResults") +@_cdecl("bjs_compareAPIResults") +public func _bjs_compareAPIResults(_ r1IsSome: Int32, _ r1CaseId: Int32, _ r2IsSome: Int32, _ r2CaseId: Int32) -> Void { + #if arch(wasm32) + let _tmp_r2 = Optional.bridgeJSLiftParameter(r2IsSome, r2CaseId) + let _tmp_r1 = Optional.bridgeJSLiftParameter(r1IsSome, r1CaseId) + let ret = compareAPIResults(_: _tmp_r1, _: _tmp_r2) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalComplexResult") +@_cdecl("bjs_roundTripOptionalComplexResult") +public func _bjs_roundTripOptionalComplexResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAllTypesResult") +@_cdecl("bjs_roundTripOptionalAllTypesResult") +public func _bjs_roundTripOptionalAllTypesResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalPayloadResult") +@_cdecl("bjs_roundTripOptionalPayloadResult") +public func _bjs_roundTripOptionalPayloadResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalPayloadResultOpt") +@_cdecl("bjs_roundTripOptionalPayloadResultOpt") +public func _bjs_roundTripOptionalPayloadResultOpt(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalClass") +@_cdecl("bjs_roundTripOptionalClass") +public func _bjs_roundTripOptionalClass(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalGreeter") +@_cdecl("bjs_roundTripOptionalGreeter") +public func _bjs_roundTripOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_applyOptionalGreeter") +@_cdecl("bjs_applyOptionalGreeter") +public func _bjs_applyOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer, _ transform: Int32) -> Void { + #if arch(wasm32) + let ret = applyOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue), _: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC.bridgeJSLift(transform)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeOptionalHolder") +@_cdecl("bjs_makeOptionalHolder") +public func _bjs_makeOptionalHolder(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeOptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripOptionalAPIOptionalResult") +@_cdecl("bjs_roundTripOptionalAPIOptionalResult") +public func _bjs_roundTripOptionalAPIOptionalResult(_ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalAPIOptionalResult(result: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -5508,6 +6503,17 @@ public func _bjs_roundTripDataPoint() -> Void { #endif } +@_expose(wasm, "bjs_roundTripPublicPoint") +@_cdecl("bjs_roundTripPublicPoint") +public func _bjs_roundTripPublicPoint() -> Void { + #if arch(wasm32) + let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripContact") @_cdecl("bjs_roundTripContact") public func _bjs_roundTripContact() -> Void { @@ -5598,43 +6604,196 @@ public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { #endif } -@_expose(wasm, "bjs_Greeter_init") -@_cdecl("bjs_Greeter_init") -public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripJSObjectContainer") +@_cdecl("bjs_roundTripJSObjectContainer") +public func _bjs_roundTripJSObjectContainer() -> Void { #if arch(wasm32) - let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_greet") -@_cdecl("bjs_Greeter_greet") -public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_roundTripFooContainer") +@_cdecl("bjs_roundTripFooContainer") +public func _bjs_roundTripFooContainer() -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() + let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_changeName") -@_cdecl("bjs_Greeter_changeName") -public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripArrayMembers") +@_cdecl("bjs_roundTripArrayMembers") +public func _bjs_roundTripArrayMembers() -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_greetWith") -@_cdecl("bjs_Greeter_greetWith") -public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer, _ customGreeting: Int32) -> Void { +@_expose(wasm, "bjs_arrayMembersSum") +@_cdecl("bjs_arrayMembersSum") +public func _bjs_arrayMembersSum() -> Int32 { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetWith(greeter: Greeter.bridgeJSLiftParameter(greeter), customGreeting: _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLift(customGreeting)) + let _tmp_values = [Int].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_arrayMembersFirst") +@_cdecl("bjs_arrayMembersFirst") +public func _bjs_arrayMembersFirst() -> Void { + #if arch(wasm32) + let _tmp_values = [String].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeIntToInt") +@_cdecl("bjs_ClosureSupportExports_static_makeIntToInt") +public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeIntToInt(_: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeDoubleToDouble") +@_cdecl("bjs_ClosureSupportExports_static_makeDoubleToDouble") +public func _bjs_ClosureSupportExports_static_makeDoubleToDouble(_ base: Float64) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeStringToString") +@_cdecl("bjs_ClosureSupportExports_static_makeStringToString") +public func _bjs_ClosureSupportExports_static_makeStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSIntToInt") +@_cdecl("bjs_ClosureSupportExports_static_makeJSIntToInt") +public func _bjs_ClosureSupportExports_static_makeJSIntToInt(_ base: Int32) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeJSIntToInt(_: Int.bridgeJSLiftParameter(base)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSDoubleToDouble") +@_cdecl("bjs_ClosureSupportExports_static_makeJSDoubleToDouble") +public func _bjs_ClosureSupportExports_static_makeJSDoubleToDouble(_ base: Float64) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeJSDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSStringToString") +@_cdecl("bjs_ClosureSupportExports_static_makeJSStringToString") +public func _bjs_ClosureSupportExports_static_makeJSStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = ClosureSupportExports.makeJSStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ClosureSupportExports_deinit") +@_cdecl("bjs_ClosureSupportExports_deinit") +public func _bjs_ClosureSupportExports_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ClosureSupportExports: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportExports_wrap") +fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ClosureSupportExports_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClosureSupportExports_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_Greeter_init") +@_cdecl("bjs_Greeter_init") +public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_greet") +@_cdecl("bjs_Greeter_greet") +public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greet() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_changeName") +@_cdecl("bjs_Greeter_changeName") +public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_greetWith") +@_cdecl("bjs_Greeter_greetWith") +public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer, _ customGreeting: Int32) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greetWith(greeter: Greeter.bridgeJSLiftParameter(greeter), customGreeting: _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLift(customGreeting)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -5643,10 +6802,10 @@ public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: @_expose(wasm, "bjs_Greeter_makeFormatter") @_cdecl("bjs_Greeter_makeFormatter") -public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffixBytes: Int32, _ suffixLength: Int32) -> UnsafeMutableRawPointer { +public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffixBytes: Int32, _ suffixLength: Int32) -> Int32 { #if arch(wasm32) let ret = Greeter.bridgeJSLiftParameter(_self).makeFormatter(suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) - return _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -5654,10 +6813,10 @@ public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffi @_expose(wasm, "bjs_Greeter_static_makeCreator") @_cdecl("bjs_Greeter_static_makeCreator") -public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> UnsafeMutableRawPointer { +public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> Int32 { #if arch(wasm32) let ret = Greeter.makeCreator(defaultName: String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength)) - return _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -5665,10 +6824,10 @@ public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ default @_expose(wasm, "bjs_Greeter_makeCustomGreeter") @_cdecl("bjs_Greeter_makeCustomGreeter") -public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = Greeter.bridgeJSLiftParameter(_self).makeCustomGreeter() - return _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -5724,12 +6883,15 @@ extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_Calculator_square") @_cdecl("bjs_Calculator_square") @@ -5771,12 +6933,15 @@ extension Calculator: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Calculator_wrap") -fileprivate func _bjs_Calculator_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Calculator_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Calculator_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Calculator_wrap_extern(pointer) +} @_expose(wasm, "bjs_InternalGreeter_deinit") @_cdecl("bjs_InternalGreeter_deinit") @@ -5796,12 +6961,15 @@ extension InternalGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_InternalGreeter_wrap") -fileprivate func _bjs_InternalGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_InternalGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_InternalGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_InternalGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_PublicGreeter_deinit") @_cdecl("bjs_PublicGreeter_deinit") @@ -5821,12 +6989,15 @@ extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PublicGreeter_wrap") -fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PublicGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_PackageGreeter_deinit") @_cdecl("bjs_PackageGreeter_deinit") @@ -5846,12 +7017,15 @@ extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PackageGreeter_wrap") -fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PackageGreeter_wrap_extern(pointer) +} @_expose(wasm, "bjs_Converter_init") @_cdecl("bjs_Converter_init") @@ -5893,12 +7067,15 @@ extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Converter_wrap") -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Converter_wrap_extern(pointer) +} @_expose(wasm, "bjs_HTTPServer_init") @_cdecl("bjs_HTTPServer_init") @@ -5939,12 +7116,15 @@ extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObje #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_HTTPServer_wrap") -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_HTTPServer_wrap_extern(pointer) +} @_expose(wasm, "bjs_TestServer_init") @_cdecl("bjs_TestServer_init") @@ -5985,111 +7165,15 @@ extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TestServer_wrap") -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif - -@_expose(wasm, "bjs_OptionalPropertyHolder_init") -@_cdecl("bjs_OptionalPropertyHolder_init") -public func _bjs_OptionalPropertyHolder_init(_ optionalNameIsSome: Int32, _ optionalNameBytes: Int32, _ optionalNameLength: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = OptionalPropertyHolder(optionalName: Optional.bridgeJSLiftParameter(optionalNameIsSome, optionalNameBytes, optionalNameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") -public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") -public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") -public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") -public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") -public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") -public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") -@_cdecl("bjs_OptionalPropertyHolder_deinit") -public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalPropertyHolder_wrap") -fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") +@inline(never) fileprivate func _bjs_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TestServer_wrap_extern(pointer) } -#endif @_expose(wasm, "bjs_SimplePropertyHolder_init") @_cdecl("bjs_SimplePropertyHolder_init") @@ -6141,12 +7225,15 @@ extension SimplePropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SimplePropertyHolder_wrap") -fileprivate func _bjs_SimplePropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_SimplePropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_SimplePropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SimplePropertyHolder_wrap_extern(pointer) +} @_expose(wasm, "bjs_PropertyHolder_init") @_cdecl("bjs_PropertyHolder_init") @@ -6464,12 +7551,15 @@ extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PropertyHolder_wrap") -fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PropertyHolder_wrap_extern(pointer) +} @_expose(wasm, "bjs_MathUtils_static_add") @_cdecl("bjs_MathUtils_static_add") @@ -6511,12 +7601,15 @@ extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MathUtils_wrap") -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_MathUtils_wrap_extern(pointer) +} @_expose(wasm, "bjs_ConstructorDefaults_init") @_cdecl("bjs_ConstructorDefaults_init") @@ -6663,12 +7756,15 @@ extension ConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ConstructorDefaults_wrap") -fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ConstructorDefaults_wrap_extern(pointer) +} @_expose(wasm, "bjs_StaticPropertyHolder_init") @_cdecl("bjs_StaticPropertyHolder_init") @@ -6910,12 +8006,15 @@ extension StaticPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticPropertyHolder_wrap") -fileprivate func _bjs_StaticPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_StaticPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_StaticPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_StaticPropertyHolder_wrap_extern(pointer) +} @_expose(wasm, "bjs_DataProcessorManager_init") @_cdecl("bjs_DataProcessorManager_init") @@ -7164,9 +8263,7 @@ public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPoi @_cdecl("bjs_DataProcessorManager_backupProcessor_get") public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor.flatMap { - $0 as? AnyDataProcessor - } + let ret = (DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor).flatMap { $0 as? AnyDataProcessor } return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -7201,12 +8298,15 @@ extension DataProcessorManager: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessorManager_wrap") -fileprivate func _bjs_DataProcessorManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_DataProcessorManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_DataProcessorManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_DataProcessorManager_wrap_extern(pointer) +} @_expose(wasm, "bjs_SwiftDataProcessor_init") @_cdecl("bjs_SwiftDataProcessor_init") @@ -7555,12 +8655,15 @@ extension SwiftDataProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SwiftDataProcessor_wrap") -fileprivate func _bjs_SwiftDataProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_SwiftDataProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func _bjs_SwiftDataProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SwiftDataProcessor_wrap_extern(pointer) +} @_expose(wasm, "bjs_TextProcessor_init") @_cdecl("bjs_TextProcessor_init") @@ -7597,10 +8700,10 @@ public func _bjs_TextProcessor_processWithCustom(_ _self: UnsafeMutableRawPointe @_expose(wasm, "bjs_TextProcessor_getTransform") @_cdecl("bjs_TextProcessor_getTransform") -public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).getTransform() - return _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7641,10 +8744,10 @@ public func _bjs_TextProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawP @_expose(wasm, "bjs_TextProcessor_makeOptionalStringFormatter") @_cdecl("bjs_TextProcessor_makeOptionalStringFormatter") -public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalStringFormatter() - return _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7652,10 +8755,10 @@ public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutabl @_expose(wasm, "bjs_TextProcessor_makeOptionalGreeterCreator") @_cdecl("bjs_TextProcessor_makeOptionalGreeterCreator") -public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalGreeterCreator() - return _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7707,10 +8810,10 @@ public func _bjs_TextProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer @_expose(wasm, "bjs_TextProcessor_makeDirectionChecker") @_cdecl("bjs_TextProcessor_makeDirectionChecker") -public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDirectionChecker() - return _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_Sb.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7718,10 +8821,10 @@ public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPoi @_expose(wasm, "bjs_TextProcessor_makeThemeValidator") @_cdecl("bjs_TextProcessor_makeThemeValidator") -public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeThemeValidator() - return _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7729,10 +8832,10 @@ public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPoint @_expose(wasm, "bjs_TextProcessor_makeStatusCodeExtractor") @_cdecl("bjs_TextProcessor_makeStatusCodeExtractor") -public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeStatusCodeExtractor() - return _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7740,10 +8843,10 @@ public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRaw @_expose(wasm, "bjs_TextProcessor_makeAPIResultHandler") @_cdecl("bjs_TextProcessor_makeAPIResultHandler") -public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeAPIResultHandler() - return _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7784,10 +8887,10 @@ public func _bjs_TextProcessor_processOptionalAPIResult(_ _self: UnsafeMutableRa @_expose(wasm, "bjs_TextProcessor_makeOptionalDirectionFormatter") @_cdecl("bjs_TextProcessor_makeOptionalDirectionFormatter") -public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalDirectionFormatter() - return _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS.bridgeJSLower(ret) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7810,775 +8913,2359 @@ extension TextProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject { } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TextProcessor_wrap") -fileprivate func _bjs_TextProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TextProcessor_wrap") +fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TextProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TextProcessor_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_OptionalHolder_init") +@_cdecl("bjs_OptionalHolder_init") +public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = OptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_get") +@_cdecl("bjs_OptionalHolder_nullableGreeter_get") +public func _bjs_OptionalHolder_nullableGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_set") +@_cdecl("bjs_OptionalHolder_nullableGreeter_set") +public func _bjs_OptionalHolder_nullableGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_get") +@_cdecl("bjs_OptionalHolder_undefinedNumber_get") +public func _bjs_OptionalHolder_undefinedNumber_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_set") +@_cdecl("bjs_OptionalHolder_undefinedNumber_set") +public func _bjs_OptionalHolder_undefinedNumber_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { + #if arch(wasm32) + OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber = JSUndefinedOr.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalHolder_deinit") +@_cdecl("bjs_OptionalHolder_deinit") +public func _bjs_OptionalHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension OptionalHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalHolder_wrap") +fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_OptionalHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalHolder_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_init") +@_cdecl("bjs_OptionalPropertyHolder_init") +public func _bjs_OptionalPropertyHolder_init(_ optionalNameIsSome: Int32, _ optionalNameBytes: Int32, _ optionalNameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = OptionalPropertyHolder(optionalName: Optional.bridgeJSLiftParameter(optionalNameIsSome, optionalNameBytes, optionalNameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") +public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") +public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") +public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") +public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") +public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") +public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") +@_cdecl("bjs_OptionalPropertyHolder_deinit") +public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalPropertyHolder_wrap") +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalPropertyHolder_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_Container_init") +@_cdecl("bjs_Container_init") +public func _bjs_Container_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let _tmp_config = Optional.bridgeJSLiftParameter() + let _tmp_location = DataPoint.bridgeJSLiftParameter() + let ret = Container(location: _tmp_location, config: _tmp_config) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Container_location_get") +@_cdecl("bjs_Container_location_get") +public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Container.bridgeJSLiftParameter(_self).location + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Container_location_set") +@_cdecl("bjs_Container_location_set") +public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Container.bridgeJSLiftParameter(_self).location = DataPoint.bridgeJSLiftParameter() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Container_config_get") +@_cdecl("bjs_Container_config_get") +public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Container.bridgeJSLiftParameter(_self).config + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Container_config_set") +@_cdecl("bjs_Container_config_set") +public func _bjs_Container_config_set(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Container.bridgeJSLiftParameter(_self).config = Optional.bridgeJSLiftParameter() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Container_deinit") +@_cdecl("bjs_Container_deinit") +public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Container_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") +fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static(_ callback: Int32) -> Void { + return bjs_ClosureSupportImports_jsApplyVoid_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyBool_static") +fileprivate func bjs_ClosureSupportImports_jsApplyBool_static_extern(_ callback: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsApplyBool_static_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyBool_static(_ callback: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyBool_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyInt_static") +fileprivate func bjs_ClosureSupportImports_jsApplyInt_static_extern(_ value: Int32, _ transform: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsApplyInt_static_extern(_ value: Int32, _ transform: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyInt_static(_ value: Int32, _ transform: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyInt_static_extern(value, transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyDouble_static") +fileprivate func bjs_ClosureSupportImports_jsApplyDouble_static_extern(_ value: Float64, _ transform: Int32) -> Float64 +#else +fileprivate func bjs_ClosureSupportImports_jsApplyDouble_static_extern(_ value: Float64, _ transform: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyDouble_static(_ value: Float64, _ transform: Int32) -> Float64 { + return bjs_ClosureSupportImports_jsApplyDouble_static_extern(value, transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyString_static") +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ value: Int32, _ transform: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsApplyString_static_extern(_ value: Int32, _ transform: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyString_static(_ value: Int32, _ transform: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyString_static_extern(value, transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyJSObject_static") +fileprivate func bjs_ClosureSupportImports_jsApplyJSObject_static_extern(_ value: Int32, _ transform: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsApplyJSObject_static_extern(_ value: Int32, _ transform: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsApplyJSObject_static(_ value: Int32, _ transform: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsApplyJSObject_static_extern(value, transform) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeIntToInt_static") +fileprivate func bjs_ClosureSupportImports_jsMakeIntToInt_static_extern(_ base: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsMakeIntToInt_static_extern(_ base: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeIntToInt_static(_ base: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsMakeIntToInt_static_extern(base) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeDoubleToDouble_static") +fileprivate func bjs_ClosureSupportImports_jsMakeDoubleToDouble_static_extern(_ base: Float64) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsMakeDoubleToDouble_static_extern(_ base: Float64) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeDoubleToDouble_static(_ base: Float64) -> Int32 { + return bjs_ClosureSupportImports_jsMakeDoubleToDouble_static_extern(base) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsMakeStringToString_static") +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefix: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static_extern(_ prefix: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsMakeStringToString_static(_ prefix: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsMakeStringToString_static_extern(prefix) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsCallTwice_static") +fileprivate func bjs_ClosureSupportImports_jsCallTwice_static_extern(_ value: Int32, _ callback: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsCallTwice_static_extern(_ value: Int32, _ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsCallTwice_static(_ value: Int32, _ callback: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsCallTwice_static_extern(value, callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsCallBinary_static") +fileprivate func bjs_ClosureSupportImports_jsCallBinary_static_extern(_ callback: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsCallBinary_static_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsCallBinary_static(_ callback: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsCallBinary_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsCallTriple_static") +fileprivate func bjs_ClosureSupportImports_jsCallTriple_static_extern(_ callback: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsCallTriple_static_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsCallTriple_static(_ callback: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsCallTriple_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsCallAfterRelease_static") +fileprivate func bjs_ClosureSupportImports_jsCallAfterRelease_static_extern(_ callback: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsCallAfterRelease_static_extern(_ callback: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsCallAfterRelease_static(_ callback: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsCallAfterRelease_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsOptionalInvoke_static") +fileprivate func bjs_ClosureSupportImports_jsOptionalInvoke_static_extern(_ callbackIsSome: Int32, _ callbackFuncRef: Int32) -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsOptionalInvoke_static_extern(_ callbackIsSome: Int32, _ callbackFuncRef: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsOptionalInvoke_static(_ callbackIsSome: Int32, _ callbackFuncRef: Int32) -> Int32 { + return bjs_ClosureSupportImports_jsOptionalInvoke_static_extern(callbackIsSome, callbackFuncRef) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsStoreClosure_static") +fileprivate func bjs_ClosureSupportImports_jsStoreClosure_static_extern(_ callback: Int32) -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsStoreClosure_static_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsStoreClosure_static(_ callback: Int32) -> Void { + return bjs_ClosureSupportImports_jsStoreClosure_static_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsCallStoredClosure_static") +fileprivate func bjs_ClosureSupportImports_jsCallStoredClosure_static_extern() -> Void +#else +fileprivate func bjs_ClosureSupportImports_jsCallStoredClosure_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsCallStoredClosure_static() -> Void { + return bjs_ClosureSupportImports_jsCallStoredClosure_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsHeapCount_static") +fileprivate func bjs_ClosureSupportImports_jsHeapCount_static_extern() -> Int32 +#else +fileprivate func bjs_ClosureSupportImports_jsHeapCount_static_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_jsHeapCount_static() -> Int32 { + return bjs_ClosureSupportImports_jsHeapCount_static_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_runJsClosureSupportTests_static") +fileprivate func bjs_ClosureSupportImports_runJsClosureSupportTests_static_extern() -> Void +#else +fileprivate func bjs_ClosureSupportImports_runJsClosureSupportTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureSupportImports_runJsClosureSupportTests_static() -> Void { + return bjs_ClosureSupportImports_runJsClosureSupportTests_static_extern() +} + +func _$ClosureSupportImports_jsApplyVoid(_ callback: JSTypedClosure<() -> Void>) throws(JSException) -> Void { + let callbackFuncRef = callback.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsApplyVoid_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$ClosureSupportImports_jsApplyBool(_ callback: JSTypedClosure<() -> Bool>) throws(JSException) -> Bool { + let callbackFuncRef = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyBool_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsApplyInt(_ value: Int, _ transform: JSTypedClosure<(Int) -> Int>) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyInt_static(valueValue, transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsApplyDouble(_ value: Double, _ transform: JSTypedClosure<(Double) -> Double>) throws(JSException) -> Double { + let valueValue = value.bridgeJSLowerParameter() + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyDouble_static(valueValue, transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsApplyString(_ value: String, _ transform: JSTypedClosure<(String) -> String>) throws(JSException) -> String { + let valueValue = value.bridgeJSLowerParameter() + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyString_static(valueValue, transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsApplyJSObject(_ value: JSObject, _ transform: JSTypedClosure<(JSObject) -> JSObject>) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let transformFuncRef = transform.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsApplyJSObject_static(valueValue, transformFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsMakeIntToInt(_ base: Int) throws(JSException) -> (Int) -> Int { + let baseValue = base.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsMakeIntToInt_static(baseValue) + if let error = _swift_js_take_exception() { + throw error + } + return _BJS_Closure_20BridgeJSRuntimeTestsSi_Si.bridgeJSLift(ret) +} + +func _$ClosureSupportImports_jsMakeDoubleToDouble(_ base: Double) throws(JSException) -> (Double) -> Double { + let baseValue = base.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsMakeDoubleToDouble_static(baseValue) + if let error = _swift_js_take_exception() { + throw error + } + return _BJS_Closure_20BridgeJSRuntimeTestsSd_Sd.bridgeJSLift(ret) +} + +func _$ClosureSupportImports_jsMakeStringToString(_ prefix: String) throws(JSException) -> (String) -> String { + let prefixValue = prefix.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsMakeStringToString_static(prefixValue) + if let error = _swift_js_take_exception() { + throw error + } + return _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(ret) +} + +func _$ClosureSupportImports_jsCallTwice(_ value: Int, _ callback: JSTypedClosure<(Int) -> Void>) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let callbackFuncRef = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsCallTwice_static(valueValue, callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsCallBinary(_ callback: JSTypedClosure<(Int, Int) -> Int>) throws(JSException) -> Int { + let callbackFuncRef = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsCallBinary_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsCallTriple(_ callback: JSTypedClosure<(Int, Int, Int) -> Int>) throws(JSException) -> Int { + let callbackFuncRef = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsCallTriple_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsCallAfterRelease(_ callback: JSTypedClosure<() -> Void>) throws(JSException) -> String { + let callbackFuncRef = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsCallAfterRelease_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsOptionalInvoke(_ callback: Optional Bool>>) throws(JSException) -> Bool { + let (callbackIsSome, callbackFuncRef) = callback.bridgeJSLowerParameter() + let ret = bjs_ClosureSupportImports_jsOptionalInvoke_static(callbackIsSome, callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_jsStoreClosure(_ callback: JSTypedClosure<() -> Void>) throws(JSException) -> Void { + let callbackFuncRef = callback.bridgeJSLowerParameter() + bjs_ClosureSupportImports_jsStoreClosure_static(callbackFuncRef) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$ClosureSupportImports_jsCallStoredClosure() throws(JSException) -> Void { + bjs_ClosureSupportImports_jsCallStoredClosure_static() + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$ClosureSupportImports_jsHeapCount() throws(JSException) -> Int { + let ret = bjs_ClosureSupportImports_jsHeapCount_static() + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ClosureSupportImports_runJsClosureSupportTests() throws(JSException) -> Void { + bjs_ClosureSupportImports_runJsClosureSupportTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionary") +fileprivate func bjs_jsRoundTripDictionary_extern() -> Void +#else +fileprivate func bjs_jsRoundTripDictionary_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripDictionary() -> Void { + return bjs_jsRoundTripDictionary_extern() +} + +func _$jsRoundTripDictionary(_ values: [String: Int]) throws(JSException) -> [String: Int] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripDictionary() + if let error = _swift_js_take_exception() { + throw error + } + return [String: Int].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryBool") +fileprivate func bjs_jsRoundTripDictionaryBool_extern() -> Void +#else +fileprivate func bjs_jsRoundTripDictionaryBool_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripDictionaryBool() -> Void { + return bjs_jsRoundTripDictionaryBool_extern() +} + +func _$jsRoundTripDictionaryBool(_ values: [String: Bool]) throws(JSException) -> [String: Bool] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripDictionaryBool() + if let error = _swift_js_take_exception() { + throw error + } + return [String: Bool].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryDouble") +fileprivate func bjs_jsRoundTripDictionaryDouble_extern() -> Void +#else +fileprivate func bjs_jsRoundTripDictionaryDouble_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripDictionaryDouble() -> Void { + return bjs_jsRoundTripDictionaryDouble_extern() +} + +func _$jsRoundTripDictionaryDouble(_ values: [String: Double]) throws(JSException) -> [String: Double] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripDictionaryDouble() + if let error = _swift_js_take_exception() { + throw error + } + return [String: Double].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryJSObject") +fileprivate func bjs_jsRoundTripDictionaryJSObject_extern() -> Void +#else +fileprivate func bjs_jsRoundTripDictionaryJSObject_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripDictionaryJSObject() -> Void { + return bjs_jsRoundTripDictionaryJSObject_extern() +} + +func _$jsRoundTripDictionaryJSObject(_ values: [String: JSObject]) throws(JSException) -> [String: JSObject] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripDictionaryJSObject() + if let error = _swift_js_take_exception() { + throw error + } + return [String: JSObject].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripDictionaryJSValue") +fileprivate func bjs_jsRoundTripDictionaryJSValue_extern() -> Void +#else +fileprivate func bjs_jsRoundTripDictionaryJSValue_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripDictionaryJSValue() -> Void { + return bjs_jsRoundTripDictionaryJSValue_extern() +} + +func _$jsRoundTripDictionaryJSValue(_ values: [String: JSValue]) throws(JSException) -> [String: JSValue] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripDictionaryJSValue() + if let error = _swift_js_take_exception() { + throw error + } + return [String: JSValue].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripNestedDictionary") +fileprivate func bjs_jsRoundTripNestedDictionary_extern() -> Void +#else +fileprivate func bjs_jsRoundTripNestedDictionary_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripNestedDictionary() -> Void { + return bjs_jsRoundTripNestedDictionary_extern() +} + +func _$jsRoundTripNestedDictionary(_ values: [String: [Double]]) throws(JSException) -> [String: [Double]] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripNestedDictionary() + if let error = _swift_js_take_exception() { + throw error + } + return [String: [Double]].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalDictionary") +fileprivate func bjs_jsRoundTripOptionalDictionary_extern(_ values: Int32) -> Void +#else +fileprivate func bjs_jsRoundTripOptionalDictionary_extern(_ values: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalDictionary(_ values: Int32) -> Void { + return bjs_jsRoundTripOptionalDictionary_extern(values) +} + +func _$jsRoundTripOptionalDictionary(_ values: Optional<[String: String]>) throws(JSException) -> Optional<[String: String]> { + let valuesIsSome = values.bridgeJSLowerParameter() + bjs_jsRoundTripOptionalDictionary(valuesIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional<[String: String]>.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripUndefinedDictionary") +fileprivate func bjs_jsRoundTripUndefinedDictionary_extern(_ values: Int32) -> Void +#else +fileprivate func bjs_jsRoundTripUndefinedDictionary_extern(_ values: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripUndefinedDictionary(_ values: Int32) -> Void { + return bjs_jsRoundTripUndefinedDictionary_extern(values) +} + +func _$jsRoundTripUndefinedDictionary(_ values: JSUndefinedOr<[String: Int]>) throws(JSException) -> JSUndefinedOr<[String: Int]> { + let valuesIsSome = values.bridgeJSLowerParameter() + bjs_jsRoundTripUndefinedDictionary(valuesIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return JSUndefinedOr<[String: Int]>.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_init") +fileprivate func bjs_Foo_init_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_Foo_init_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Foo_init(_ value: Int32) -> Int32 { + return bjs_Foo_init_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_value_get") +fileprivate func bjs_Foo_value_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Foo_value_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Foo_value_get(_ self: Int32) -> Int32 { + return bjs_Foo_value_get_extern(self) +} + +func _$Foo_init(_ value: String) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_Foo_init(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$Foo_value_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Foo_value_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_globalObject1_get") +fileprivate func bjs_globalObject1_get_extern() -> Void +#else +fileprivate func bjs_globalObject1_get_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_globalObject1_get() -> Void { + return bjs_globalObject1_get_extern() +} + +func _$globalObject1_get() throws(JSException) -> JSValue { + bjs_globalObject1_get() + if let error = _swift_js_take_exception() { + throw error + } + return JSValue.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripVoid") +fileprivate func bjs_jsRoundTripVoid_extern() -> Void +#else +fileprivate func bjs_jsRoundTripVoid_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripVoid() -> Void { + return bjs_jsRoundTripVoid_extern() +} + +func _$jsRoundTripVoid() throws(JSException) -> Void { + bjs_jsRoundTripVoid() + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripNumber") +fileprivate func bjs_jsRoundTripNumber_extern(_ v: Float64) -> Float64 +#else +fileprivate func bjs_jsRoundTripNumber_extern(_ v: Float64) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripNumber(_ v: Float64) -> Float64 { + return bjs_jsRoundTripNumber_extern(v) +} + +func _$jsRoundTripNumber(_ v: Double) throws(JSException) -> Double { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripNumber(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripBool") +fileprivate func bjs_jsRoundTripBool_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripBool_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripBool(_ v: Int32) -> Int32 { + return bjs_jsRoundTripBool_extern(v) +} + +func _$jsRoundTripBool(_ v: Bool) throws(JSException) -> Bool { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripBool(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripString") +fileprivate func bjs_jsRoundTripString_extern(_ v: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripString_extern(_ v: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripString(_ v: Int32) -> Int32 { + return bjs_jsRoundTripString_extern(v) +} + +func _$jsRoundTripString(_ v: String) throws(JSException) -> String { + let vValue = v.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripString(vValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripJSValue") +fileprivate func bjs_jsRoundTripJSValue_extern(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void +#else +fileprivate func bjs_jsRoundTripJSValue_extern(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { + return bjs_jsRoundTripJSValue_extern(vKind, vPayload1, vPayload2) +} + +func _$jsRoundTripJSValue(_ v: JSValue) throws(JSException) -> JSValue { + let (vKind, vPayload1, vPayload2) = v.bridgeJSLowerParameter() + bjs_jsRoundTripJSValue(vKind, vPayload1, vPayload2) + if let error = _swift_js_take_exception() { + throw error + } + return JSValue.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripJSValueArray") +fileprivate func bjs_jsRoundTripJSValueArray_extern() -> Void +#else +fileprivate func bjs_jsRoundTripJSValueArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripJSValueArray() -> Void { + return bjs_jsRoundTripJSValueArray_extern() +} + +func _$jsRoundTripJSValueArray(_ v: [JSValue]) throws(JSException) -> [JSValue] { + let _ = v.bridgeJSLowerParameter() + bjs_jsRoundTripJSValueArray() + if let error = _swift_js_take_exception() { + throw error + } + return [JSValue].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalJSValueArray") +fileprivate func bjs_jsRoundTripOptionalJSValueArray_extern(_ v: Int32) -> Void +#else +fileprivate func bjs_jsRoundTripOptionalJSValueArray_extern(_ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalJSValueArray(_ v: Int32) -> Void { + return bjs_jsRoundTripOptionalJSValueArray_extern(v) +} + +func _$jsRoundTripOptionalJSValueArray(_ v: Optional<[JSValue]>) throws(JSException) -> Optional<[JSValue]> { + let vIsSome = v.bridgeJSLowerParameter() + bjs_jsRoundTripOptionalJSValueArray(vIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional<[JSValue]>.bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrVoid") +fileprivate func bjs_jsThrowOrVoid_extern(_ shouldThrow: Int32) -> Void +#else +fileprivate func bjs_jsThrowOrVoid_extern(_ shouldThrow: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsThrowOrVoid(_ shouldThrow: Int32) -> Void { + return bjs_jsThrowOrVoid_extern(shouldThrow) +} + +func _$jsThrowOrVoid(_ shouldThrow: Bool) throws(JSException) -> Void { + let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() + bjs_jsThrowOrVoid(shouldThrowValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrNumber") +fileprivate func bjs_jsThrowOrNumber_extern(_ shouldThrow: Int32) -> Float64 +#else +fileprivate func bjs_jsThrowOrNumber_extern(_ shouldThrow: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsThrowOrNumber(_ shouldThrow: Int32) -> Float64 { + return bjs_jsThrowOrNumber_extern(shouldThrow) +} + +func _$jsThrowOrNumber(_ shouldThrow: Bool) throws(JSException) -> Double { + let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() + let ret = bjs_jsThrowOrNumber(shouldThrowValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrBool") +fileprivate func bjs_jsThrowOrBool_extern(_ shouldThrow: Int32) -> Int32 +#else +fileprivate func bjs_jsThrowOrBool_extern(_ shouldThrow: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsThrowOrBool(_ shouldThrow: Int32) -> Int32 { + return bjs_jsThrowOrBool_extern(shouldThrow) +} + +func _$jsThrowOrBool(_ shouldThrow: Bool) throws(JSException) -> Bool { + let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() + let ret = bjs_jsThrowOrBool(shouldThrowValue) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrString") +fileprivate func bjs_jsThrowOrString_extern(_ shouldThrow: Int32) -> Int32 +#else +fileprivate func bjs_jsThrowOrString_extern(_ shouldThrow: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsThrowOrString(_ shouldThrow: Int32) -> Int32 { + return bjs_jsThrowOrString_extern(shouldThrow) +} + +func _$jsThrowOrString(_ shouldThrow: Bool) throws(JSException) -> String { + let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() + let ret = bjs_jsThrowOrString(shouldThrowValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripFeatureFlag") +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flag: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripFeatureFlag_extern(_ flag: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripFeatureFlag(_ flag: Int32) -> Int32 { + return bjs_jsRoundTripFeatureFlag_extern(flag) +} + +func _$jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> FeatureFlag { + let flagValue = flag.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripFeatureFlag(flagValue) + if let error = _swift_js_take_exception() { + throw error + } + return FeatureFlag.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runAsyncWorks") +fileprivate func bjs_runAsyncWorks_extern() -> Int32 +#else +fileprivate func bjs_runAsyncWorks_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_runAsyncWorks() -> Int32 { + return bjs_runAsyncWorks_extern() +} + +func _$runAsyncWorks() throws(JSException) -> JSPromise { + let ret = bjs_runAsyncWorks() + if let error = _swift_js_take_exception() { + throw error + } + return JSPromise.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__jsWeirdFunction") +fileprivate func bjs__jsWeirdFunction_extern() -> Float64 +#else +fileprivate func bjs__jsWeirdFunction_extern() -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs__jsWeirdFunction() -> Float64 { + return bjs__jsWeirdFunction_extern() +} + +func _$_jsWeirdFunction() throws(JSException) -> Double { + let ret = bjs__jsWeirdFunction() + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripNumberArray") +fileprivate func bjs_jsRoundTripNumberArray_extern() -> Void +#else +fileprivate func bjs_jsRoundTripNumberArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripNumberArray() -> Void { + return bjs_jsRoundTripNumberArray_extern() +} + +func _$jsRoundTripNumberArray(_ values: [Double]) throws(JSException) -> [Double] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripNumberArray() + if let error = _swift_js_take_exception() { + throw error + } + return [Double].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripStringArray") +fileprivate func bjs_jsRoundTripStringArray_extern() -> Void +#else +fileprivate func bjs_jsRoundTripStringArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripStringArray() -> Void { + return bjs_jsRoundTripStringArray_extern() +} + +func _$jsRoundTripStringArray(_ values: [String]) throws(JSException) -> [String] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripStringArray() + if let error = _swift_js_take_exception() { + throw error + } + return [String].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripBoolArray") +fileprivate func bjs_jsRoundTripBoolArray_extern() -> Void +#else +fileprivate func bjs_jsRoundTripBoolArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripBoolArray() -> Void { + return bjs_jsRoundTripBoolArray_extern() +} + +func _$jsRoundTripBoolArray(_ values: [Bool]) throws(JSException) -> [Bool] { + let _ = values.bridgeJSLowerParameter() + bjs_jsRoundTripBoolArray() + if let error = _swift_js_take_exception() { + throw error + } + return [Bool].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsSumNumberArray") +fileprivate func bjs_jsSumNumberArray_extern() -> Float64 +#else +fileprivate func bjs_jsSumNumberArray_extern() -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsSumNumberArray() -> Float64 { + return bjs_jsSumNumberArray_extern() +} + +func _$jsSumNumberArray(_ values: [Double]) throws(JSException) -> Double { + let _ = values.bridgeJSLowerParameter() + let ret = bjs_jsSumNumberArray() + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsCreateNumberArray") +fileprivate func bjs_jsCreateNumberArray_extern() -> Void +#else +fileprivate func bjs_jsCreateNumberArray_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsCreateNumberArray() -> Void { + return bjs_jsCreateNumberArray_extern() +} + +func _$jsCreateNumberArray() throws(JSException) -> [Double] { + bjs_jsCreateNumberArray() + if let error = _swift_js_take_exception() { + throw error + } + return [Double].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_parseInt") +fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 +#else +fileprivate func bjs_parseInt_extern(_ string: Int32) -> Float64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { + return bjs_parseInt_extern(string) +} + +func _$parseInt(_ string: String) throws(JSException) -> Double { + let stringValue = string.bridgeJSLowerParameter() + let ret = bjs_parseInt(stringValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_init") +fileprivate func bjs_JsGreeter_init_extern(_ name: Int32, _ prefix: Int32) -> Int32 +#else +fileprivate func bjs_JsGreeter_init_extern(_ name: Int32, _ prefix: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_init(_ name: Int32, _ prefix: Int32) -> Int32 { + return bjs_JsGreeter_init_extern(name, prefix) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_get") +fileprivate func bjs_JsGreeter_name_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_JsGreeter_name_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_name_get(_ self: Int32) -> Int32 { + return bjs_JsGreeter_name_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_prefix_get") +fileprivate func bjs_JsGreeter_prefix_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_JsGreeter_prefix_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_prefix_get(_ self: Int32) -> Int32 { + return bjs_JsGreeter_prefix_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_set") +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_JsGreeter_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_JsGreeter_name_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_greet") +fileprivate func bjs_JsGreeter_greet_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_JsGreeter_greet_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_greet(_ self: Int32) -> Int32 { + return bjs_JsGreeter_greet_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_changeName") +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void +#else +fileprivate func bjs_JsGreeter_changeName_extern(_ self: Int32, _ name: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ name: Int32) -> Void { + return bjs_JsGreeter_changeName_extern(self, name) +} + +func _$JsGreeter_init(_ name: String, _ prefix: String) throws(JSException) -> JSObject { + let nameValue = name.bridgeJSLowerParameter() + let prefixValue = prefix.bridgeJSLowerParameter() + let ret = bjs_JsGreeter_init(nameValue, prefixValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$JsGreeter_name_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_JsGreeter_name_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$JsGreeter_prefix_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_JsGreeter_prefix_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$JsGreeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_JsGreeter_name_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_JsGreeter_greet(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let nameValue = name.bridgeJSLowerParameter() + bjs_JsGreeter_changeName(selfValue, nameValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__WeirdClass_init") +fileprivate func bjs__WeirdClass_init_extern() -> Int32 +#else +fileprivate func bjs__WeirdClass_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs__WeirdClass_init() -> Int32 { + return bjs__WeirdClass_init_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__WeirdClass_method_with_dashes") +fileprivate func bjs__WeirdClass_method_with_dashes_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs__WeirdClass_method_with_dashes_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs__WeirdClass_method_with_dashes(_ self: Int32) -> Int32 { + return bjs__WeirdClass_method_with_dashes_extern(self) +} + +func _$_WeirdClass_init() throws(JSException) -> JSObject { + let ret = bjs__WeirdClass_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$_WeirdClass_method_with_dashes(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs__WeirdClass_method_with_dashes(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_init") +fileprivate func bjs_StaticBox_init_extern(_ value: Float64) -> Int32 #else -fileprivate func _bjs_TextProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_StaticBox_init_extern(_ value: Float64) -> Int32 { fatalError("Only available on WebAssembly") } #endif - -@_expose(wasm, "bjs_Container_init") -@_cdecl("bjs_Container_init") -public func _bjs_Container_init(_ config: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let _tmp_config = Optional.bridgeJSLiftParameter(config) - let _tmp_location = DataPoint.bridgeJSLiftParameter() - let ret = Container(location: _tmp_location, config: _tmp_config) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Container_location_get") -@_cdecl("bjs_Container_location_get") -public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).location - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_Container_location_set") -@_cdecl("bjs_Container_location_set") -public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).location = DataPoint.bridgeJSLiftParameter() - #else - fatalError("Only available on WebAssembly") - #endif +@inline(never) fileprivate func bjs_StaticBox_init(_ value: Float64) -> Int32 { + return bjs_StaticBox_init_extern(value) } -@_expose(wasm, "bjs_Container_config_get") -@_cdecl("bjs_Container_config_get") -public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).config - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_create_static") +fileprivate func bjs_StaticBox_create_static_extern(_ value: Float64) -> Int32 +#else +fileprivate func bjs_StaticBox_create_static_extern(_ value: Float64) -> Int32 { fatalError("Only available on WebAssembly") - #endif } - -@_expose(wasm, "bjs_Container_config_set") -@_cdecl("bjs_Container_config_set") -public func _bjs_Container_config_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).config = Optional.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif +#endif +@inline(never) fileprivate func bjs_StaticBox_create_static(_ value: Float64) -> Int32 { + return bjs_StaticBox_create_static_extern(value) } -@_expose(wasm, "bjs_Container_deinit") -@_cdecl("bjs_Container_deinit") -public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_value_static") +fileprivate func bjs_StaticBox_value_static_extern() -> Float64 +#else +fileprivate func bjs_StaticBox_value_static_extern() -> Float64 { fatalError("Only available on WebAssembly") - #endif } - -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) - } +#endif +@inline(never) fileprivate func bjs_StaticBox_value_static() -> Float64 { + return bjs_StaticBox_value_static_extern() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") -fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_makeDefault_static") +fileprivate func bjs_StaticBox_makeDefault_static_extern() -> Int32 #else -fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_StaticBox_makeDefault_static_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_StaticBox_makeDefault_static() -> Int32 { + return bjs_StaticBox_makeDefault_static_extern() +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_init") -fileprivate func bjs_Foo_init(_ value: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_with_dashes_static") +fileprivate func bjs_StaticBox_with_dashes_static_extern() -> Int32 #else -fileprivate func bjs_Foo_init(_ value: Int32) -> Int32 { +fileprivate func bjs_StaticBox_with_dashes_static_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_StaticBox_with_dashes_static() -> Int32 { + return bjs_StaticBox_with_dashes_static_extern() +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Foo_value_get") -fileprivate func bjs_Foo_value_get(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticBox_value") +fileprivate func bjs_StaticBox_value_extern(_ self: Int32) -> Float64 #else -fileprivate func bjs_Foo_value_get(_ self: Int32) -> Int32 { +fileprivate func bjs_StaticBox_value_extern(_ self: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_StaticBox_value(_ self: Int32) -> Float64 { + return bjs_StaticBox_value_extern(self) +} -func _$Foo_init(_ value: String) throws(JSException) -> JSObject { +func _$StaticBox_init(_ value: Double) throws(JSException) -> JSObject { let valueValue = value.bridgeJSLowerParameter() - let ret = bjs_Foo_init(valueValue) + let ret = bjs_StaticBox_init(valueValue) if let error = _swift_js_take_exception() { throw error } return JSObject.bridgeJSLiftReturn(ret) } -func _$Foo_value_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Foo_value_get(selfValue) +func _$StaticBox_create(_ value: Double) throws(JSException) -> StaticBox { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_StaticBox_create_static(valueValue) if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) + return StaticBox.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_globalObject1_get") -fileprivate func bjs_globalObject1_get() -> Int32 -#else -fileprivate func bjs_globalObject1_get() -> Int32 { - fatalError("Only available on WebAssembly") +func _$StaticBox_value() throws(JSException) -> Double { + let ret = bjs_StaticBox_value_static() + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) } -#endif -func _$globalObject1_get() throws(JSException) -> JSObject { - let ret = bjs_globalObject1_get() +func _$StaticBox_makeDefault() throws(JSException) -> StaticBox { + let ret = bjs_StaticBox_makeDefault_static() if let error = _swift_js_take_exception() { throw error } - return JSObject.bridgeJSLiftReturn(ret) + return StaticBox.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripVoid") -fileprivate func bjs_jsRoundTripVoid() -> Void -#else -fileprivate func bjs_jsRoundTripVoid() -> Void { - fatalError("Only available on WebAssembly") +func _$StaticBox_with_dashes() throws(JSException) -> StaticBox { + let ret = bjs_StaticBox_with_dashes_static() + if let error = _swift_js_take_exception() { + throw error + } + return StaticBox.bridgeJSLiftReturn(ret) } -#endif -func _$jsRoundTripVoid() throws(JSException) -> Void { - bjs_jsRoundTripVoid() +func _$StaticBox_value(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_StaticBox_value(selfValue) if let error = _swift_js_take_exception() { throw error } + return Double.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripNumber") -fileprivate func bjs_jsRoundTripNumber(_ v: Float64) -> Float64 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_init") +fileprivate func bjs_Animal_init_extern(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 #else -fileprivate func bjs_jsRoundTripNumber(_ v: Float64) -> Float64 { +fileprivate func bjs_Animal_init_extern(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_Animal_init(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { + return bjs_Animal_init_extern(name, age, isCat) +} -func _$jsRoundTripNumber(_ v: Double) throws(JSException) -> Double { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripNumber(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_get") +fileprivate func bjs_Animal_name_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Animal_name_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animal_name_get(_ self: Int32) -> Int32 { + return bjs_Animal_name_get_extern(self) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripBool") -fileprivate func bjs_jsRoundTripBool(_ v: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_age_get") +fileprivate func bjs_Animal_age_get_extern(_ self: Int32) -> Float64 #else -fileprivate func bjs_jsRoundTripBool(_ v: Int32) -> Int32 { +fileprivate func bjs_Animal_age_get_extern(_ self: Int32) -> Float64 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_Animal_age_get(_ self: Int32) -> Float64 { + return bjs_Animal_age_get_extern(self) +} -func _$jsRoundTripBool(_ v: Bool) throws(JSException) -> Bool { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripBool(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_isCat_get") +fileprivate func bjs_Animal_isCat_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Animal_isCat_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animal_isCat_get(_ self: Int32) -> Int32 { + return bjs_Animal_isCat_get_extern(self) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripString") -fileprivate func bjs_jsRoundTripString(_ v: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_set") +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void #else -fileprivate func bjs_jsRoundTripString(_ v: Int32) -> Int32 { +fileprivate func bjs_Animal_name_set_extern(_ self: Int32, _ newValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_Animal_name_set_extern(self, newValue) +} -func _$jsRoundTripString(_ v: String) throws(JSException) -> String { - let vValue = v.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripString(vValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_age_set") +fileprivate func bjs_Animal_age_set_extern(_ self: Int32, _ newValue: Float64) -> Void +#else +fileprivate func bjs_Animal_age_set_extern(_ self: Int32, _ newValue: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animal_age_set(_ self: Int32, _ newValue: Float64) -> Void { + return bjs_Animal_age_set_extern(self, newValue) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrVoid") -fileprivate func bjs_jsThrowOrVoid(_ shouldThrow: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_isCat_set") +fileprivate func bjs_Animal_isCat_set_extern(_ self: Int32, _ newValue: Int32) -> Void #else -fileprivate func bjs_jsThrowOrVoid(_ shouldThrow: Int32) -> Void { +fileprivate func bjs_Animal_isCat_set_extern(_ self: Int32, _ newValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_Animal_isCat_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_Animal_isCat_set_extern(self, newValue) +} -func _$jsThrowOrVoid(_ shouldThrow: Bool) throws(JSException) -> Void { - let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() - bjs_jsThrowOrVoid(shouldThrowValue) - if let error = _swift_js_take_exception() { - throw error - } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_bark") +fileprivate func bjs_Animal_bark_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Animal_bark_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Animal_bark(_ self: Int32) -> Int32 { + return bjs_Animal_bark_extern(self) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrNumber") -fileprivate func bjs_jsThrowOrNumber(_ shouldThrow: Int32) -> Float64 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_getIsCat") +fileprivate func bjs_Animal_getIsCat_extern(_ self: Int32) -> Int32 #else -fileprivate func bjs_jsThrowOrNumber(_ shouldThrow: Int32) -> Float64 { +fileprivate func bjs_Animal_getIsCat_extern(_ self: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_Animal_getIsCat(_ self: Int32) -> Int32 { + return bjs_Animal_getIsCat_extern(self) +} -func _$jsThrowOrNumber(_ shouldThrow: Bool) throws(JSException) -> Double { - let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() - let ret = bjs_jsThrowOrNumber(shouldThrowValue) +func _$Animal_init(_ name: String, _ age: Double, _ isCat: Bool) throws(JSException) -> JSObject { + let nameValue = name.bridgeJSLowerParameter() + let ageValue = age.bridgeJSLowerParameter() + let isCatValue = isCat.bridgeJSLowerParameter() + let ret = bjs_Animal_init(nameValue, ageValue, isCatValue) if let error = _swift_js_take_exception() { throw error } - return Double.bridgeJSLiftReturn(ret) + return JSObject.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrBool") -fileprivate func bjs_jsThrowOrBool(_ shouldThrow: Int32) -> Int32 -#else -fileprivate func bjs_jsThrowOrBool(_ shouldThrow: Int32) -> Int32 { - fatalError("Only available on WebAssembly") +func _$Animal_name_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Animal_name_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) } -#endif -func _$jsThrowOrBool(_ shouldThrow: Bool) throws(JSException) -> Bool { - let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() - let ret = bjs_jsThrowOrBool(shouldThrowValue) +func _$Animal_age_get(_ self: JSObject) throws(JSException) -> Double { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Animal_age_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Double.bridgeJSLiftReturn(ret) +} + +func _$Animal_isCat_get(_ self: JSObject) throws(JSException) -> Bool { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Animal_isCat_get(selfValue) if let error = _swift_js_take_exception() { throw error } return Bool.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsThrowOrString") -fileprivate func bjs_jsThrowOrString(_ shouldThrow: Int32) -> Int32 -#else -fileprivate func bjs_jsThrowOrString(_ shouldThrow: Int32) -> Int32 { - fatalError("Only available on WebAssembly") +func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_Animal_name_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } } -#endif -func _$jsThrowOrString(_ shouldThrow: Bool) throws(JSException) -> String { - let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() - let ret = bjs_jsThrowOrString(shouldThrowValue) +func _$Animal_age_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_Animal_age_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$Animal_isCat_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_Animal_isCat_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$Animal_bark(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Animal_bark(selfValue) if let error = _swift_js_take_exception() { throw error } return String.bridgeJSLiftReturn(ret) } +func _$Animal_getIsCat(_ self: JSObject) throws(JSException) -> Bool { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Animal_getIsCat(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripFeatureFlag") -fileprivate func bjs_jsRoundTripFeatureFlag(_ flag: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripIntArray") +fileprivate func bjs_jsRoundTripIntArray_extern() -> Void #else -fileprivate func bjs_jsRoundTripFeatureFlag(_ flag: Int32) -> Int32 { +fileprivate func bjs_jsRoundTripIntArray_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsRoundTripIntArray() -> Void { + return bjs_jsRoundTripIntArray_extern() +} -func _$jsRoundTripFeatureFlag(_ flag: FeatureFlag) throws(JSException) -> FeatureFlag { - let flagValue = flag.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripFeatureFlag(flagValue) +func _$jsRoundTripIntArray(_ items: [Int]) throws(JSException) -> [Int] { + let _ = items.bridgeJSLowerParameter() + bjs_jsRoundTripIntArray() if let error = _swift_js_take_exception() { throw error } - return FeatureFlag.bridgeJSLiftReturn(ret) + return [Int].bridgeJSLiftReturn() } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runAsyncWorks") -fileprivate func bjs_runAsyncWorks() -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsArrayLength") +fileprivate func bjs_jsArrayLength_extern() -> Int32 #else -fileprivate func bjs_runAsyncWorks() -> Int32 { +fileprivate func bjs_jsArrayLength_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsArrayLength() -> Int32 { + return bjs_jsArrayLength_extern() +} -func _$runAsyncWorks() throws(JSException) -> JSPromise { - let ret = bjs_runAsyncWorks() +func _$jsArrayLength(_ items: [Int]) throws(JSException) -> Int { + let _ = items.bridgeJSLowerParameter() + let ret = bjs_jsArrayLength() if let error = _swift_js_take_exception() { throw error } - return JSPromise.bridgeJSLiftReturn(ret) + return Int.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__jsWeirdFunction") -fileprivate func bjs__jsWeirdFunction() -> Float64 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_makeArrayHost") +fileprivate func bjs_makeArrayHost_extern() -> Int32 #else -fileprivate func bjs__jsWeirdFunction() -> Float64 { +fileprivate func bjs_makeArrayHost_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_makeArrayHost() -> Int32 { + return bjs_makeArrayHost_extern() +} -func _$_jsWeirdFunction() throws(JSException) -> Double { - let ret = bjs__jsWeirdFunction() +func _$makeArrayHost(_ numbers: [Int], _ labels: [String]) throws(JSException) -> ArrayHost { + let _ = labels.bridgeJSLowerParameter() + let _ = numbers.bridgeJSLowerParameter() + let ret = bjs_makeArrayHost() if let error = _swift_js_take_exception() { throw error } - return Double.bridgeJSLiftReturn(ret) + return ArrayHost.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_parseInt") -fileprivate func bjs_parseInt(_ string: Int32) -> Float64 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_init") +fileprivate func bjs_ArrayHost_init_extern() -> Int32 #else -fileprivate func bjs_parseInt(_ string: Int32) -> Float64 { +fileprivate func bjs_ArrayHost_init_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_init() -> Int32 { + return bjs_ArrayHost_init_extern() +} -func _$parseInt(_ string: String) throws(JSException) -> Double { - let stringValue = string.bridgeJSLowerParameter() - let ret = bjs_parseInt(stringValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_numbers_get") +fileprivate func bjs_ArrayHost_numbers_get_extern(_ self: Int32) -> Void +#else +fileprivate func bjs_ArrayHost_numbers_get_extern(_ self: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ArrayHost_numbers_get(_ self: Int32) -> Void { + return bjs_ArrayHost_numbers_get_extern(self) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_init") -fileprivate func bjs_JsGreeter_init(_ name: Int32, _ prefix: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_labels_get") +fileprivate func bjs_ArrayHost_labels_get_extern(_ self: Int32) -> Void #else -fileprivate func bjs_JsGreeter_init(_ name: Int32, _ prefix: Int32) -> Int32 { +fileprivate func bjs_ArrayHost_labels_get_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_labels_get(_ self: Int32) -> Void { + return bjs_ArrayHost_labels_get_extern(self) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_get") -fileprivate func bjs_JsGreeter_name_get(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_numbers_set") +fileprivate func bjs_ArrayHost_numbers_set_extern(_ self: Int32) -> Void #else -fileprivate func bjs_JsGreeter_name_get(_ self: Int32) -> Int32 { +fileprivate func bjs_ArrayHost_numbers_set_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_numbers_set(_ self: Int32) -> Void { + return bjs_ArrayHost_numbers_set_extern(self) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_prefix_get") -fileprivate func bjs_JsGreeter_prefix_get(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_labels_set") +fileprivate func bjs_ArrayHost_labels_set_extern(_ self: Int32) -> Void #else -fileprivate func bjs_JsGreeter_prefix_get(_ self: Int32) -> Int32 { +fileprivate func bjs_ArrayHost_labels_set_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_labels_set(_ self: Int32) -> Void { + return bjs_ArrayHost_labels_set_extern(self) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_name_set") -fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValue: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_concatNumbers") +fileprivate func bjs_ArrayHost_concatNumbers_extern(_ self: Int32) -> Void #else -fileprivate func bjs_JsGreeter_name_set(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_ArrayHost_concatNumbers_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_concatNumbers(_ self: Int32) -> Void { + return bjs_ArrayHost_concatNumbers_extern(self) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_greet") -fileprivate func bjs_JsGreeter_greet(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_concatLabels") +fileprivate func bjs_ArrayHost_concatLabels_extern(_ self: Int32) -> Void #else -fileprivate func bjs_JsGreeter_greet(_ self: Int32) -> Int32 { +fileprivate func bjs_ArrayHost_concatLabels_extern(_ self: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_concatLabels(_ self: Int32) -> Void { + return bjs_ArrayHost_concatLabels_extern(self) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JsGreeter_changeName") -fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ name: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayHost_firstLabel") +fileprivate func bjs_ArrayHost_firstLabel_extern(_ self: Int32) -> Int32 #else -fileprivate func bjs_JsGreeter_changeName(_ self: Int32, _ name: Int32) -> Void { +fileprivate func bjs_ArrayHost_firstLabel_extern(_ self: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_ArrayHost_firstLabel(_ self: Int32) -> Int32 { + return bjs_ArrayHost_firstLabel_extern(self) +} -func _$JsGreeter_init(_ name: String, _ prefix: String) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let prefixValue = prefix.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_init(nameValue, prefixValue) +func _$ArrayHost_init(_ numbers: [Int], _ labels: [String]) throws(JSException) -> JSObject { + let _ = labels.bridgeJSLowerParameter() + let _ = numbers.bridgeJSLowerParameter() + let ret = bjs_ArrayHost_init() if let error = _swift_js_take_exception() { throw error } return JSObject.bridgeJSLiftReturn(ret) } -func _$JsGreeter_name_get(_ self: JSObject) throws(JSException) -> String { +func _$ArrayHost_numbers_get(_ self: JSObject) throws(JSException) -> [Int] { let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_name_get(selfValue) + bjs_ArrayHost_numbers_get(selfValue) if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) + return [Int].bridgeJSLiftReturn() } -func _$JsGreeter_prefix_get(_ self: JSObject) throws(JSException) -> String { +func _$ArrayHost_labels_get(_ self: JSObject) throws(JSException) -> [String] { let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_prefix_get(selfValue) + bjs_ArrayHost_labels_get(selfValue) if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) + return [String].bridgeJSLiftReturn() } -func _$JsGreeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { +func _$ArrayHost_numbers_set(_ self: JSObject, _ newValue: [Int]) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_JsGreeter_name_set(selfValue, newValueValue) + let _ = newValue.bridgeJSLowerParameter() + bjs_ArrayHost_numbers_set(selfValue) if let error = _swift_js_take_exception() { throw error } } -func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { +func _$ArrayHost_labels_set(_ self: JSObject, _ newValue: [String]) throws(JSException) -> Void { let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_JsGreeter_greet(selfValue) + let _ = newValue.bridgeJSLowerParameter() + bjs_ArrayHost_labels_set(selfValue) if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) } -func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { +func _$ArrayHost_concatNumbers(_ self: JSObject, _ values: [Int]) throws(JSException) -> [Int] { let selfValue = self.bridgeJSLowerParameter() - let nameValue = name.bridgeJSLowerParameter() - bjs_JsGreeter_changeName(selfValue, nameValue) + let _ = values.bridgeJSLowerParameter() + bjs_ArrayHost_concatNumbers(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return [Int].bridgeJSLiftReturn() +} + +func _$ArrayHost_concatLabels(_ self: JSObject, _ values: [String]) throws(JSException) -> [String] { + let selfValue = self.bridgeJSLowerParameter() + let _ = values.bridgeJSLowerParameter() + bjs_ArrayHost_concatLabels(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return [String].bridgeJSLiftReturn() +} + +func _$ArrayHost_firstLabel(_ self: JSObject, _ values: [String]) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let _ = values.bridgeJSLowerParameter() + let ret = bjs_ArrayHost_firstLabel(selfValue) if let error = _swift_js_take_exception() { throw error } + return String.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__WeirdClass_init") -fileprivate func bjs__WeirdClass_init() -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") +fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 #else -fileprivate func bjs__WeirdClass_init() -> Int32 { +fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsTranslatePoint(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { + return bjs_jsTranslatePoint_extern(point, dx, dy) +} + +func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { + let pointObjectId = point.bridgeJSLowerParameter() + let dxValue = dx.bridgeJSLowerParameter() + let dyValue = dy.bridgeJSLowerParameter() + let ret = bjs_jsTranslatePoint(pointObjectId, dxValue, dyValue) + if let error = _swift_js_take_exception() { + throw error + } + return Point.bridgeJSLiftReturn(ret) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs__WeirdClass_method_with_dashes") -fileprivate func bjs__WeirdClass_method_with_dashes(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MyJSClassInternal_init") +fileprivate func bjs_MyJSClassInternal_init_extern() -> Int32 #else -fileprivate func bjs__WeirdClass_method_with_dashes(_ self: Int32) -> Int32 { +fileprivate func bjs_MyJSClassInternal_init_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_MyJSClassInternal_init() -> Int32 { + return bjs_MyJSClassInternal_init_extern() +} -func _$_WeirdClass_init() throws(JSException) -> JSObject { - let ret = bjs__WeirdClass_init() +func _$MyJSClassInternal_init() throws(JSException) -> JSObject { + let ret = bjs_MyJSClassInternal_init() if let error = _swift_js_take_exception() { throw error } return JSObject.bridgeJSLiftReturn(ret) } -func _$_WeirdClass_method_with_dashes(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs__WeirdClass_method_with_dashes(selfValue) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MyJSClassPublic_init") +fileprivate func bjs_MyJSClassPublic_init_extern() -> Int32 +#else +fileprivate func bjs_MyJSClassPublic_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_MyJSClassPublic_init() -> Int32 { + return bjs_MyJSClassPublic_init_extern() +} + +func _$MyJSClassPublic_init() throws(JSException) -> JSObject { + let ret = bjs_MyJSClassPublic_init() if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) + return JSObject.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_init") -fileprivate func bjs_Animal_init(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MyJSClassPackage_init") +fileprivate func bjs_MyJSClassPackage_init_extern() -> Int32 #else -fileprivate func bjs_Animal_init(_ name: Int32, _ age: Float64, _ isCat: Int32) -> Int32 { +fileprivate func bjs_MyJSClassPackage_init_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_MyJSClassPackage_init() -> Int32 { + return bjs_MyJSClassPackage_init_extern() +} + +func _$MyJSClassPackage_init() throws(JSException) -> JSObject { + let ret = bjs_MyJSClassPackage_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_get") -fileprivate func bjs_Animal_name_get(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsFunctionWithPackageAccess") +fileprivate func bjs_jsFunctionWithPackageAccess_extern() -> Void #else -fileprivate func bjs_Animal_name_get(_ self: Int32) -> Int32 { +fileprivate func bjs_jsFunctionWithPackageAccess_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsFunctionWithPackageAccess() -> Void { + return bjs_jsFunctionWithPackageAccess_extern() +} + +func _$jsFunctionWithPackageAccess() throws(JSException) -> Void { + bjs_jsFunctionWithPackageAccess() + if let error = _swift_js_take_exception() { + throw error + } +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_age_get") -fileprivate func bjs_Animal_age_get(_ self: Int32) -> Float64 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsFunctionWithPublicAccess") +fileprivate func bjs_jsFunctionWithPublicAccess_extern() -> Void #else -fileprivate func bjs_Animal_age_get(_ self: Int32) -> Float64 { +fileprivate func bjs_jsFunctionWithPublicAccess_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsFunctionWithPublicAccess() -> Void { + return bjs_jsFunctionWithPublicAccess_extern() +} + +func _$jsFunctionWithPublicAccess() throws(JSException) -> Void { + bjs_jsFunctionWithPublicAccess() + if let error = _swift_js_take_exception() { + throw error + } +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_isCat_get") -fileprivate func bjs_Animal_isCat_get(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsFunctionWithInternalAccess") +fileprivate func bjs_jsFunctionWithInternalAccess_extern() -> Void #else -fileprivate func bjs_Animal_isCat_get(_ self: Int32) -> Int32 { +fileprivate func bjs_jsFunctionWithInternalAccess_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsFunctionWithInternalAccess() -> Void { + return bjs_jsFunctionWithInternalAccess_extern() +} + +func _$jsFunctionWithInternalAccess() throws(JSException) -> Void { + bjs_jsFunctionWithInternalAccess() + if let error = _swift_js_take_exception() { + throw error + } +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_name_set") -fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValue: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsFunctionWithFilePrivateAccess") +fileprivate func bjs_jsFunctionWithFilePrivateAccess_extern() -> Void #else -fileprivate func bjs_Animal_name_set(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_jsFunctionWithFilePrivateAccess_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsFunctionWithFilePrivateAccess() -> Void { + return bjs_jsFunctionWithFilePrivateAccess_extern() +} + +func _$jsFunctionWithFilePrivateAccess() throws(JSException) -> Void { + bjs_jsFunctionWithFilePrivateAccess() + if let error = _swift_js_take_exception() { + throw error + } +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_age_set") -fileprivate func bjs_Animal_age_set(_ self: Int32, _ newValue: Float64) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsFunctionWithPrivateAccess") +fileprivate func bjs_jsFunctionWithPrivateAccess_extern() -> Void #else -fileprivate func bjs_Animal_age_set(_ self: Int32, _ newValue: Float64) -> Void { +fileprivate func bjs_jsFunctionWithPrivateAccess_extern() -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_jsFunctionWithPrivateAccess() -> Void { + return bjs_jsFunctionWithPrivateAccess_extern() +} + +func _$jsFunctionWithPrivateAccess() throws(JSException) -> Void { + bjs_jsFunctionWithPrivateAccess() + if let error = _swift_js_take_exception() { + throw error + } +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_isCat_set") -fileprivate func bjs_Animal_isCat_set(_ self: Int32, _ newValue: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void #else -fileprivate func bjs_Animal_isCat_set(_ self: Int32, _ newValue: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static_extern(valueIsSome, valueValue) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_bark") -fileprivate func bjs_Animal_bark(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void #else -fileprivate func bjs_Animal_bark(_ self: Int32) -> Int32 { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static_extern(valueIsSome, valueValue) +} #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Animal_getIsCat") -fileprivate func bjs_Animal_getIsCat(_ self: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void #else -fileprivate func bjs_Animal_getIsCat(_ self: Int32) -> Int32 { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif - -func _$Animal_init(_ name: String, _ age: Double, _ isCat: Bool) throws(JSException) -> JSObject { - let nameValue = name.bridgeJSLowerParameter() - let ageValue = age.bridgeJSLowerParameter() - let isCatValue = isCat.bridgeJSLowerParameter() - let ret = bjs_Animal_init(nameValue, ageValue, isCatValue) - if let error = _swift_js_take_exception() { - throw error - } - return JSObject.bridgeJSLiftReturn(ret) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static_extern(nameIsSome, nameValue) } -func _$Animal_name_get(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Animal_name_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return String.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { + fatalError("Only available on WebAssembly") } - -func _$Animal_age_get(_ self: JSObject) throws(JSException) -> Double { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Animal_age_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Double.bridgeJSLiftReturn(ret) +#endif +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(_ nameIsSome: Int32, _ nameValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static_extern(nameIsSome, nameValue) } -func _$Animal_isCat_get(_ self: JSObject) throws(JSException) -> Bool { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Animal_isCat_get(selfValue) - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") +fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void +#else +fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") } - -func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Animal_name_set(selfValue, newValueValue) - if let error = _swift_js_take_exception() { - throw error - } +#endif +@inline(never) fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static() -> Void { + return bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() } -func _$Animal_age_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Animal_age_set(selfValue, newValueValue) +func _$OptionalSupportImports_jsRoundTripOptionalNumberNull(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalNumberNull_static(valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error } + return Optional.bridgeJSLiftReturnFromSideChannel() } -func _$Animal_isCat_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_Animal_isCat_set(selfValue, newValueValue) +func _$OptionalSupportImports_jsRoundTripOptionalNumberUndefined(_ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalNumberUndefined_static(valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error } + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() } -func _$Animal_bark(_ self: JSObject) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Animal_bark(selfValue) +func _$OptionalSupportImports_jsRoundTripOptionalStringNull(_ name: Optional) throws(JSException) -> Optional { + let (nameIsSome, nameValue) = name.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringNull_static(nameIsSome, nameValue) if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) + return Optional.bridgeJSLiftReturnFromSideChannel() } -func _$Animal_getIsCat(_ self: JSObject) throws(JSException) -> Bool { - let selfValue = self.bridgeJSLowerParameter() - let ret = bjs_Animal_getIsCat(selfValue) +func _$OptionalSupportImports_jsRoundTripOptionalStringUndefined(_ name: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { + let (nameIsSome, nameValue) = name.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_static(nameIsSome, nameValue) if let error = _swift_js_take_exception() { throw error } - return Bool.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsApplyInt") -fileprivate func bjs_jsApplyInt(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func bjs_jsApplyInt(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") + return JSUndefinedOr.bridgeJSLiftReturnFromSideChannel() } -#endif -func _$jsApplyInt(_ value: Int, _ transform: @escaping (Int) -> Int) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() - let transformPointer = _BJS_Closure_20BridgeJSRuntimeTestsSi_Si.bridgeJSLower(transform) - let ret = bjs_jsApplyInt(valueValue, transformPointer) +func _$OptionalSupportImports_runJsOptionalSupportTests() throws(JSException) -> Void { + bjs_OptionalSupportImports_runJsOptionalSupportTests_static() if let error = _swift_js_take_exception() { throw error } - return Int.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsMakeAdder") -fileprivate func bjs_jsMakeAdder(_ base: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_gc") +fileprivate func bjs_gc_extern() -> Void #else -fileprivate func bjs_jsMakeAdder(_ base: Int32) -> Int32 { +fileprivate func bjs_gc_extern() -> Void { fatalError("Only available on WebAssembly") } #endif - -func _$jsMakeAdder(_ base: Int) throws(JSException) -> (Int) -> Int { - let baseValue = base.bridgeJSLowerParameter() - let ret = bjs_jsMakeAdder(baseValue) - if let error = _swift_js_take_exception() { - throw error - } - return _BJS_Closure_20BridgeJSRuntimeTestsSi_Si.bridgeJSLift(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsMapString") -fileprivate func bjs_jsMapString(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func bjs_jsMapString(_ value: Int32, _ transform: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") +@inline(never) fileprivate func bjs_gc() -> Void { + return bjs_gc_extern() } -#endif -func _$jsMapString(_ value: String, _ transform: @escaping (String) -> String) throws(JSException) -> String { - let valueValue = value.bridgeJSLowerParameter() - let transformPointer = _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLower(transform) - let ret = bjs_jsMapString(valueValue, transformPointer) +func _$gc() throws(JSException) -> Void { + bjs_gc() if let error = _swift_js_take_exception() { throw error } - return String.bridgeJSLiftReturn(ret) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsMakePrefixer") -fileprivate func bjs_jsMakePrefixer(_ prefix: Int32) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SwiftClassSupportImports_jsRoundTripGreeter_static") +fileprivate func bjs_SwiftClassSupportImports_jsRoundTripGreeter_static_extern(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func bjs_jsMakePrefixer(_ prefix: Int32) -> Int32 { +fileprivate func bjs_SwiftClassSupportImports_jsRoundTripGreeter_static_extern(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif - -func _$jsMakePrefixer(_ prefix: String) throws(JSException) -> (String) -> String { - let prefixValue = prefix.bridgeJSLowerParameter() - let ret = bjs_jsMakePrefixer(prefixValue) - if let error = _swift_js_take_exception() { - throw error - } - return _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(ret) +@inline(never) fileprivate func bjs_SwiftClassSupportImports_jsRoundTripGreeter_static(_ greeter: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return bjs_SwiftClassSupportImports_jsRoundTripGreeter_static_extern(greeter) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsCallTwice") -fileprivate func bjs_jsCallTwice(_ value: Int32, _ callback: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static") +fileprivate func bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static_extern(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func bjs_jsCallTwice(_ value: Int32, _ callback: UnsafeMutableRawPointer) -> Int32 { +fileprivate func bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static_extern(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif +@inline(never) fileprivate func bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static(_ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static_extern(greeterIsSome, greeterPointer) +} -func _$jsCallTwice(_ value: Int, _ callback: @escaping (Int) -> Void) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() - let callbackPointer = _BJS_Closure_20BridgeJSRuntimeTestsSi_y.bridgeJSLower(callback) - let ret = bjs_jsCallTwice(valueValue, callbackPointer) +func _$SwiftClassSupportImports_jsRoundTripGreeter(_ greeter: Greeter) throws(JSException) -> Greeter { + let greeterPointer = greeter.bridgeJSLowerParameter() + let ret = bjs_SwiftClassSupportImports_jsRoundTripGreeter_static(greeterPointer) if let error = _swift_js_take_exception() { throw error } - return Int.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") -fileprivate func bjs_jsTranslatePoint(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 -#else -fileprivate func bjs_jsTranslatePoint(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { - fatalError("Only available on WebAssembly") + return Greeter.bridgeJSLiftReturn(ret) } -#endif -func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { - let pointObjectId = point.bridgeJSLowerParameter() - let dxValue = dx.bridgeJSLowerParameter() - let dyValue = dy.bridgeJSLowerParameter() - let ret = bjs_jsTranslatePoint(pointObjectId, dxValue, dyValue) +func _$SwiftClassSupportImports_jsRoundTripOptionalGreeter(_ greeter: Optional) throws(JSException) -> Optional { + let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() + let ret = bjs_SwiftClassSupportImports_jsRoundTripOptionalGreeter_static(greeterIsSome, greeterPointer) if let error = _swift_js_take_exception() { throw error } - return Point.bridgeJSLiftReturn(ret) + return Optional.bridgeJSLiftReturn(ret) } \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index c79139ea4..45acc8a9c 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -2,134 +2,165 @@ "exported" : { "classes" : [ { - "constructor" : { - "abiName" : "bjs_Greeter_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - - } - } - } - ] - }, - "explicitAccessControl" : "public", "methods" : [ { - "abiName" : "bjs_Greeter_greet", + "abiName" : "bjs_ClosureSupportExports_static_makeIntToInt", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "greet", + "name" : "makeIntToInt", "parameters" : [ + { + "label" : "_", + "name" : "base", + "type" : { + "int" : { + } + } + } ], "returnType" : { - "string" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + } + } + }, + "useJSTypedClosure" : false + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" } } }, { - "abiName" : "bjs_Greeter_changeName", + "abiName" : "bjs_ClosureSupportExports_static_makeDoubleToDouble", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "changeName", + "name" : "makeDoubleToDouble", "parameters" : [ { - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "base", "type" : { - "string" : { + "double" : { } } } ], "returnType" : { - "void" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + } + } + }, + "useJSTypedClosure" : false + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" } } }, { - "abiName" : "bjs_Greeter_greetWith", + "abiName" : "bjs_ClosureSupportExports_static_makeStringToString", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "greetWith", + "name" : "makeStringToString", "parameters" : [ { - "label" : "greeter", - "name" : "greeter", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "label" : "customGreeting", - "name" : "customGreeting", + "label" : "_", + "name" : "prefix", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTests7GreeterC_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - ], - "returnType" : { - "string" : { + "string" : { - } - } - } } } } ], "returnType" : { - "string" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + } + } + }, + "useJSTypedClosure" : false + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" } } }, { - "abiName" : "bjs_Greeter_makeFormatter", + "abiName" : "bjs_ClosureSupportExports_static_makeJSIntToInt", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "makeFormatter", + "name" : "makeJSIntToInt", "parameters" : [ { - "label" : "suffix", - "name" : "suffix", + "label" : "_", + "name" : "base", "type" : { - "string" : { + "int" : { } } @@ -140,38 +171,44 @@ "_0" : { "isAsync" : false, "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "string" : { + "int" : { } } ], "returnType" : { - "string" : { + "int" : { } } - } + }, + "useJSTypedClosure" : true + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" } } }, { - "abiName" : "bjs_Greeter_static_makeCreator", + "abiName" : "bjs_ClosureSupportExports_static_makeJSDoubleToDouble", "effects" : { "isAsync" : false, "isStatic" : true, "isThrows" : false }, - "name" : "makeCreator", + "name" : "makeJSDoubleToDouble", "parameters" : [ { - "label" : "defaultName", - "name" : "defaultName", + "label" : "_", + "name" : "base", "type" : { - "string" : { + "double" : { } } @@ -182,51 +219,60 @@ "_0" : { "isAsync" : false, "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_7GreeterC", + "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "string" : { + "double" : { } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "double" : { + } } - } + }, + "useJSTypedClosure" : true } }, "staticContext" : { "className" : { - "_0" : "Greeter" + "_0" : "ClosureSupportExports" } } }, { - "abiName" : "bjs_Greeter_makeCustomGreeter", + "abiName" : "bjs_ClosureSupportExports_static_makeJSStringToString", "effects" : { "isAsync" : false, - "isStatic" : false, + "isStatic" : true, "isThrows" : false }, - "name" : "makeCustomGreeter", + "name" : "makeJSStringToString", "parameters" : [ + { + "label" : "_", + "name" : "prefix", + "type" : { + "string" : { + } + } + } ], "returnType" : { "closure" : { "_0" : { "isAsync" : false, "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTests7GreeterC_SS", + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "swiftHeapObject" : { - "_0" : "Greeter" + "string" : { + } } ], @@ -235,50 +281,305 @@ } } - } + }, + "useJSTypedClosure" : true + } + }, + "staticContext" : { + "className" : { + "_0" : "ClosureSupportExports" } } } ], - "name" : "Greeter", + "name" : "ClosureSupportExports", "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { - } - } - }, - { - "isReadonly" : true, + ], + "swiftCallName" : "ClosureSupportExports" + }, + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "effects" : { + "isAsync" : false, "isStatic" : false, - "name" : "prefix", - "type" : { - "string" : { + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + } } } - } - ], - "swiftCallName" : "Greeter" - }, - { + ] + }, + "explicitAccessControl" : "public", "methods" : [ { - "abiName" : "bjs_Calculator_square", + "abiName" : "bjs_Greeter_greet", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "square", + "name" : "greet", "parameters" : [ - { - "label" : "value", - "name" : "value", + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_changeName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "changeName", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_greetWith", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greetWith", + "parameters" : [ + { + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "label" : "customGreeting", + "name" : "customGreeting", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests7GreeterC_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Greeter_makeFormatter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeFormatter", + "parameters" : [ + { + "label" : "suffix", + "name" : "suffix", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_Greeter_static_makeCreator", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "makeCreator", + "parameters" : [ + { + "label" : "defaultName", + "name" : "defaultName", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_7GreeterC", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + "useJSTypedClosure" : false + } + }, + "staticContext" : { + "className" : { + "_0" : "Greeter" + } + } + }, + { + "abiName" : "bjs_Greeter_makeCustomGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeCustomGreeter", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests7GreeterC_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + } + ], + "name" : "Greeter", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "prefix", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Greeter" + }, + { + "methods" : [ + { + "abiName" : "bjs_Calculator_square", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "square", + "parameters" : [ + { + "label" : "value", + "name" : "value", "type" : { "int" : { @@ -527,7 +828,7 @@ }, { "constructor" : { - "abiName" : "bjs_OptionalPropertyHolder_init", + "abiName" : "bjs_SimplePropertyHolder_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -535,84 +836,10 @@ }, "parameters" : [ { - "label" : "optionalName", - "name" : "optionalName", + "label" : "value", + "name" : "value", "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "OptionalPropertyHolder", - "properties" : [ - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalName", - "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalAge", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "isReadonly" : false, - "isStatic" : false, - "name" : "optionalGreeter", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } - } - ], - "swiftCallName" : "OptionalPropertyHolder" - }, - { - "constructor" : { - "abiName" : "bjs_SimplePropertyHolder_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "int" : { + "int" : { } } @@ -1057,12 +1284,13 @@ "label" : "tag", "name" : "tag", "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } } @@ -1134,12 +1362,13 @@ "isStatic" : false, "name" : "tag", "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } } @@ -1293,12 +1522,13 @@ } }, "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } }, @@ -1312,12 +1542,13 @@ } }, "type" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -1499,12 +1730,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -1537,12 +1769,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } }, @@ -1559,12 +1792,13 @@ "label" : "_", "name" : "tag", "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } } @@ -1587,12 +1821,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -1609,12 +1844,13 @@ "label" : "_", "name" : "count", "type" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } @@ -1637,12 +1873,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "caseEnum" : { "_0" : "Direction" } - } + }, + "_1" : "null" } } }, @@ -1659,12 +1896,13 @@ "label" : "_", "name" : "direction", "type" : { - "optional" : { + "nullable" : { "_0" : { "caseEnum" : { "_0" : "Direction" } - } + }, + "_1" : "null" } } } @@ -1687,13 +1925,14 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "Theme", "_1" : "String" } - } + }, + "_1" : "null" } } }, @@ -1710,13 +1949,14 @@ "label" : "_", "name" : "theme", "type" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "Theme", "_1" : "String" } - } + }, + "_1" : "null" } } } @@ -1739,13 +1979,14 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "HttpStatus", "_1" : "Int" } - } + }, + "_1" : "null" } } }, @@ -1762,13 +2003,14 @@ "label" : "_", "name" : "status", "type" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "HttpStatus", "_1" : "Int" } - } + }, + "_1" : "null" } } } @@ -1791,12 +2033,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } }, @@ -1813,12 +2056,13 @@ "label" : "_", "name" : "apiResult", "type" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } } @@ -1847,12 +2091,13 @@ "isStatic" : false, "name" : "backupProcessor", "type" : { - "optional" : { + "nullable" : { "_0" : { "swiftProtocol" : { "_0" : "DataProcessor" } - } + }, + "_1" : "null" } } } @@ -2037,12 +2282,13 @@ "label" : "_", "name" : "greeter", "type" : { - "optional" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } } @@ -2065,12 +2311,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } }, @@ -2087,12 +2334,13 @@ "label" : "_", "name" : "result", "type" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } } @@ -2115,12 +2363,13 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } } @@ -2152,12 +2401,13 @@ "isStatic" : false, "name" : "optionalTag", "type" : { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } }, @@ -2166,12 +2416,13 @@ "isStatic" : false, "name" : "optionalCount", "type" : { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } }, @@ -2180,12 +2431,13 @@ "isStatic" : false, "name" : "direction", "type" : { - "optional" : { + "nullable" : { "_0" : { "caseEnum" : { "_0" : "Direction" } - } + }, + "_1" : "null" } } }, @@ -2194,13 +2446,14 @@ "isStatic" : false, "name" : "optionalTheme", "type" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "Theme", "_1" : "String" } - } + }, + "_1" : "null" } } }, @@ -2209,13 +2462,14 @@ "isStatic" : false, "name" : "httpStatus", "type" : { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "HttpStatus", "_1" : "Int" } - } + }, + "_1" : "null" } } }, @@ -2224,12 +2478,13 @@ "isStatic" : false, "name" : "apiResult", "type" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } }, @@ -2248,12 +2503,13 @@ "isStatic" : false, "name" : "optionalHelper", "type" : { - "optional" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } } @@ -2291,7 +2547,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2373,7 +2630,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2414,7 +2672,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2439,12 +2698,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } ], @@ -2453,7 +2713,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2485,12 +2746,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } ], @@ -2499,7 +2761,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2531,12 +2794,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } ], @@ -2545,7 +2809,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2576,12 +2841,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "string" : { } - } + }, + "_1" : "null" } } ], @@ -2590,7 +2856,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2616,15 +2883,17 @@ ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2659,7 +2928,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2702,7 +2972,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2745,7 +3016,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2787,7 +3059,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -2828,7 +3101,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2863,7 +3137,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2898,7 +3173,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2932,7 +3208,8 @@ } } - } + }, + "useJSTypedClosure" : false } } }, @@ -2957,12 +3234,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "caseEnum" : { "_0" : "Direction" } - } + }, + "_1" : "null" } } ], @@ -2971,7 +3249,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -3003,13 +3282,14 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "rawValueEnum" : { "_0" : "Theme", "_1" : "String" } - } + }, + "_1" : "null" } } ], @@ -3018,7 +3298,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -3050,12 +3331,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { "_0" : "APIResult" } - } + }, + "_1" : "null" } } ], @@ -3064,7 +3346,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -3095,12 +3378,13 @@ "moduleName" : "BridgeJSRuntimeTests", "parameters" : [ { - "optional" : { + "nullable" : { "_0" : { "caseEnum" : { "_0" : "Direction" } - } + }, + "_1" : "null" } } ], @@ -3109,7 +3393,8 @@ } } - } + }, + "useJSTypedClosure" : false } } } @@ -3122,7 +3407,7 @@ }, { "constructor" : { - "abiName" : "bjs_Container_init", + "abiName" : "bjs_OptionalHolder_init", "effects" : { "isAsync" : false, "isStatic" : false, @@ -3130,24 +3415,30 @@ }, "parameters" : [ { - "label" : "location", - "name" : "location", + "label" : "nullableGreeter", + "name" : "nullableGreeter", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } }, { - "label" : "config", - "name" : "config", + "label" : "undefinedNumber", + "name" : "undefinedNumber", "type" : { - "optional" : { + "nullable" : { "_0" : { - "swiftStruct" : { - "_0" : "Config" + "double" : { + } - } + }, + "_1" : "undefined" } } } @@ -3156,59 +3447,210 @@ "methods" : [ ], - "name" : "Container", + "name" : "OptionalHolder", "properties" : [ { "isReadonly" : false, "isStatic" : false, - "name" : "location", + "name" : "nullableGreeter", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } }, { "isReadonly" : false, "isStatic" : false, - "name" : "config", + "name" : "undefinedNumber", "type" : { - "optional" : { + "nullable" : { "_0" : { - "swiftStruct" : { - "_0" : "Config" + "double" : { + } - } + }, + "_1" : "undefined" } } } ], - "swiftCallName" : "Container" - } - ], - "enums" : [ + "swiftCallName" : "OptionalHolder" + }, { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "north" + "constructor" : { + "abiName" : "bjs_OptionalPropertyHolder_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false }, + "parameters" : [ + { + "label" : "optionalName", + "name" : "optionalName", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "OptionalPropertyHolder", + "properties" : [ { - "associatedValues" : [ + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalName", + "type" : { + "nullable" : { + "_0" : { + "string" : { - ], - "name" : "south" + } + }, + "_1" : "null" + } + } }, { - "associatedValues" : [ + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalAge", + "type" : { + "nullable" : { + "_0" : { + "int" : { - ], - "name" : "east" + } + }, + "_1" : "null" + } + } }, { - "associatedValues" : [ + "isReadonly" : false, + "isStatic" : false, + "name" : "optionalGreeter", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "OptionalPropertyHolder" + }, + { + "constructor" : { + "abiName" : "bjs_Container_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "location", + "name" : "location", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + }, + { + "label" : "config", + "name" : "config", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Container", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "location", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "config", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Config" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Container" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + }, + { + "associatedValues" : [ + + ], + "name" : "east" + }, + { + "associatedValues" : [ ], "name" : "west" @@ -3500,6 +3942,91 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "StringUtils", + "namespace" : [ + "Utils" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Utils_StringUtils_static_uppercase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "uppercase", + "namespace" : [ + "Utils", + "StringUtils" + ], + "parameters" : [ + { + "label" : "_", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "Utils.StringUtils" + } + } + }, + { + "abiName" : "bjs_Utils_StringUtils_static_lowercase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "lowercase", + "namespace" : [ + "Utils", + "StringUtils" + ], + "parameters" : [ + { + "label" : "_", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "Utils.StringUtils" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Utils.StringUtils", + "tsFullPath" : "Utils.StringUtils" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "Networking", @@ -4157,61 +4684,55 @@ "associatedValues" : [ { "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } + "swiftStruct" : { + "_0" : "Address" } } } ], - "name" : "success" + "name" : "structPayload" }, { "associatedValues" : [ { "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } + "swiftHeapObject" : { + "_0" : "Greeter" } } - }, + } + ], + "name" : "classPayload" + }, + { + "associatedValues" : [ { "type" : { - "optional" : { - "_0" : { - "bool" : { + "jsObject" : { - } - } } } } ], - "name" : "failure" + "name" : "jsObjectPayload" }, { "associatedValues" : [ { "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } + "associatedValueEnum" : { + "_0" : "APIResult" } } - }, + } + ], + "name" : "nestedEnum" + }, + { + "associatedValues" : [ { "type" : { - "optional" : { + "array" : { "_0" : { "int" : { @@ -4219,47 +4740,134 @@ } } } - }, + } + ], + "name" : "arrayPayload" + }, + { + "associatedValues" : [ { "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } + "jsObject" : { + "_0" : "Foo" } } } ], - "name" : "status" + "name" : "jsClassPayload" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" } ], "emitStyle" : "const", - "name" : "APIOptionalResult", + "name" : "AllTypesResult", "staticMethods" : [ ], "staticProperties" : [ ], - "swiftCallName" : "APIOptionalResult", - "tsFullPath" : "APIOptionalResult" + "swiftCallName" : "AllTypesResult", + "tsFullPath" : "AllTypesResult" }, { "cases" : [ { "associatedValues" : [ - + { + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + } ], - "name" : "scientific" + "name" : "precision" }, { "associatedValues" : [ - + { + "type" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } ], - "name" : "basic" - } + "name" : "direction" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optPrecision" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optDirection" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "TypedPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "TypedPayloadResult", + "tsFullPath" : "TypedPayloadResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "scientific" + }, + { + "associatedValues" : [ + + ], + "name" : "basic" + } ], "emitStyle" : "const", "name" : "StaticCalculator", @@ -4356,7 +4964,7 @@ }, "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticUtils.Nested" } } } @@ -4367,6 +4975,94 @@ "swiftCallName" : "StaticUtils.Nested", "tsFullPath" : "StaticUtils.Nested" }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "GraphOperations", + "namespace" : [ + "Services", + "Graph" + ], + "staticMethods" : [ + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_createGraph", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "createGraph", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "rootId", + "name" : "rootId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + }, + { + "abiName" : "bjs_Services_Graph_GraphOperations_static_nodeCount", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "nodeCount", + "namespace" : [ + "Services", + "Graph", + "GraphOperations" + ], + "parameters" : [ + { + "label" : "graphId", + "name" : "graphId", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "GraphOperations" + } + } + } + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GraphOperations", + "tsFullPath" : "Services.Graph.GraphOperations" + }, { "cases" : [ { @@ -4501,7 +5197,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticPropertyNamespace" } }, "type" : { @@ -4519,7 +5215,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticPropertyNamespace" } }, "type" : { @@ -4555,7 +5251,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticPropertyNamespace.NestedProperties" } }, "type" : { @@ -4574,7 +5270,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticPropertyNamespace.NestedProperties" } }, "type" : { @@ -4593,7 +5289,7 @@ ], "staticContext" : { "namespaceEnum" : { - + "_0" : "StaticPropertyNamespace.NestedProperties" } }, "type" : { @@ -4605,114 +5301,341 @@ ], "swiftCallName" : "StaticPropertyNamespace.NestedProperties", "tsFullPath" : "StaticPropertyNamespace.NestedProperties" - } - ], - "exposeToGlobal" : false, - "functions" : [ - { - "abiName" : "bjs_roundTripVoid", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripVoid", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } }, { - "abiName" : "bjs_roundTripInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripInt", - "parameters" : [ + "cases" : [ { - "label" : "v", - "name" : "v", - "type" : { - "int" : { - + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Address" + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "int" : { - - } - } - }, - { - "abiName" : "bjs_roundTripUInt", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripUInt", - "parameters" : [ + ], + "name" : "optStruct" + }, { - "label" : "v", - "name" : "v", - "type" : { - "uint" : { - + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "uint" : { - - } - } - }, - { - "abiName" : "bjs_roundTripFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripFloat", - "parameters" : [ + ], + "name" : "optClass" + }, { - "label" : "v", - "name" : "v", - "type" : { - "float" : { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + } + }, + "_1" : "null" + } + } } - } - } - ], - "returnType" : { - "float" : { - - } - } - }, - { - "abiName" : "bjs_roundTripDouble", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDouble", - "parameters" : [ + ], + "name" : "optJSObject" + }, { - "label" : "v", - "name" : "v", + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optNestedEnum" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optArray" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "optJsClass" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "OptionalAllTypesResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "OptionalAllTypesResult", + "tsFullPath" : "OptionalAllTypesResult" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + { + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "status" + } + ], + "emitStyle" : "const", + "name" : "APIOptionalResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "APIOptionalResult", + "tsFullPath" : "APIOptionalResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundTripVoid", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_roundTripInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripInt", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_roundTripUInt", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUInt", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "uint" : { + + } + } + } + ], + "returnType" : { + "uint" : { + + } + } + }, + { + "abiName" : "bjs_roundTripFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripFloat", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "float" : { + + } + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDouble", + "parameters" : [ + { + "label" : "v", + "name" : "v", "type" : { "double" : { @@ -4976,19 +5899,231 @@ } }, { - "abiName" : "bjs_makeImportedFoo", + "abiName" : "bjs_roundTripDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "makeImportedFoo", + "name" : "roundTripDictionaryExport", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "dictionary" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "abiName" : "bjs_roundTripOptionalDictionaryExport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalDictionaryExport", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSValue", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsValue" : { + + } + } + } + ], + "returnType" : { + "jsValue" : { + + } + } + }, + { + "abiName" : "bjs_roundTripOptionalJSValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalJSValue", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsValue" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripJSValueArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSValueArray", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } + }, + { + "abiName" : "bjs_roundTripOptionalJSValueArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalJSValueArray", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_makeImportedFoo", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "makeImportedFoo", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { } } @@ -6597,602 +7732,572 @@ } }, { - "abiName" : "bjs_roundTripOptionalString", + "abiName" : "bjs_roundTripAllTypesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalString", + "name" : "roundTripAllTypesResult", "parameters" : [ { - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "result", "type" : { - "optional" : { - "_0" : { - "string" : { - - } - } + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } } ], "returnType" : { - "optional" : { - "_0" : { - "string" : { - - } - } + "associatedValueEnum" : { + "_0" : "AllTypesResult" } } }, { - "abiName" : "bjs_roundTripOptionalInt", + "abiName" : "bjs_roundTripTypedPayloadResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalInt", + "name" : "roundTripTypedPayloadResult", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "_", + "name" : "result", "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } } ], "returnType" : { - "optional" : { - "_0" : { - "int" : { - - } - } + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" } } }, { - "abiName" : "bjs_roundTripOptionalBool", + "abiName" : "bjs_createPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalBool", + "name" : "createPropertyHolder", "parameters" : [ { - "label" : "flag", - "name" : "flag", + "label" : "intValue", + "name" : "intValue", "type" : { - "optional" : { - "_0" : { - "bool" : { + "int" : { - } - } } } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "bool" : { + }, + { + "label" : "floatValue", + "name" : "floatValue", + "type" : { + "float" : { } } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalFloat", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalFloat", - "parameters" : [ + }, { - "label" : "number", - "name" : "number", + "label" : "doubleValue", + "name" : "doubleValue", "type" : { - "optional" : { - "_0" : { - "float" : { + "double" : { - } - } } } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "float" : { + }, + { + "label" : "boolValue", + "name" : "boolValue", + "type" : { + "bool" : { + + } + } + }, + { + "label" : "stringValue", + "name" : "stringValue", + "type" : { + "string" : { + + } + } + }, + { + "label" : "jsObject", + "name" : "jsObject", + "type" : { + "jsObject" : { } } } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "PropertyHolder" + } } }, { - "abiName" : "bjs_roundTripOptionalDouble", + "abiName" : "bjs_testPropertyHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDouble", + "name" : "testPropertyHolder", "parameters" : [ { - "label" : "precision", - "name" : "precision", + "label" : "holder", + "name" : "holder", "type" : { - "optional" : { - "_0" : { - "double" : { - - } - } + "swiftHeapObject" : { + "_0" : "PropertyHolder" } } } ], "returnType" : { - "optional" : { - "_0" : { - "double" : { + "string" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalSyntax", + "abiName" : "bjs_resetObserverCounts", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalSyntax", + "name" : "resetObserverCounts", "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - } - } - } - } - } ], "returnType" : { - "optional" : { - "_0" : { - "string" : { + "void" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalMixSyntax", + "abiName" : "bjs_getObserverStats", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalMixSyntax", + "name" : "getObserverStats", "parameters" : [ - { - "label" : "name", - "name" : "name", - "type" : { - "optional" : { - "_0" : { - "string" : { - } - } - } - } - } ], "returnType" : { - "optional" : { - "_0" : { - "string" : { + "string" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalSwiftSyntax", + "abiName" : "bjs_testStringDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalSwiftSyntax", + "name" : "testStringDefault", "parameters" : [ { - "label" : "name", - "name" : "name", + "defaultValue" : { + "string" : { + "_0" : "Hello World" + } + }, + "label" : "message", + "name" : "message", "type" : { - "optional" : { - "_0" : { - "string" : { + "string" : { - } - } } } } ], "returnType" : { - "optional" : { - "_0" : { - "string" : { + "string" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalWithSpaces", + "abiName" : "bjs_testIntDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalWithSpaces", + "name" : "testIntDefault", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "int" : { + "_0" : 42 + } + }, + "label" : "count", + "name" : "count", "type" : { - "optional" : { - "_0" : { - "double" : { + "int" : { - } - } } } } ], "returnType" : { - "optional" : { - "_0" : { - "double" : { + "int" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalTypeAlias", + "abiName" : "bjs_testBoolDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTypeAlias", + "name" : "testBoolDefault", "parameters" : [ { - "label" : "age", - "name" : "age", + "defaultValue" : { + "bool" : { + "_0" : true + } + }, + "label" : "flag", + "name" : "flag", "type" : { - "optional" : { - "_0" : { - "int" : { + "bool" : { - } - } } } } ], "returnType" : { - "optional" : { - "_0" : { - "int" : { + "bool" : { - } - } } } }, { - "abiName" : "bjs_roundTripOptionalStatus", + "abiName" : "bjs_testOptionalDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStatus", + "name" : "testOptionalDefault", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "null" : { + + } + }, + "label" : "name", + "name" : "name", "type" : { - "optional" : { + "nullable" : { "_0" : { - "caseEnum" : { - "_0" : "Status" + "string" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "optional" : { + "nullable" : { "_0" : { - "caseEnum" : { - "_0" : "Status" + "string" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripOptionalTheme", + "abiName" : "bjs_testMultipleDefaults", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTheme", + "name" : "testMultipleDefaults", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "string" : { + "_0" : "Default Title" + } + }, + "label" : "title", + "name" : "title", "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "string" : { + + } + } + }, + { + "defaultValue" : { + "int" : { + "_0" : -10 + } + }, + "label" : "count", + "name" : "count", + "type" : { + "int" : { + + } + } + }, + { + "defaultValue" : { + "bool" : { + "_0" : false + } + }, + "label" : "enabled", + "name" : "enabled", + "type" : { + "bool" : { + } } } ], "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripOptionalHttpStatus", + "abiName" : "bjs_testSimpleEnumDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalHttpStatus", + "name" : "testSimpleEnumDefault", "parameters" : [ { - "label" : "value", - "name" : "value", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } + "defaultValue" : { + "enumCase" : { + "_0" : "Status", + "_1" : "success" + } + }, + "label" : "status", + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" } } } ], "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_roundTripOptionalTSDirection", + "abiName" : "bjs_testDirectionDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTSDirection", + "name" : "testDirectionDefault", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "enumCase" : { + "_0" : "Direction", + "_1" : "north" + } + }, + "label" : "direction", + "name" : "direction", "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "TSDirection" - } - } + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_roundTripOptionalTSTheme", + "abiName" : "bjs_testRawStringEnumDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalTSTheme", + "name" : "testRawStringEnumDefault", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "enumCase" : { + "_0" : "Theme", + "_1" : "light" + } + }, + "label" : "theme", + "name" : "theme", "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" - } - } + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_roundTripOptionalNetworkingAPIMethod", + "abiName" : "bjs_testComplexInit", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalNetworkingAPIMethod", + "name" : "testComplexInit", "parameters" : [ { - "label" : "_", - "name" : "method", - "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Networking.API.Method" + "defaultValue" : { + "objectWithArguments" : { + "_0" : "Greeter", + "_1" : [ + { + "string" : { + "_0" : "DefaultGreeter" + } } - } + ] + } + }, + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Networking.API.Method" - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripOptionalAPIResult", + "abiName" : "bjs_testEmptyInit", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalAPIResult", + "name" : "testEmptyInit", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "object" : { + "_0" : "StaticPropertyHolder" + } + }, + "label" : "_", + "name" : "object", "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" } } } ], "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } + "swiftHeapObject" : { + "_0" : "StaticPropertyHolder" } } }, { - "abiName" : "bjs_compareAPIResults", + "abiName" : "bjs_arrayWithDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "compareAPIResults", + "name" : "arrayWithDefault", "parameters" : [ { - "label" : "_", - "name" : "r1", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 1 + } + }, + { + "int" : { + "_0" : 2 + } + }, + { + "int" : { + "_0" : 3 + } } - } + ] } - } - }, - { + }, "label" : "_", - "name" : "r2", + "name" : "values", "type" : { - "optional" : { + "array" : { "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "int" : { + } } } @@ -7200,158 +8305,135 @@ } ], "returnType" : { - "string" : { + "int" : { } } }, { - "abiName" : "bjs_roundTripOptionalComplexResult", + "abiName" : "bjs_arrayWithOptionalDefault", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalComplexResult", + "name" : "arrayWithOptionalDefault", "parameters" : [ { + "defaultValue" : { + "null" : { + + } + }, "label" : "_", - "name" : "result", + "name" : "values", "type" : { - "optional" : { + "nullable" : { "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" + "array" : { + "_0" : { + "int" : { + + } + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ComplexResult" - } - } + "int" : { + } } }, { - "abiName" : "bjs_roundTripOptionalClass", + "abiName" : "bjs_arrayMixedDefaults", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalClass", + "name" : "arrayMixedDefaults", "parameters" : [ { - "label" : "value", - "name" : "value", + "defaultValue" : { + "string" : { + "_0" : "Sum" + } + }, + "label" : "prefix", + "name" : "prefix", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "array" : { + "_0" : [ + { + "int" : { + "_0" : 10 + } + }, + { + "int" : { + "_0" : 20 + } + } + ] + } + }, + "label" : "values", + "name" : "values", "type" : { - "optional" : { + "array" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "int" : { + } } } } - } - ], - "returnType" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - } - } - }, - { - "abiName" : "bjs_roundTripOptionalAPIOptionalResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripOptionalAPIOptionalResult", - "parameters" : [ + }, { - "label" : "result", - "name" : "result", + "defaultValue" : { + "string" : { + "_0" : "!" + } + }, + "label" : "suffix", + "name" : "suffix", "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } + "string" : { + } } } ], "returnType" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIOptionalResult" - } - } + "string" : { + } } }, { - "abiName" : "bjs_createPropertyHolder", + "abiName" : "bjs_formatName", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "createPropertyHolder", + "name" : "formatName", "parameters" : [ { - "label" : "intValue", - "name" : "intValue", - "type" : { - "int" : { - - } - } - }, - { - "label" : "floatValue", - "name" : "floatValue", - "type" : { - "float" : { - - } - } - }, - { - "label" : "doubleValue", - "name" : "doubleValue", - "type" : { - "double" : { - - } - } - }, - { - "label" : "boolValue", - "name" : "boolValue", - "type" : { - "bool" : { - - } - } - }, - { - "label" : "stringValue", - "name" : "stringValue", + "label" : "_", + "name" : "name", "type" : { "string" : { @@ -7359,192 +8441,274 @@ } }, { - "label" : "jsObject", - "name" : "jsObject", + "label" : "transform", + "name" : "transform", "type" : { - "jsObject" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + } + } + }, + "useJSTypedClosure" : false } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" + "string" : { + } } }, { - "abiName" : "bjs_testPropertyHolder", + "abiName" : "bjs_makeFormatter", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testPropertyHolder", + "name" : "makeFormatter", "parameters" : [ { - "label" : "holder", - "name" : "holder", + "label" : "prefix", + "name" : "prefix", "type" : { - "swiftHeapObject" : { - "_0" : "PropertyHolder" + "string" : { + } } } ], "returnType" : { - "string" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + } + } + }, + "useJSTypedClosure" : false } } }, { - "abiName" : "bjs_resetObserverCounts", + "abiName" : "bjs_makeAdder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "resetObserverCounts", + "name" : "makeAdder", "parameters" : [ + { + "label" : "base", + "name" : "base", + "type" : { + "int" : { + } + } + } ], "returnType" : { - "void" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false } } }, { - "abiName" : "bjs_getObserverStats", + "abiName" : "bjs_roundTripIntArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "getObserverStats", + "name" : "roundTripIntArray", "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + } + } + } + } + } ], "returnType" : { - "string" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { - "abiName" : "bjs_testStringDefault", + "abiName" : "bjs_roundTripStringArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testStringDefault", + "name" : "roundTripStringArray", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Hello World" - } - }, - "label" : "message", - "name" : "message", + "label" : "_", + "name" : "values", "type" : { - "string" : { + "array" : { + "_0" : { + "string" : { + } + } } } } ], "returnType" : { - "string" : { + "array" : { + "_0" : { + "string" : { + } + } } } }, { - "abiName" : "bjs_testIntDefault", + "abiName" : "bjs_roundTripDoubleArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testIntDefault", + "name" : "roundTripDoubleArray", "parameters" : [ { - "defaultValue" : { - "int" : { - "_0" : 42 - } - }, - "label" : "count", - "name" : "count", + "label" : "_", + "name" : "values", "type" : { - "int" : { + "array" : { + "_0" : { + "double" : { + } + } } } } ], "returnType" : { - "int" : { + "array" : { + "_0" : { + "double" : { + } + } } } }, { - "abiName" : "bjs_testBoolDefault", + "abiName" : "bjs_roundTripBoolArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testBoolDefault", + "name" : "roundTripBoolArray", "parameters" : [ { - "defaultValue" : { - "bool" : { - "_0" : true - } - }, - "label" : "flag", - "name" : "flag", + "label" : "_", + "name" : "values", "type" : { - "bool" : { + "array" : { + "_0" : { + "bool" : { + } + } } } } ], "returnType" : { - "bool" : { + "array" : { + "_0" : { + "bool" : { + } + } } } }, { - "abiName" : "bjs_testOptionalDefault", + "abiName" : "bjs_roundTripDirectionArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testOptionalDefault", + "name" : "roundTripDirectionArray", "parameters" : [ { - "defaultValue" : { - "null" : { - - } - }, - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "values", "type" : { - "optional" : { + "array" : { "_0" : { - "string" : { - + "caseEnum" : { + "_0" : "Direction" } } } @@ -7552,311 +8716,249 @@ } ], "returnType" : { - "optional" : { + "array" : { "_0" : { - "string" : { - + "caseEnum" : { + "_0" : "Direction" } } } } }, { - "abiName" : "bjs_testMultipleDefaults", + "abiName" : "bjs_roundTripStatusArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testMultipleDefaults", + "name" : "roundTripStatusArray", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Default Title" - } - }, - "label" : "title", - "name" : "title", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "int" : { - "_0" : -10 - } - }, - "label" : "count", - "name" : "count", - "type" : { - "int" : { - - } - } - }, - { - "defaultValue" : { - "bool" : { - "_0" : false - } - }, - "label" : "enabled", - "name" : "enabled", + "label" : "_", + "name" : "values", "type" : { - "bool" : { - + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + } } } }, { - "abiName" : "bjs_testSimpleEnumDefault", + "abiName" : "bjs_roundTripThemeArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testSimpleEnumDefault", + "name" : "roundTripThemeArray", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Status", - "_1" : "success" - } - }, - "label" : "status", - "name" : "status", + "label" : "_", + "name" : "values", "type" : { - "caseEnum" : { - "_0" : "Status" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } }, { - "abiName" : "bjs_testDirectionDefault", + "abiName" : "bjs_roundTripHttpStatusArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testDirectionDefault", + "name" : "roundTripHttpStatusArray", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Direction", - "_1" : "north" - } - }, - "label" : "direction", - "name" : "direction", + "label" : "_", + "name" : "values", "type" : { - "caseEnum" : { - "_0" : "Direction" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } } } }, { - "abiName" : "bjs_testRawStringEnumDefault", + "abiName" : "bjs_roundTripDataPointArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testRawStringEnumDefault", + "name" : "roundTripDataPointArray", "parameters" : [ { - "defaultValue" : { - "enumCase" : { - "_0" : "Theme", - "_1" : "light" - } - }, - "label" : "theme", - "name" : "theme", + "label" : "_", + "name" : "points", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } } } }, { - "abiName" : "bjs_testComplexInit", + "abiName" : "bjs_roundTripGreeterArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testComplexInit", + "name" : "roundTripGreeterArray", "parameters" : [ { - "defaultValue" : { - "objectWithArguments" : { - "_0" : "Greeter", - "_1" : [ - { - "string" : { - "_0" : "DefaultGreeter" - } - } - ] - } - }, - "label" : "greeter", - "name" : "greeter", + "label" : "_", + "name" : "greeters", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } } }, { - "abiName" : "bjs_testEmptyInit", + "abiName" : "bjs_roundTripOptionalIntArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testEmptyInit", + "name" : "roundTripOptionalIntArray", "parameters" : [ { - "defaultValue" : { - "object" : { - "_0" : "StaticPropertyHolder" - } - }, "label" : "_", - "name" : "object", + "name" : "values", "type" : { - "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "StaticPropertyHolder" - } - } - }, - { - "abiName" : "bjs_arrayWithDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "arrayWithDefault", - "parameters" : [ - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 1 - } - }, - { - "int" : { - "_0" : 2 - } - }, - { - "int" : { - "_0" : 3 - } - } - ] - } - }, - "label" : "_", - "name" : "values", - "type" : { - "array" : { + "array" : { + "_0" : { + "nullable" : { "_0" : { "int" : { } - } + }, + "_1" : "null" } } } - ], - "returnType" : { - "int" : { - - } } }, { - "abiName" : "bjs_arrayWithOptionalDefault", + "abiName" : "bjs_roundTripOptionalStringArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayWithOptionalDefault", + "name" : "roundTripOptionalStringArray", "parameters" : [ { - "defaultValue" : { - "null" : { - - } - }, "label" : "_", "name" : "values", "type" : { - "optional" : { + "array" : { "_0" : { - "array" : { + "nullable" : { "_0" : { - "int" : { + "string" : { } - } + }, + "_1" : "null" } } } @@ -7864,123 +8966,85 @@ } ], "returnType" : { - "int" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "string" : { + } + }, + "_1" : "null" + } + } } } }, { - "abiName" : "bjs_arrayMixedDefaults", + "abiName" : "bjs_roundTripOptionalDataPointArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "arrayMixedDefaults", + "name" : "roundTripOptionalDataPointArray", "parameters" : [ { - "defaultValue" : { - "string" : { - "_0" : "Sum" - } - }, - "label" : "prefix", - "name" : "prefix", - "type" : { - "string" : { - - } - } - }, - { - "defaultValue" : { - "array" : { - "_0" : [ - { - "int" : { - "_0" : 10 - } - }, - { - "int" : { - "_0" : 20 - } - } - ] - } - }, - "label" : "values", - "name" : "values", + "label" : "_", + "name" : "points", "type" : { "array" : { "_0" : { - "int" : { - + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" } } } } - }, - { - "defaultValue" : { - "string" : { - "_0" : "!" - } - }, - "label" : "suffix", - "name" : "suffix", - "type" : { - "string" : { - - } - } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } } } }, { - "abiName" : "bjs_formatName", + "abiName" : "bjs_roundTripOptionalDirectionArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "formatName", + "name" : "roundTripOptionalDirectionArray", "parameters" : [ { "label" : "_", - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "label" : "transform", - "name" : "transform", + "name" : "directions", "type" : { - "closure" : { + "array" : { "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" } - } - ], - "returnType" : { - "string" : { - - } + }, + "_1" : "null" } } } @@ -7988,169 +9052,200 @@ } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } } } }, { - "abiName" : "bjs_makeFormatter", + "abiName" : "bjs_roundTripOptionalStatusArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeFormatter", + "name" : "roundTripOptionalStatusArray", "parameters" : [ { - "label" : "prefix", - "name" : "prefix", + "label" : "_", + "name" : "statuses", "type" : { - "string" : { - + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "_1" : "null" + } + } } } } ], "returnType" : { - "closure" : { + "array" : { "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" } - } - ], - "returnType" : { - "string" : { - - } + }, + "_1" : "null" } } } } }, { - "abiName" : "bjs_makeAdder", + "abiName" : "bjs_roundTripOptionalIntArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAdder", + "name" : "roundTripOptionalIntArrayType", "parameters" : [ { - "label" : "base", - "name" : "base", + "label" : "_", + "name" : "values", "type" : { - "int" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "closure" : { + "nullable" : { "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { + "array" : { + "_0" : { "int" : { } } - ], - "returnType" : { - "int" : { - - } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripIntArray", + "abiName" : "bjs_roundTripOptionalStringArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripIntArray", + "name" : "roundTripOptionalStringArrayType", "parameters" : [ { "label" : "_", "name" : "values", "type" : { - "array" : { + "nullable" : { "_0" : { - "int" : { + "array" : { + "_0" : { + "string" : { + } + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "int" : { + "array" : { + "_0" : { + "string" : { + } + } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripStringArray", + "abiName" : "bjs_roundTripOptionalGreeterArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripStringArray", + "name" : "roundTripOptionalGreeterArrayType", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "greeters", "type" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripDoubleArray", + "abiName" : "bjs_roundTripNestedIntArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDoubleArray", + "name" : "roundTripNestedIntArray", "parameters" : [ { "label" : "_", @@ -8158,8 +9253,12 @@ "type" : { "array" : { "_0" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } } @@ -8169,21 +9268,25 @@ "returnType" : { "array" : { "_0" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } } } }, { - "abiName" : "bjs_roundTripBoolArray", + "abiName" : "bjs_roundTripNestedStringArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripBoolArray", + "name" : "roundTripNestedStringArray", "parameters" : [ { "label" : "_", @@ -8191,8 +9294,12 @@ "type" : { "array" : { "_0" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } @@ -8202,21 +9309,25 @@ "returnType" : { "array" : { "_0" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } } }, { - "abiName" : "bjs_roundTripDirectionArray", + "abiName" : "bjs_roundTripNestedDoubleArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDirectionArray", + "name" : "roundTripNestedDoubleArray", "parameters" : [ { "label" : "_", @@ -8224,8 +9335,12 @@ "type" : { "array" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" + "array" : { + "_0" : { + "double" : { + + } + } } } } @@ -8235,21 +9350,25 @@ "returnType" : { "array" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" + "array" : { + "_0" : { + "double" : { + + } + } } } } } }, { - "abiName" : "bjs_roundTripStatusArray", + "abiName" : "bjs_roundTripNestedBoolArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripStatusArray", + "name" : "roundTripNestedBoolArray", "parameters" : [ { "label" : "_", @@ -8257,8 +9376,12 @@ "type" : { "array" : { "_0" : { - "caseEnum" : { - "_0" : "Status" + "array" : { + "_0" : { + "bool" : { + + } + } } } } @@ -8268,31 +9391,38 @@ "returnType" : { "array" : { "_0" : { - "caseEnum" : { - "_0" : "Status" + "array" : { + "_0" : { + "bool" : { + + } + } } } } } }, { - "abiName" : "bjs_roundTripThemeArray", + "abiName" : "bjs_roundTripNestedDataPointArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripThemeArray", + "name" : "roundTripNestedDataPointArray", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "points", "type" : { "array" : { "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } } } } @@ -8302,32 +9432,38 @@ "returnType" : { "array" : { "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } } } } } }, { - "abiName" : "bjs_roundTripHttpStatusArray", + "abiName" : "bjs_roundTripNestedDirectionArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripHttpStatusArray", + "name" : "roundTripNestedDirectionArray", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "directions", "type" : { "array" : { "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } } @@ -8337,31 +9473,38 @@ "returnType" : { "array" : { "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } } } }, { - "abiName" : "bjs_roundTripDataPointArray", + "abiName" : "bjs_roundTripNestedGreeterArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataPointArray", + "name" : "roundTripNestedGreeterArray", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "greeters", "type" : { "array" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } } } @@ -8371,30 +9514,36 @@ "returnType" : { "array" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" + "array" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } } } } } }, { - "abiName" : "bjs_roundTripGreeterArray", + "abiName" : "bjs_roundTripUnsafeRawPointerArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripGreeterArray", + "name" : "roundTripUnsafeRawPointerArray", "parameters" : [ { "label" : "_", - "name" : "greeters", + "name" : "values", "type" : { "array" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } } @@ -8404,21 +9553,23 @@ "returnType" : { "array" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } } } }, { - "abiName" : "bjs_roundTripOptionalIntArray", + "abiName" : "bjs_roundTripUnsafeMutableRawPointerArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalIntArray", + "name" : "roundTripUnsafeMutableRawPointerArray", "parameters" : [ { "label" : "_", @@ -8426,11 +9577,9 @@ "type" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "int" : { - - } + "kind" : "unsafeMutableRawPointer" } } } @@ -8441,11 +9590,9 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "int" : { - - } + "kind" : "unsafeMutableRawPointer" } } } @@ -8453,13 +9600,13 @@ } }, { - "abiName" : "bjs_roundTripOptionalStringArray", + "abiName" : "bjs_roundTripOpaquePointerArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStringArray", + "name" : "roundTripOpaquePointerArray", "parameters" : [ { "label" : "_", @@ -8467,11 +9614,9 @@ "type" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "string" : { - - } + "kind" : "opaquePointer" } } } @@ -8482,11 +9627,9 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "string" : { - - } + "kind" : "opaquePointer" } } } @@ -8494,25 +9637,24 @@ } }, { - "abiName" : "bjs_roundTripOptionalDataPointArray", + "abiName" : "bjs_roundTripUnsafePointerArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDataPointArray", + "name" : "roundTripUnsafePointerArray", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "values", "type" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } + "kind" : "unsafePointer", + "pointee" : "UInt8" } } } @@ -8523,11 +9665,10 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } + "kind" : "unsafePointer", + "pointee" : "UInt8" } } } @@ -8535,25 +9676,24 @@ } }, { - "abiName" : "bjs_roundTripOptionalDirectionArray", + "abiName" : "bjs_roundTripUnsafeMutablePointerArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDirectionArray", + "name" : "roundTripUnsafeMutablePointerArray", "parameters" : [ { "label" : "_", - "name" : "directions", + "name" : "values", "type" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" - } + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" } } } @@ -8564,11 +9704,10 @@ "returnType" : { "array" : { "_0" : { - "optional" : { + "unsafePointer" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" - } + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" } } } @@ -8576,26 +9715,22 @@ } }, { - "abiName" : "bjs_roundTripOptionalStatusArray", + "abiName" : "bjs_consumeDataProcessorArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStatusArray", + "name" : "consumeDataProcessorArrayType", "parameters" : [ { "label" : "_", - "name" : "statuses", + "name" : "processors", "type" : { "array" : { "_0" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - } + "swiftProtocol" : { + "_0" : "DataProcessor" } } } @@ -8603,40 +9738,28 @@ } ], "returnType" : { - "array" : { - "_0" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Status" - } - } - } - } + "int" : { + } } }, { - "abiName" : "bjs_roundTripOptionalIntArrayType", + "abiName" : "bjs_roundTripDataProcessorArrayType", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalIntArrayType", + "name" : "roundTripDataProcessorArrayType", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "processors", "type" : { - "optional" : { + "array" : { "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } + "swiftProtocol" : { + "_0" : "DataProcessor" } } } @@ -8644,40 +9767,32 @@ } ], "returnType" : { - "optional" : { + "array" : { "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } + "swiftProtocol" : { + "_0" : "DataProcessor" } } } } }, { - "abiName" : "bjs_roundTripOptionalStringArrayType", + "abiName" : "bjs_roundTripJSObjectArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalStringArrayType", + "name" : "roundTripJSObjectArray", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "objects", "type" : { - "optional" : { + "array" : { "_0" : { - "array" : { - "_0" : { - "string" : { + "jsObject" : { - } - } } } } @@ -8685,40 +9800,37 @@ } ], "returnType" : { - "optional" : { + "array" : { "_0" : { - "array" : { - "_0" : { - "string" : { + "jsObject" : { - } - } } } } } }, { - "abiName" : "bjs_roundTripOptionalGreeterArrayType", + "abiName" : "bjs_roundTripOptionalJSObjectArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalGreeterArrayType", + "name" : "roundTripOptionalJSObjectArray", "parameters" : [ { "label" : "_", - "name" : "greeters", + "name" : "objects", "type" : { - "optional" : { + "array" : { "_0" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsObject" : { + } - } + }, + "_1" : "null" } } } @@ -8726,40 +9838,37 @@ } ], "returnType" : { - "optional" : { + "array" : { "_0" : { - "array" : { + "nullable" : { "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsObject" : { + } - } + }, + "_1" : "null" } } } } }, { - "abiName" : "bjs_roundTripNestedIntArray", + "abiName" : "bjs_roundTripFooArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedIntArray", + "name" : "roundTripFooArray", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "foos", "type" : { "array" : { "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } + "jsObject" : { + "_0" : "Foo" } } } @@ -8769,38 +9878,35 @@ "returnType" : { "array" : { "_0" : { - "array" : { - "_0" : { - "int" : { - - } - } + "jsObject" : { + "_0" : "Foo" } } } } }, { - "abiName" : "bjs_roundTripNestedStringArray", + "abiName" : "bjs_roundTripOptionalFooArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedStringArray", + "name" : "roundTripOptionalFooArray", "parameters" : [ { "label" : "_", - "name" : "values", + "name" : "foos", "type" : { "array" : { "_0" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "jsObject" : { + "_0" : "Foo" } - } + }, + "_1" : "null" } } } @@ -8810,1451 +9916,1590 @@ "returnType" : { "array" : { "_0" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "jsObject" : { + "_0" : "Foo" } - } + }, + "_1" : "null" } } } } }, { - "abiName" : "bjs_roundTripNestedDoubleArray", + "abiName" : "bjs_roundTripOptionalString", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedDoubleArray", + "name" : "roundTripOptionalString", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "name", + "name" : "name", "type" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "double" : { + "string" : { - } - } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "double" : { + "string" : { - } - } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripNestedBoolArray", + "abiName" : "bjs_roundTripOptionalInt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedBoolArray", + "name" : "roundTripOptionalInt", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "value", + "name" : "value", "type" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "bool" : { + "int" : { - } - } } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "bool" : { + "int" : { - } - } } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripNestedDataPointArray", + "abiName" : "bjs_roundTripOptionalBool", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedDataPointArray", + "name" : "roundTripOptionalBool", "parameters" : [ { - "label" : "_", - "name" : "points", + "label" : "flag", + "name" : "flag", "type" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } + "bool" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } + "bool" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripNestedDirectionArray", + "abiName" : "bjs_roundTripOptionalFloat", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedDirectionArray", + "name" : "roundTripOptionalFloat", "parameters" : [ { - "label" : "_", - "name" : "directions", + "label" : "number", + "name" : "number", "type" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "float" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "float" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripNestedGreeterArray", + "abiName" : "bjs_roundTripOptionalDouble", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripNestedGreeterArray", + "name" : "roundTripOptionalDouble", "parameters" : [ { - "label" : "_", - "name" : "greeters", + "label" : "precision", + "name" : "precision", "type" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "double" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "array" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "double" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripUnsafeRawPointerArray", + "abiName" : "bjs_roundTripOptionalSyntax", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeRawPointerArray", + "name" : "roundTripOptionalSyntax", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "name", + "name" : "name", "type" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } + "string" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } + "string" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripUnsafeMutableRawPointerArray", + "abiName" : "bjs_roundTripOptionalMixSyntax", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutableRawPointerArray", + "name" : "roundTripOptionalMixSyntax", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "name", + "name" : "name", "type" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } + "string" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } + "string" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripOpaquePointerArray", + "abiName" : "bjs_roundTripOptionalSwiftSyntax", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOpaquePointerArray", + "name" : "roundTripOptionalSwiftSyntax", "parameters" : [ { - "label" : "_", - "name" : "values", + "label" : "name", + "name" : "name", "type" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "string" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "string" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_consumeDataProcessorArrayType", + "abiName" : "bjs_roundTripOptionalWithSpaces", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "consumeDataProcessorArrayType", + "name" : "roundTripOptionalWithSpaces", "parameters" : [ { - "label" : "_", - "name" : "processors", + "label" : "value", + "name" : "value", "type" : { - "array" : { + "nullable" : { "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" + "double" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "int" : { + "nullable" : { + "_0" : { + "double" : { + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripDataProcessorArrayType", + "abiName" : "bjs_roundTripOptionalTypeAlias", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataProcessorArrayType", + "name" : "roundTripOptionalTypeAlias", "parameters" : [ { - "label" : "_", - "name" : "processors", + "label" : "age", + "name" : "age", "type" : { - "array" : { + "nullable" : { "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" + "int" : { + } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "swiftProtocol" : { - "_0" : "DataProcessor" + "int" : { + } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripPointerFields", + "abiName" : "bjs_roundTripOptionalStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripPointerFields", + "name" : "roundTripOptionalStatus", "parameters" : [ { - "label" : "_", + "label" : "value", "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "PointerFields" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PointerFields" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_testStructDefault", + "abiName" : "bjs_roundTripOptionalTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testStructDefault", + "name" : "roundTripOptionalTheme", "parameters" : [ { - "defaultValue" : { - "structLiteral" : { - "_0" : "DataPoint", - "_1" : [ - { - "name" : "x", - "value" : { - "float" : { - "_0" : 1 - } - } - }, - { - "name" : "y", - "value" : { - "float" : { - "_0" : 2 - } - } - }, - { - "name" : "label", - "value" : { - "string" : { - "_0" : "default" - } - } - }, - { - "name" : "optCount", - "value" : { - "null" : { - - } - } - }, - { - "name" : "optFlag", - "value" : { - "null" : { - - } - } - } - ] - } - }, - "label" : "point", - "name" : "point", + "label" : "value", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { - + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_cartToJSObject", + "abiName" : "bjs_roundTripOptionalHttpStatus", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "cartToJSObject", + "name" : "roundTripOptionalHttpStatus", "parameters" : [ { - "label" : "_", - "name" : "cart", + "label" : "value", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "CopyableCart" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" } } } ], "returnType" : { - "jsObject" : { - + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_nestedCartToJSObject", + "abiName" : "bjs_roundTripOptionalTSDirection", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "nestedCartToJSObject", + "name" : "roundTripOptionalTSDirection", "parameters" : [ { - "label" : "_", - "name" : "cart", + "label" : "value", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "CopyableNestedCart" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "TSDirection" + } + }, + "_1" : "null" } } } ], "returnType" : { - "jsObject" : { - + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "TSDirection" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripDataPoint", + "abiName" : "bjs_roundTripOptionalTSTheme", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataPoint", + "name" : "roundTripOptionalTSTheme", "parameters" : [ { - "label" : "_", - "name" : "data", + "label" : "value", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripContact", + "abiName" : "bjs_roundTripOptionalNetworkingAPIMethod", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripContact", + "name" : "roundTripOptionalNetworkingAPIMethod", "parameters" : [ { "label" : "_", - "name" : "contact", + "name" : "method", "type" : { - "swiftStruct" : { - "_0" : "Contact" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "Contact" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Networking.API.Method" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripConfig", + "abiName" : "bjs_roundTripOptionalAPIResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripConfig", + "name" : "roundTripOptionalAPIResult", "parameters" : [ { - "label" : "_", - "name" : "config", + "label" : "value", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "Config" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "Config" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripSessionData", + "abiName" : "bjs_roundTripOptionalTypedPayloadResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripSessionData", + "name" : "roundTripOptionalTypedPayloadResult", "parameters" : [ { "label" : "_", - "name" : "session", + "name" : "result", "type" : { - "swiftStruct" : { - "_0" : "SessionData" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "SessionData" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "TypedPayloadResult" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripValidationReport", + "abiName" : "bjs_takeOptionalJSObject", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripValidationReport", + "name" : "takeOptionalJSObject", "parameters" : [ { "label" : "_", - "name" : "report", + "name" : "value", "type" : { - "swiftStruct" : { - "_0" : "ValidationReport" + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "ValidationReport" + "void" : { + } } }, { - "abiName" : "bjs_roundTripAdvancedConfig", + "abiName" : "bjs_compareAPIResults", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripAdvancedConfig", + "name" : "compareAPIResults", "parameters" : [ { "label" : "_", - "name" : "config", + "name" : "r1", "type" : { - "swiftStruct" : { - "_0" : "AdvancedConfig" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + { + "label" : "_", + "name" : "r2", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "AdvancedConfig" + "string" : { + } } }, { - "abiName" : "bjs_roundTripMeasurementConfig", + "abiName" : "bjs_roundTripOptionalComplexResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripMeasurementConfig", + "name" : "roundTripOptionalComplexResult", "parameters" : [ { "label" : "_", - "name" : "config", + "name" : "result", "type" : { - "swiftStruct" : { - "_0" : "MeasurementConfig" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "MeasurementConfig" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ComplexResult" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_updateValidationReport", + "abiName" : "bjs_roundTripOptionalAllTypesResult", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "updateValidationReport", + "name" : "roundTripOptionalAllTypesResult", "parameters" : [ { "label" : "_", - "name" : "newResult", + "name" : "result", "type" : { - "optional" : { + "nullable" : { "_0" : { "associatedValueEnum" : { - "_0" : "APIResult" + "_0" : "AllTypesResult" } - } + }, + "_1" : "null" } } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AllTypesResult" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalPayloadResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalPayloadResult", + "parameters" : [ { "label" : "_", - "name" : "report", + "name" : "result", "type" : { - "swiftStruct" : { - "_0" : "ValidationReport" + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "ValidationReport" + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" } } }, { - "abiName" : "bjs_testContainerWithStruct", + "abiName" : "bjs_roundTripOptionalPayloadResultOpt", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "testContainerWithStruct", + "name" : "roundTripOptionalPayloadResultOpt", "parameters" : [ { "label" : "_", - "name" : "point", + "name" : "result", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Container" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "OptionalAllTypesResult" + } + }, + "_1" : "null" } } - } - ], - "protocols" : [ + }, { - "methods" : [ + "abiName" : "bjs_roundTripOptionalClass", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalClass", + "parameters" : [ { - "abiName" : "bjs_DataProcessor_increment", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "increment", - "parameters" : [ - { - "label" : "by", - "name" : "amount", - "type" : { - "int" : { - + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" } - } - } - ], - "returnType" : { - "void" : { - + }, + "_1" : "null" } } - }, - { - "abiName" : "bjs_DataProcessor_getValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } }, - "name" : "getValue", - "parameters" : [ - - ], - "returnType" : { - "int" : { - - } - } - }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalGreeter", + "parameters" : [ { - "abiName" : "bjs_DataProcessor_setLabelElements", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "setLabelElements", - "parameters" : [ - { - "label" : "_", - "name" : "labelPrefix", - "type" : { - "string" : { - - } - } - }, - { - "label" : "_", - "name" : "labelSuffix", - "type" : { - "string" : { - + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" } - } - } - ], - "returnType" : { - "void" : { - + }, + "_1" : "null" } } - }, - { - "abiName" : "bjs_DataProcessor_getLabel", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getLabel", - "parameters" : [ - - ], - "returnType" : { - "string" : { - + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" } - } - }, - { - "abiName" : "bjs_DataProcessor_isEven", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false }, - "name" : "isEven", - "parameters" : [ - - ], - "returnType" : { - "bool" : { - - } - } - }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_applyOptionalGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "applyOptionalGreeter", + "parameters" : [ { - "abiName" : "bjs_DataProcessor_processGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processGreeter", - "parameters" : [ - { - "label" : "_", - "name" : "greeter", - "type" : { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_DataProcessor_createGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "createGreeter", - "parameters" : [ - - ], - "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + }, + "_1" : "null" } } }, { - "abiName" : "bjs_DataProcessor_processOptionalGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "processOptionalGreeter", - "parameters" : [ - { - "label" : "_", - "name" : "greeter", - "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" } } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } } - } - } - ], - "returnType" : { - "string" : { - + }, + "useJSTypedClosure" : false } } - }, - { - "abiName" : "bjs_DataProcessor_createOptionalGreeter", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } }, - "name" : "createOptionalGreeter", - "parameters" : [ - - ], - "returnType" : { - "optional" : { + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_makeOptionalHolder", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeOptionalHolder", + "parameters" : [ + { + "label" : "nullableGreeter", + "name" : "nullableGreeter", + "type" : { + "nullable" : { "_0" : { "swiftHeapObject" : { "_0" : "Greeter" } - } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_DataProcessor_handleAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "handleAPIResult", - "parameters" : [ - { - "label" : "_", - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - } - } - ], - "returnType" : { - "void" : { + "label" : "undefinedNumber", + "name" : "undefinedNumber", + "type" : { + "nullable" : { + "_0" : { + "double" : { + } + }, + "_1" : "undefined" } } - }, - { - "abiName" : "bjs_DataProcessor_getAPIResult", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getAPIResult", - "parameters" : [ - - ], - "returnType" : { - "optional" : { + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "OptionalHolder" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalAPIOptionalResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalAPIOptionalResult", + "parameters" : [ + { + "label" : "result", + "name" : "result", + "type" : { + "nullable" : { "_0" : { "associatedValueEnum" : { - "_0" : "APIResult" + "_0" : "APIOptionalResult" } - } + }, + "_1" : "null" } } } ], - "name" : "DataProcessor", - "properties" : [ - { - "isReadonly" : false, - "name" : "count", - "type" : { - "int" : { - + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIOptionalResult" } - } - }, + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripPointerFields", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripPointerFields", + "parameters" : [ { - "isReadonly" : true, - "name" : "name", + "label" : "_", + "name" : "value", "type" : { - "string" : { - + "swiftStruct" : { + "_0" : "PointerFields" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PointerFields" + } + } + }, + { + "abiName" : "bjs_testStructDefault", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testStructDefault", + "parameters" : [ { - "isReadonly" : false, - "name" : "optionalTag", - "type" : { - "optional" : { - "_0" : { - "string" : { + "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" : { + } + } } - } + ] } - } - }, - { - "isReadonly" : false, - "name" : "optionalCount", + }, + "label" : "point", + "name" : "point", "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } + "swiftStruct" : { + "_0" : "DataPoint" } } - }, + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_cartToJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "cartToJSObject", + "parameters" : [ { - "isReadonly" : false, - "name" : "direction", + "label" : "_", + "name" : "cart", "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "swiftStruct" : { + "_0" : "CopyableCart" } } - }, + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_nestedCartToJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "nestedCartToJSObject", + "parameters" : [ { - "isReadonly" : false, - "name" : "optionalTheme", + "label" : "_", + "name" : "cart", "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "swiftStruct" : { + "_0" : "CopyableNestedCart" } } - }, + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDataPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDataPoint", + "parameters" : [ { - "isReadonly" : false, - "name" : "httpStatus", + "label" : "_", + "name" : "data", "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } + "swiftStruct" : { + "_0" : "DataPoint" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + }, + { + "abiName" : "bjs_roundTripPublicPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripPublicPoint", + "parameters" : [ { - "isReadonly" : false, - "name" : "apiResult", + "label" : "_", + "name" : "point", "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" - } - } - } - } - }, - { - "isReadonly" : false, - "name" : "helper", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "swiftStruct" : { + "_0" : "PublicPoint" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_roundTripContact", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripContact", + "parameters" : [ { - "isReadonly" : false, - "name" : "optionalHelper", + "label" : "_", + "name" : "contact", "type" : { - "optional" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } + "swiftStruct" : { + "_0" : "Contact" } } } - ] - } - ], - "structs" : [ - { - "methods" : [ - ], - "name" : "Point", - "properties" : [ + "returnType" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + }, + { + "abiName" : "bjs_roundTripConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripConfig", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "x", + "label" : "_", + "name" : "config", "type" : { - "int" : { - + "swiftStruct" : { + "_0" : "Config" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Config" + } + } + }, + { + "abiName" : "bjs_roundTripSessionData", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripSessionData", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "y", + "label" : "_", + "name" : "session", "type" : { - "int" : { - + "swiftStruct" : { + "_0" : "SessionData" } } } ], - "swiftCallName" : "Point" + "returnType" : { + "swiftStruct" : { + "_0" : "SessionData" + } + } }, { - "constructor" : { - "abiName" : "bjs_PointerFields_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "raw", - "name" : "raw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } - } - } - }, - { - "label" : "mutRaw", - "name" : "mutRaw", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } - } - } - }, - { - "label" : "opaque", - "name" : "opaque", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - }, - { - "label" : "ptr", - "name" : "ptr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - }, - { - "label" : "mutPtr", - "name" : "mutPtr", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - } - ] + "abiName" : "bjs_roundTripValidationReport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false }, - "methods" : [ - - ], - "name" : "PointerFields", - "properties" : [ + "name" : "roundTripValidationReport", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "raw", + "label" : "_", + "name" : "report", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" - } + "swiftStruct" : { + "_0" : "ValidationReport" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } + }, + { + "abiName" : "bjs_roundTripAdvancedConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripAdvancedConfig", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "mutRaw", + "label" : "_", + "name" : "config", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" - } + "swiftStruct" : { + "_0" : "AdvancedConfig" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "AdvancedConfig" + } + } + }, + { + "abiName" : "bjs_roundTripMeasurementConfig", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMeasurementConfig", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "opaque", + "label" : "_", + "name" : "config", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "swiftStruct" : { + "_0" : "MeasurementConfig" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "MeasurementConfig" + } + } + }, + { + "abiName" : "bjs_updateValidationReport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "updateValidationReport", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "ptr", + "label" : "_", + "name" : "newResult", "type" : { - "unsafePointer" : { + "nullable" : { "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "mutPtr", + "label" : "_", + "name" : "report", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } + "swiftStruct" : { + "_0" : "ValidationReport" } } } ], - "swiftCallName" : "PointerFields" + "returnType" : { + "swiftStruct" : { + "_0" : "ValidationReport" + } + } }, { - "constructor" : { - "abiName" : "bjs_DataPoint_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "x", - "name" : "x", - "type" : { - "double" : { - - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "double" : { - - } - } - }, - { - "label" : "label", - "name" : "label", - "type" : { - "string" : { - - } - } - }, - { - "label" : "optCount", - "name" : "optCount", - "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } - } - } - }, - { - "label" : "optFlag", - "name" : "optFlag", - "type" : { - "optional" : { - "_0" : { - "bool" : { - - } - } - } + "abiName" : "bjs_testContainerWithStruct", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "testContainerWithStruct", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" } } - ] - }, - "methods" : [ - + } ], - "name" : "DataPoint", - "properties" : [ + "returnType" : { + "swiftHeapObject" : { + "_0" : "Container" + } + } + }, + { + "abiName" : "bjs_roundTripJSObjectContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSObjectContainer", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "x", + "label" : "_", + "name" : "container", "type" : { - "double" : { - + "swiftStruct" : { + "_0" : "JSObjectContainer" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "JSObjectContainer" + } + } + }, + { + "abiName" : "bjs_roundTripFooContainer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripFooContainer", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "y", + "label" : "_", + "name" : "container", "type" : { - "double" : { - + "swiftStruct" : { + "_0" : "FooContainer" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "FooContainer" + } + } + }, + { + "abiName" : "bjs_roundTripArrayMembers", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripArrayMembers", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "label", + "label" : "_", + "name" : "value", "type" : { - "string" : { - + "swiftStruct" : { + "_0" : "ArrayMembers" } } - }, + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "ArrayMembers" + } + } + }, + { + "abiName" : "bjs_arrayMembersSum", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "arrayMembersSum", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "optCount", + "label" : "_", + "name" : "value", "type" : { - "optional" : { - "_0" : { - "int" : { - - } - } + "swiftStruct" : { + "_0" : "ArrayMembers" } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "optFlag", + "label" : "_", + "name" : "values", "type" : { - "optional" : { + "array" : { "_0" : { - "bool" : { + "int" : { } } @@ -10262,42 +11507,37 @@ } } ], - "swiftCallName" : "DataPoint" + "returnType" : { + "int" : { + + } + } }, { - "methods" : [ - - ], - "name" : "Address", - "properties" : [ + "abiName" : "bjs_arrayMembersFirst", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "arrayMembersFirst", + "parameters" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "street", + "label" : "_", + "name" : "value", "type" : { - "string" : { - + "swiftStruct" : { + "_0" : "ArrayMembers" } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "city", + "label" : "_", + "name" : "values", "type" : { - "string" : { - - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "zipCode", - "type" : { - "optional" : { + "array" : { "_0" : { - "int" : { + "string" : { } } @@ -10305,1072 +11545,3346 @@ } } ], - "swiftCallName" : "Address" - }, + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ { "methods" : [ - - ], - "name" : "Contact", - "properties" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { + "abiName" : "bjs_DataProcessor_increment", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "increment", + "parameters" : [ + { + "label" : "by", + "name" : "amount", + "type" : { + "int" : { + } + } } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "age", - "type" : { - "int" : { + ], + "returnType" : { + "void" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "address", - "type" : { - "swiftStruct" : { - "_0" : "Address" + "abiName" : "bjs_DataProcessor_getValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getValue", + "parameters" : [ + + ], + "returnType" : { + "int" : { + } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "email", - "type" : { - "optional" : { - "_0" : { + "abiName" : "bjs_DataProcessor_setLabelElements", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setLabelElements", + "parameters" : [ + { + "label" : "_", + "name" : "labelPrefix", + "type" : { "string" : { } } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "secondaryAddress", - "type" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "Address" + }, + { + "label" : "_", + "name" : "labelSuffix", + "type" : { + "string" : { + } } } - } - } - ], - "swiftCallName" : "Contact" - }, - { - "methods" : [ - - ], - "name" : "Config", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { + ], + "returnType" : { + "void" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "theme", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "direction", - "type" : { - "optional" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "abiName" : "bjs_DataProcessor_getLabel", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getLabel", + "parameters" : [ + + ], + "returnType" : { + "string" : { + } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - } - ], - "swiftCallName" : "Config" - }, - { - "methods" : [ + "abiName" : "bjs_DataProcessor_isEven", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "isEven", + "parameters" : [ - ], - "name" : "SessionData", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "id", - "type" : { - "int" : { + ], + "returnType" : { + "bool" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "owner", - "type" : { - "optional" : { - "_0" : { + "abiName" : "bjs_DataProcessor_processGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processGreeter", + "parameters" : [ + { + "label" : "_", + "name" : "greeter", + "type" : { "swiftHeapObject" : { "_0" : "Greeter" } } } - } - } - ], - "swiftCallName" : "SessionData" - }, - { - "methods" : [ + ], + "returnType" : { + "string" : { - ], - "name" : "ValidationReport", - "properties" : [ + } + } + }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "id", - "type" : { - "int" : { + "abiName" : "bjs_DataProcessor_createGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createGreeter", + "parameters" : [ + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "result", + "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" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_createOptionalGreeter", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "createOptionalGreeter", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + }, + { + "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" : { + + } + } + }, + { + "abiName" : "bjs_DataProcessor_getAPIResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getAPIResult", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "DataProcessor", + "properties" : [ + { + "isReadonly" : false, + "name" : "count", "type" : { - "associatedValueEnum" : { - "_0" : "APIResult" + "int" : { + } } }, { "isReadonly" : true, - "isStatic" : false, - "name" : "status", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : false, + "name" : "optionalTag", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "optionalCount", "type" : { - "optional" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : false, + "name" : "direction", + "type" : { + "nullable" : { "_0" : { "caseEnum" : { - "_0" : "Status" + "_0" : "Direction" } - } + }, + "_1" : "null" } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "outcome", + "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" : { - "optional" : { + "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" } } } + ] + } + ], + "structs" : [ + { + "methods" : [ + ], - "swiftCallName" : "ValidationReport" + "name" : "Point", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "Point" }, { - "methods" : [ + "constructor" : { + "abiName" : "bjs_PointerFields_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "raw", + "name" : "raw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "label" : "mutRaw", + "name" : "mutRaw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "label" : "opaque", + "name" : "opaque", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "label" : "ptr", + "name" : "ptr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "label" : "mutPtr", + "name" : "mutPtr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "PointerFields", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "raw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "mutRaw", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "opaque", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "ptr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "mutPtr", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "swiftCallName" : "PointerFields" + }, + { + "constructor" : { + "abiName" : "bjs_DataPoint_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + }, + { + "label" : "optCount", + "name" : "optCount", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "label" : "optFlag", + "name" : "optFlag", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "DataPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optCount", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optFlag", + "type" : { + "nullable" : { + "_0" : { + "bool" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "DataPoint" + }, + { + "constructor" : { + "abiName" : "bjs_PublicPoint_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "int" : { + + } + } + } + ] + }, + "explicitAccessControl" : "public", + "methods" : [ + + ], + "name" : "PublicPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "PublicPoint" + }, + { + "methods" : [ + + ], + "name" : "Address", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "street", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "city", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "zipCode", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Address" + }, + { + "methods" : [ + + ], + "name" : "Contact", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "age", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "address", + "type" : { + "swiftStruct" : { + "_0" : "Address" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "email", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "secondaryAddress", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Address" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "Contact" + }, + { + "methods" : [ + + ], + "name" : "Config", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "theme", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "direction", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + } + ], + "swiftCallName" : "Config" + }, + { + "methods" : [ + + ], + "name" : "SessionData", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "owner", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "SessionData" + }, + { + "methods" : [ + + ], + "name" : "ValidationReport", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "result", + "type" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "status", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Status" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "outcome", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ValidationReport" + }, + { + "methods" : [ + + ], + "name" : "AdvancedConfig", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "title", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "enabled", + "type" : { + "bool" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "status", + "type" : { + "caseEnum" : { + "_0" : "Status" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "result", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "metadata", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "location", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "defaults", + "type" : { + "swiftStruct" : { + "_0" : "ConfigStruct" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "overrideDefaults", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "ConfigStruct" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "AdvancedConfig" + }, + { + "methods" : [ + + ], + "name" : "MeasurementConfig", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "precision", + "type" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "ratio", + "type" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalPrecision", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Precision", + "_1" : "Float" + } + }, + "_1" : "null" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalRatio", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Ratio", + "_1" : "Double" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "MeasurementConfig" + }, + { + "constructor" : { + "abiName" : "bjs_MathOperations_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "defaultValue" : { + "double" : { + "_0" : 0 + } + }, + "label" : "baseValue", + "name" : "baseValue", + "type" : { + "double" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_MathOperations_add", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "add", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "defaultValue" : { + "double" : { + "_0" : 10 + } + }, + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_MathOperations_multiply", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "multiply", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_MathOperations_static_subtract", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "subtract", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "double" : { + + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + }, + "staticContext" : { + "structName" : { + "_0" : "MathOperations" + } + } + } + ], + "name" : "MathOperations", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "baseValue", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "MathOperations" + }, + { + "methods" : [ + { + "abiName" : "bjs_CopyableCart_static_fromJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "fromJSObject", + "parameters" : [ + { + "label" : "_", + "name" : "object", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "CopyableCart" + } + }, + "staticContext" : { + "structName" : { + "_0" : "CopyableCart" + } + } + } + ], + "name" : "CopyableCart", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "note", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "CopyableCart" + }, + { + "methods" : [ + + ], + "name" : "CopyableCartItem", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "sku", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "quantity", + "type" : { + "int" : { + + } + } + } + ], + "swiftCallName" : "CopyableCartItem" + }, + { + "methods" : [ + { + "abiName" : "bjs_CopyableNestedCart_static_fromJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "fromJSObject", + "parameters" : [ + { + "label" : "_", + "name" : "object", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "CopyableNestedCart" + } + }, + "staticContext" : { + "structName" : { + "_0" : "CopyableNestedCart" + } + } + } + ], + "name" : "CopyableNestedCart", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "id", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "item", + "type" : { + "swiftStruct" : { + "_0" : "CopyableCartItem" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "shippingAddress", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Address" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "CopyableNestedCart" + }, + { + "methods" : [ + + ], + "name" : "ConfigStruct", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "value", + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "defaultConfig", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "maxRetries", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "int" : { + + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "name" : "timeout", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "computedSetting", + "staticContext" : { + "structName" : { + "_0" : "ConfigStruct" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "ConfigStruct" + }, + { + "methods" : [ + + ], + "name" : "JSObjectContainer", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "object", + "type" : { + "jsObject" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalObject", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "JSObjectContainer" + }, + { + "methods" : [ + + ], + "name" : "FooContainer", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "foo", + "type" : { + "jsObject" : { + "_0" : "Foo" + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optionalFoo", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "FooContainer" + }, + { + "methods" : [ + { + "abiName" : "bjs_ArrayMembers_sumValues", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "sumValues", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "abiName" : "bjs_ArrayMembers_firstString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "firstString", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "ArrayMembers", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "ints", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optStrings", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ArrayMembers" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureSupportImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "name" : "jsApplyVoid", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "name" : "jsApplyBool", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_Sb", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "name" : "jsApplyInt", + "parameters" : [ + { + "name" : "value", + "type" : { + "int" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "name" : "jsApplyDouble", + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "name" : "jsApplyString", + "parameters" : [ + { + "name" : "value", + "type" : { + "string" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "name" : "jsApplyJSObject", + "parameters" : [ + { + "name" : "value", + "type" : { + "jsObject" : { + + } + } + }, + { + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests8JSObjectC_8JSObjectC", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "jsObject" : { + + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "name" : "jsMakeIntToInt", + "parameters" : [ + { + "name" : "base", + "type" : { + "int" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "name" : "jsMakeDoubleToDouble", + "parameters" : [ + { + "name" : "base", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSd_Sd", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "name" : "jsMakeStringToString", + "parameters" : [ + { + "name" : "prefix", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + "useJSTypedClosure" : false + } + } + }, + { + "name" : "jsCallTwice", + "parameters" : [ + { + "name" : "value", + "type" : { + "int" : { + + } + } + }, + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSi_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "name" : "jsCallBinary", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSiSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + }, + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "name" : "jsCallTriple", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsSiSiSi_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "int" : { + + } + }, + { + "int" : { + + } + }, + { + "int" : { + + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "int" : { + + } + } + }, + { + "name" : "jsCallAfterRelease", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "name" : "jsOptionalInvoke", + "parameters" : [ + { + "name" : "callback", + "type" : { + "nullable" : { + "_0" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_Sb", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + "useJSTypedClosure" : true + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "bool" : { - ], - "name" : "AdvancedConfig", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "id", - "type" : { - "int" : { + } + } + }, + { + "name" : "jsStoreClosure", + "parameters" : [ + { + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsy_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "title", - "type" : { - "string" : { + ], + "returnType" : { + "void" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "enabled", - "type" : { - "bool" : { + } + } + }, + "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "void" : { - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "theme", - "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "status", - "type" : { - "caseEnum" : { - "_0" : "Status" - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "result", - "type" : { - "optional" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "APIResult" } } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "metadata", - "type" : { - "optional" : { - "_0" : { - "jsObject" : { + }, + { + "name" : "jsCallStoredClosure", + "parameters" : [ + + ], + "returnType" : { + "void" : { } } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "location", - "type" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "DataPoint" + }, + { + "name" : "jsHeapCount", + "parameters" : [ + + ], + "returnType" : { + "int" : { + } } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "defaults", - "type" : { - "swiftStruct" : { - "_0" : "ConfigStruct" - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "overrideDefaults", - "type" : { - "optional" : { - "_0" : { - "swiftStruct" : { - "_0" : "ConfigStruct" + }, + { + "name" : "runJsClosureSupportTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + } } } - } + ] } - ], - "swiftCallName" : "AdvancedConfig" + ] }, { - "methods" : [ - - ], - "name" : "MeasurementConfig", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "precision", - "type" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" - } - } - }, + "functions" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "ratio", - "type" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" + "name" : "jsRoundTripDictionary", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "int" : { + + } + } + } + } } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "optionalPrecision", - "type" : { - "optional" : { + ], + "returnType" : { + "dictionary" : { "_0" : { - "rawValueEnum" : { - "_0" : "Precision", - "_1" : "Float" + "int" : { + } } } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "optionalRatio", - "type" : { - "optional" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Ratio", - "_1" : "Double" + "name" : "jsRoundTripDictionaryBool", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "bool" : { + + } + } } } } - } - } - ], - "swiftCallName" : "MeasurementConfig" - }, - { - "constructor" : { - "abiName" : "bjs_MathOperations_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "defaultValue" : { - "double" : { - "_0" : 0 - } - }, - "label" : "baseValue", - "name" : "baseValue", - "type" : { - "double" : { + ], + "returnType" : { + "dictionary" : { + "_0" : { + "bool" : { + } } } } - ] - }, - "methods" : [ + }, { - "abiName" : "bjs_MathOperations_add", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "add", + "name" : "jsRoundTripDictionaryDouble", "parameters" : [ { - "label" : "a", - "name" : "a", + "name" : "values", "type" : { + "dictionary" : { + "_0" : { + "double" : { + + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { "double" : { } } - }, + } + } + }, + { + "name" : "jsRoundTripDictionaryJSObject", + "parameters" : [ { - "defaultValue" : { - "double" : { - "_0" : 10 - } - }, - "label" : "b", - "name" : "b", + "name" : "values", "type" : { - "double" : { + "dictionary" : { + "_0" : { + "jsObject" : { + } + } } } } ], "returnType" : { - "double" : { + "dictionary" : { + "_0" : { + "jsObject" : { + } + } } } }, { - "abiName" : "bjs_MathOperations_multiply", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "multiply", + "name" : "jsRoundTripDictionaryJSValue", "parameters" : [ { - "label" : "a", - "name" : "a", + "name" : "values", "type" : { - "double" : { + "dictionary" : { + "_0" : { + "jsValue" : { + } + } } } - }, + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "jsValue" : { + + } + } + } + } + }, + { + "name" : "jsRoundTripNestedDictionary", + "parameters" : [ { - "label" : "b", - "name" : "b", + "name" : "values", "type" : { - "double" : { + "dictionary" : { + "_0" : { + "array" : { + "_0" : { + "double" : { + } + } + } + } } } } ], "returnType" : { - "double" : { + "dictionary" : { + "_0" : { + "array" : { + "_0" : { + "double" : { + } + } + } + } } } }, { - "abiName" : "bjs_MathOperations_static_subtract", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "subtract", + "name" : "jsRoundTripOptionalDictionary", "parameters" : [ { - "label" : "a", - "name" : "a", + "name" : "values", "type" : { - "double" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } - }, + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "jsRoundTripUndefinedDictionary", + "parameters" : [ { - "label" : "b", - "name" : "b", + "name" : "values", "type" : { - "double" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "int" : { + } + } + } + }, + "_1" : "undefined" } } } ], "returnType" : { - "double" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "int" : { - } - }, - "staticContext" : { - "structName" : { - "_0" : "MathOperations" + } + } + } + }, + "_1" : "undefined" } } } ], - "name" : "MathOperations", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "baseValue", - "type" : { - "double" : { + "types" : [ - } - } - } - ], - "swiftCallName" : "MathOperations" + ] }, { - "methods" : [ + "functions" : [ + + ], + "types" : [ { - "abiName" : "bjs_CopyableCart_static_fromJSObject", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false + "constructor" : { + "parameters" : [ + { + "name" : "value", + "type" : { + "string" : { + + } + } + } + ] }, - "name" : "fromJSObject", - "parameters" : [ + "getters" : [ { - "label" : "_", - "name" : "object", + "name" : "value", "type" : { - "jsObject" : { + "string" : { } } } ], - "returnType" : { - "swiftStruct" : { - "_0" : "CopyableCart" - } - }, - "staticContext" : { - "structName" : { - "_0" : "CopyableCart" - } - } + "methods" : [ + + ], + "name" : "Foo", + "setters" : [ + + ], + "staticMethods" : [ + + ] } - ], - "name" : "CopyableCart", - "properties" : [ + ] + }, + { + "functions" : [ { - "isReadonly" : true, - "isStatic" : false, - "name" : "x", - "type" : { - "int" : { + "name" : "jsRoundTripVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "note", - "type" : { - "optional" : { - "_0" : { - "string" : { + "name" : "jsRoundTripNumber", + "parameters" : [ + { + "name" : "v", + "type" : { + "double" : { } } } - } - } - ], - "swiftCallName" : "CopyableCart" - }, - { - "methods" : [ + ], + "returnType" : { + "double" : { - ], - "name" : "CopyableCartItem", - "properties" : [ + } + } + }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "sku", - "type" : { - "string" : { + "name" : "jsRoundTripBool", + "parameters" : [ + { + "name" : "v", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "bool" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "quantity", - "type" : { - "int" : { + "name" : "jsRoundTripString", + "parameters" : [ + { + "name" : "v", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { } } - } - ], - "swiftCallName" : "CopyableCartItem" - }, - { - "methods" : [ + }, { - "abiName" : "bjs_CopyableNestedCart_static_fromJSObject", - "effects" : { - "isAsync" : false, - "isStatic" : true, - "isThrows" : false - }, - "name" : "fromJSObject", + "name" : "jsRoundTripJSValue", "parameters" : [ { - "label" : "_", - "name" : "object", + "name" : "v", "type" : { - "jsObject" : { + "jsValue" : { } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "CopyableNestedCart" - } - }, - "staticContext" : { - "structName" : { - "_0" : "CopyableNestedCart" - } - } - } - ], - "name" : "CopyableNestedCart", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "id", - "type" : { - "int" : { + "jsValue" : { } } }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "item", - "type" : { - "swiftStruct" : { - "_0" : "CopyableCartItem" + "name" : "jsRoundTripJSValueArray", + "parameters" : [ + { + "name" : "v", + "type" : { + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + } } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "shippingAddress", - "type" : { - "optional" : { + ], + "returnType" : { + "array" : { "_0" : { - "swiftStruct" : { - "_0" : "Address" + "jsValue" : { + } } } } - } - ], - "swiftCallName" : "CopyableNestedCart" - }, - { - "methods" : [ - - ], - "name" : "ConfigStruct", - "properties" : [ + }, { - "isReadonly" : true, - "isStatic" : false, - "name" : "name", - "type" : { - "string" : { + "name" : "jsRoundTripOptionalJSValueArray", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" + } + } } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "value", - "type" : { - "int" : { + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" } } }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "defaultConfig", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" + "name" : "jsThrowOrVoid", + "parameters" : [ + { + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } } - }, - "type" : { - "string" : { + ], + "returnType" : { + "void" : { } } }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "maxRetries", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" + "name" : "jsThrowOrNumber", + "parameters" : [ + { + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } } - }, - "type" : { - "int" : { + ], + "returnType" : { + "double" : { } } }, { - "isReadonly" : false, - "isStatic" : true, - "name" : "timeout", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" + "name" : "jsThrowOrBool", + "parameters" : [ + { + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } } - }, - "type" : { - "double" : { + ], + "returnType" : { + "bool" : { } } }, { - "isReadonly" : true, - "isStatic" : true, - "name" : "computedSetting", - "staticContext" : { - "structName" : { - "_0" : "ConfigStruct" + "name" : "jsThrowOrString", + "parameters" : [ + { + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } } - }, - "type" : { + ], + "returnType" : { "string" : { } } - } - ], - "swiftCallName" : "ConfigStruct" - } - ] - }, - "imported" : { - "children" : [ - { - "functions" : [ - - ], - "types" : [ + }, { - "constructor" : { - "parameters" : [ - { - "name" : "value", - "type" : { - "string" : { - - } - } - } - ] - }, - "getters" : [ + "name" : "jsRoundTripFeatureFlag", + "parameters" : [ { - "name" : "value", + "name" : "flag", "type" : { - "string" : { - + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" } } } ], - "methods" : [ + "returnType" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + }, + { + "name" : "runAsyncWorks", + "parameters" : [ ], - "name" : "Foo", - "setters" : [ - - ] - } - ] - }, - { - "functions" : [ + "returnType" : { + "jsObject" : { + "_0" : "JSPromise" + } + } + }, { - "name" : "jsRoundTripVoid", + "jsName" : "$jsWeirdFunction", + "name" : "_jsWeirdFunction", "parameters" : [ ], "returnType" : { - "void" : { + "double" : { } } }, { - "name" : "jsRoundTripNumber", + "name" : "jsRoundTripNumberArray", "parameters" : [ { - "name" : "v", + "name" : "values", "type" : { - "double" : { + "array" : { + "_0" : { + "double" : { + } + } } } } ], "returnType" : { - "double" : { + "array" : { + "_0" : { + "double" : { + } + } } } }, { - "name" : "jsRoundTripBool", + "name" : "jsRoundTripStringArray", "parameters" : [ { - "name" : "v", + "name" : "values", "type" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } ], "returnType" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } }, { - "name" : "jsRoundTripString", + "name" : "jsRoundTripBoolArray", "parameters" : [ { - "name" : "v", + "name" : "values", "type" : { - "string" : { + "array" : { + "_0" : { + "bool" : { + } + } } } } ], "returnType" : { - "string" : { + "array" : { + "_0" : { + "bool" : { + } + } } } }, { - "name" : "jsThrowOrVoid", + "name" : "jsSumNumberArray", "parameters" : [ { - "name" : "shouldThrow", + "name" : "values", "type" : { - "bool" : { + "array" : { + "_0" : { + "double" : { + } + } } } } ], "returnType" : { - "void" : { + "double" : { } } }, { - "name" : "jsThrowOrNumber", + "name" : "jsCreateNumberArray", "parameters" : [ - { - "name" : "shouldThrow", - "type" : { - "bool" : { - } - } - } ], "returnType" : { - "double" : { + "array" : { + "_0" : { + "double" : { + } + } } } }, { - "name" : "jsThrowOrBool", + "from" : "global", + "name" : "parseInt", "parameters" : [ { - "name" : "shouldThrow", + "name" : "string", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "bool" : { + "double" : { } } - }, + } + ], + "globalGetters" : [ { - "name" : "jsThrowOrString", - "parameters" : [ + "from" : "global", + "name" : "globalObject1", + "type" : { + "jsValue" : { + + } + } + } + ], + "types" : [ + { + "constructor" : { + "parameters" : [ + { + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "name" : "prefix", + "type" : { + "string" : { + + } + } + } + ] + }, + "getters" : [ { - "name" : "shouldThrow", + "name" : "name", "type" : { - "bool" : { + "string" : { + + } + } + }, + { + "name" : "prefix", + "type" : { + "string" : { } } } ], - "returnType" : { - "string" : { + "methods" : [ + { + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "name" : "changeName", + "parameters" : [ + { + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "void" : { + } + } } - } - }, - { - "name" : "jsRoundTripFeatureFlag", - "parameters" : [ + ], + "name" : "JsGreeter", + "setters" : [ { - "name" : "flag", + "functionName" : "name_set", + "name" : "name", "type" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" + "string" : { + } } } ], - "returnType" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" + "staticMethods" : [ + + ] + }, + { + "constructor" : { + "parameters" : [ + + ] + }, + "getters" : [ + + ], + "jsName" : "$WeirdClass", + "methods" : [ + { + "jsName" : "method-with-dashes", + "name" : "method_with_dashes", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } } - } + ], + "name" : "_WeirdClass", + "setters" : [ + + ], + "staticMethods" : [ + + ] }, { - "name" : "runAsyncWorks", - "parameters" : [ + "constructor" : { + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { + + } + } + } + ] + }, + "getters" : [ ], - "returnType" : { - "jsObject" : { - "_0" : "JSPromise" + "methods" : [ + { + "name" : "value", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } } - } - }, - { - "jsName" : "$jsWeirdFunction", - "name" : "_jsWeirdFunction", - "parameters" : [ + ], + "name" : "StaticBox", + "setters" : [ ], - "returnType" : { - "double" : { + "staticMethods" : [ + { + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "double" : { - } - } - }, - { - "from" : "global", - "name" : "parseInt", - "parameters" : [ + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } + }, { - "name" : "string", - "type" : { - "string" : { + "name" : "value", + "parameters" : [ + + ], + "returnType" : { + "double" : { } } - } - ], - "returnType" : { - "double" : { + }, + { + "name" : "makeDefault", + "parameters" : [ - } - } - } - ], - "globalGetters" : [ - { - "from" : "global", - "name" : "globalObject1", - "type" : { - "jsObject" : { + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } + }, + { + "jsName" : "with-dashes", + "name" : "with_dashes", + "parameters" : [ + ], + "returnType" : { + "jsObject" : { + "_0" : "StaticBox" + } + } } - } - } - ], - "types" : [ + ] + }, { "constructor" : { "parameters" : [ @@ -11383,15 +14897,24 @@ } }, { - "name" : "prefix", + "name" : "age", "type" : { - "string" : { + "double" : { + + } + } + }, + { + "name" : "isCat", + "type" : { + "bool" : { } } } ] }, + "from" : "global", "getters" : [ { "name" : "name", @@ -11402,9 +14925,17 @@ } }, { - "name" : "prefix", + "name" : "age", "type" : { - "string" : { + "double" : { + + } + } + }, + { + "name" : "isCat", + "type" : { + "bool" : { } } @@ -11412,7 +14943,7 @@ ], "methods" : [ { - "name" : "greet", + "name" : "bark", "parameters" : [ ], @@ -11423,25 +14954,18 @@ } }, { - "name" : "changeName", + "name" : "getIsCat", "parameters" : [ - { - "name" : "name", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "void" : { + "bool" : { } } } ], - "name" : "JsGreeter", + "name" : "Animal", "setters" : [ { "functionName" : "name_set", @@ -11449,176 +14973,301 @@ "type" : { "string" : { + } + } + }, + { + "functionName" : "age_set", + "name" : "age", + "type" : { + "double" : { + + } + } + }, + { + "functionName" : "isCat_set", + "name" : "isCat", + "type" : { + "bool" : { + } } } + ], + "staticMethods" : [ + ] - }, + } + ] + }, + { + "functions" : [ { - "constructor" : { - "parameters" : [ - - ] - }, - "getters" : [ + "name" : "jsRoundTripIntArray", + "parameters" : [ + { + "name" : "items", + "type" : { + "array" : { + "_0" : { + "int" : { + } + } + } + } + } ], - "jsName" : "$WeirdClass", - "methods" : [ - { - "jsName" : "method-with-dashes", - "name" : "method_with_dashes", - "parameters" : [ + "returnType" : { + "array" : { + "_0" : { + "int" : { - ], - "returnType" : { - "string" : { + } + } + } + } + }, + { + "name" : "jsArrayLength", + "parameters" : [ + { + "name" : "items", + "type" : { + "array" : { + "_0" : { + "int" : { + } + } } } } ], - "name" : "_WeirdClass", - "setters" : [ + "returnType" : { + "int" : { - ] + } + } }, { - "constructor" : { - "parameters" : [ - { - "name" : "name", - "type" : { - "string" : { + "name" : "makeArrayHost", + "parameters" : [ + { + "name" : "numbers", + "type" : { + "array" : { + "_0" : { + "int" : { + + } + } + } + } + }, + { + "name" : "labels", + "type" : { + "array" : { + "_0" : { + "string" : { + } } } - }, + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "ArrayHost" + } + } + } + ], + "types" : [ + { + "constructor" : { + "parameters" : [ { - "name" : "age", + "name" : "numbers", "type" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { - "name" : "isCat", + "name" : "labels", "type" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } ] }, - "from" : "global", "getters" : [ { - "name" : "name", - "type" : { - "string" : { - - } - } - }, - { - "name" : "age", + "name" : "numbers", "type" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { - "name" : "isCat", + "name" : "labels", "type" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } ], "methods" : [ { - "name" : "bark", + "name" : "concatNumbers", "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "int" : { + } + } + } + } + } ], "returnType" : { - "string" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { - "name" : "getIsCat", + "name" : "concatLabels", "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + } + } + } + } + } ], "returnType" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } - } - ], - "name" : "Animal", - "setters" : [ + }, { - "functionName" : "name_set", - "name" : "name", - "type" : { + "name" : "firstLabel", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { "string" : { } } - }, + } + ], + "name" : "ArrayHost", + "setters" : [ { - "functionName" : "age_set", - "name" : "age", + "functionName" : "numbers_set", + "name" : "numbers", "type" : { - "double" : { + "array" : { + "_0" : { + "int" : { + } + } } } }, { - "functionName" : "isCat_set", - "name" : "isCat", + "functionName" : "labels_set", + "name" : "labels", "type" : { - "bool" : { + "array" : { + "_0" : { + "string" : { + } + } } } } + ], + "staticMethods" : [ + ] } ] }, - { - "functions" : [ - - ], - "types" : [ - - ] - }, - { - "functions" : [ - - ], - "types" : [ - - ] - }, { "functions" : [ { - "name" : "jsApplyInt", + "name" : "jsTranslatePoint", "parameters" : [ { - "name" : "value", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "Point" + } + } + }, + { + "name" : "dx", "type" : { "int" : { @@ -11626,189 +15275,148 @@ } }, { - "name" : "transform", + "name" : "dy", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "int" : { - - } - } - ], - "returnType" : { - "int" : { + "int" : { - } - } - } } } } ], "returnType" : { - "int" : { - + "swiftStruct" : { + "_0" : "Point" } } + } + ], + "types" : [ + + ] + }, + { + "functions" : [ + + ], + "types" : [ + { + "constructor" : { + "parameters" : [ + + ] + }, + "from" : "global", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "MyJSClassInternal", + "setters" : [ + + ], + "staticMethods" : [ + + ] }, { - "name" : "jsMakeAdder", - "parameters" : [ - { - "name" : "base", - "type" : { - "int" : { + "constructor" : { + "parameters" : [ + + ] + }, + "from" : "global", + "getters" : [ - } - } - } ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "int" : { + "methods" : [ - } - } - ], - "returnType" : { - "int" : { + ], + "name" : "MyJSClassPublic", + "setters" : [ - } - } - } - } - } + ], + "staticMethods" : [ + + ] }, { - "name" : "jsMapString", - "parameters" : [ - { - "name" : "value", - "type" : { - "string" : { + "constructor" : { + "parameters" : [ - } - } - }, - { - "name" : "transform", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { + ] + }, + "from" : "global", + "getters" : [ - } - } - ], - "returnType" : { - "string" : { + ], + "methods" : [ + + ], + "name" : "MyJSClassPackage", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + }, + { + "functions" : [ + { + "name" : "jsFunctionWithPackageAccess", + "parameters" : [ + + ], + "returnType" : { + "void" : { - } - } - } - } - } } + } + }, + { + "name" : "jsFunctionWithPublicAccess", + "parameters" : [ + ], "returnType" : { - "string" : { + "void" : { } } }, { - "name" : "jsMakePrefixer", + "name" : "jsFunctionWithInternalAccess", "parameters" : [ - { - "name" : "prefix", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { + "void" : { - } - } - } } } }, { - "name" : "jsCallTwice", + "name" : "jsFunctionWithFilePrivateAccess", "parameters" : [ - { - "name" : "value", - "type" : { - "int" : { - - } - } - }, - { - "name" : "callback", - "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsSi_y", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "int" : { - } - } - ], - "returnType" : { - "void" : { + ], + "returnType" : { + "void" : { - } - } - } - } - } } + } + }, + { + "name" : "jsFunctionWithPrivateAccess", + "parameters" : [ + ], "returnType" : { - "int" : { + "void" : { } } @@ -11820,59 +15428,224 @@ }, { "functions" : [ + + ], + "types" : [ { - "name" : "jsTranslatePoint", - "parameters" : [ + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "OptionalSupportImports", + "setters" : [ + + ], + "staticMethods" : [ { - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "Point" + "name" : "jsRoundTripOptionalNumberNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "null" } } }, { - "name" : "dx", - "type" : { - "int" : { + "name" : "jsRoundTripOptionalNumberUndefined", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "int" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "int" : { + } + }, + "_1" : "undefined" } } }, { - "name" : "dy", - "type" : { - "int" : { + "name" : "jsRoundTripOptionalStringNull", + "parameters" : [ + { + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + }, + { + "name" : "jsRoundTripOptionalStringUndefined", + "parameters" : [ + { + "name" : "name", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "undefined" + } + } + }, + { + "name" : "runJsOptionalSupportTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { } } } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "Point" - } - } + ] } - ], - "types" : [ - ] }, { "functions" : [ + { + "from" : "global", + "name" : "gc", + "parameters" : [ + + ], + "returnType" : { + "void" : { + } + } + } ], "types" : [ + { + "getters" : [ - ] - }, - { - "functions" : [ + ], + "methods" : [ - ], - "types" : [ + ], + "name" : "SwiftClassSupportImports", + "setters" : [ + ], + "staticMethods" : [ + { + "name" : "jsRoundTripGreeter", + "parameters" : [ + { + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "name" : "jsRoundTripOptionalGreeter", + "parameters" : [ + { + "name" : "greeter", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ] + } ] } ] diff --git a/Tests/BridgeJSRuntimeTests/GlobalThisImportTests.swift b/Tests/BridgeJSRuntimeTests/GlobalThisImportTests.swift index 2f6251341..fdd22401d 100644 --- a/Tests/BridgeJSRuntimeTests/GlobalThisImportTests.swift +++ b/Tests/BridgeJSRuntimeTests/GlobalThisImportTests.swift @@ -13,7 +13,11 @@ final class GlobalThisImportTests: XCTestCase { } func testGlobalGetterImport() throws { - let value = try globalObject1["prop_2"].number + guard let object = try globalObject1.object else { + XCTFail("globalObject1 was not an object") + return + } + let value = object[dynamicMember: "prop_2"].number XCTAssertEqual(value, 2) } } diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index ea9f8c68f..fa97c3197 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -35,6 +35,50 @@ class ImportAPITests: XCTestCase { } } + func testRoundTripJSValue() throws { + let symbol = JSSymbol("roundTrip") + let bigInt = JSBigInt(_slowBridge: Int64(123456789)) + let values: [JSValue] = [ + .boolean(true), + .number(42), + .string(JSString("hello")), + .object(JSObject.global), + .null, + .undefined, + .symbol(symbol), + .bigInt(bigInt), + ] + for value in values { + try XCTAssertEqual(jsRoundTripJSValue(value), value) + } + } + + func testRoundTripJSValueArray() throws { + let object = JSObject.global + let symbol = JSSymbol("array") + let bigInt = JSBigInt(_slowBridge: Int64(42)) + let values: [JSValue] = [ + .boolean(false), + .number(123.5), + .string(JSString("hello")), + .object(object), + .null, + .undefined, + .symbol(symbol), + .bigInt(bigInt), + ] + let roundTripped = try jsRoundTripJSValueArray(values) + XCTAssertEqual(roundTripped, values) + XCTAssertEqual(try jsRoundTripJSValueArray([]), []) + } + + func testRoundTripOptionalJSValueArray() throws { + XCTAssertNil(try jsRoundTripOptionalJSValueArray(nil)) + let values: [JSValue] = [.number(1), .undefined, .null] + let result = try jsRoundTripOptionalJSValueArray(values) + XCTAssertEqual(result, values) + } + func testRoundTripFeatureFlag() throws { for v in [FeatureFlag.foo, .bar] { try XCTAssertEqual(jsRoundTripFeatureFlag(v), v) @@ -91,34 +135,31 @@ class ImportAPITests: XCTestCase { XCTAssertEqual(try greeter.prefix, "Hello") } - func testClosureParameterIntToInt() throws { - let result = try jsApplyInt(21) { $0 * 2 } - XCTAssertEqual(result, 42) + func testRoundTripIntArray() throws { + let values = [1, 2, 3, 4, 5] + let result = try jsRoundTripIntArray(values) + XCTAssertEqual(result, values) + XCTAssertEqual(try jsArrayLength(values), values.count) + XCTAssertEqual(try jsRoundTripIntArray([]), []) } - func testClosureReturnIntToInt() throws { - let add10 = try jsMakeAdder(10) - XCTAssertEqual(add10(0), 10) - XCTAssertEqual(add10(32), 42) - } + func testJSClassArrayMembers() throws { + let numbers = [1, 2, 3] + let labels = ["alpha", "beta"] + let host = try makeArrayHost(numbers, labels) - func testClosureParameterStringToString() throws { - let result = try jsMapString("Hello") { value in - value + ", world!" - } - XCTAssertEqual(result, "Hello, world!") - } + XCTAssertEqual(try host.numbers, numbers) + XCTAssertEqual(try host.labels, labels) - func testClosureReturnStringToString() throws { - let prefixer = try jsMakePrefixer("Hello, ") - XCTAssertEqual(prefixer("world!"), "Hello, world!") - } + try host.setNumbers([10, 20]) + try host.setLabels(["gamma"]) + XCTAssertEqual(try host.numbers, [10, 20]) + XCTAssertEqual(try host.labels, ["gamma"]) - func testClosureParameterIntToVoid() throws { - var total = 0 - let ret = try jsCallTwice(5) { total += $0 } - XCTAssertEqual(ret, 5) - XCTAssertEqual(total, 10) + XCTAssertEqual(try host.concatNumbers([30, 40]), [10, 20, 30, 40]) + XCTAssertEqual(try host.concatLabels(["delta", "epsilon"]), ["gamma", "delta", "epsilon"]) + XCTAssertEqual(try host.firstLabel([]), "gamma") + XCTAssertEqual(try host.firstLabel(["zeta"]), "zeta") } func testJSNameFunctionAndClass() throws { @@ -127,4 +168,51 @@ class ImportAPITests: XCTestCase { let obj = try _WeirdClass() XCTAssertEqual(try obj.method_with_dashes(), "ok") } + + func testJSClassStaticFunctions() throws { + let created = try StaticBox.create(10) + XCTAssertEqual(try created.value(), 10) + + let defaultBox = try StaticBox.makeDefault() + XCTAssertEqual(try defaultBox.value(), 0) + + XCTAssertEqual(try StaticBox.value(), 99) + + let dashed = try StaticBox.with_dashes() + XCTAssertEqual(try dashed.value(), 7) + } + + func testRoundTripNumberArray() throws { + let input: [Double] = [1.0, 2.5, 3.0, -4.5] + let result = try jsRoundTripNumberArray(input) + XCTAssertEqual(result, input) + XCTAssertEqual(try jsRoundTripNumberArray([]), []) + XCTAssertEqual(try jsRoundTripNumberArray([42.0]), [42.0]) + } + + func testRoundTripStringArray() throws { + let input = ["Hello", "World", "🎉"] + let result = try jsRoundTripStringArray(input) + XCTAssertEqual(result, input) + XCTAssertEqual(try jsRoundTripStringArray([]), []) + XCTAssertEqual(try jsRoundTripStringArray(["", "a", ""]), ["", "a", ""]) + } + + func testRoundTripBoolArray() throws { + let input = [true, false, true, false] + let result = try jsRoundTripBoolArray(input) + XCTAssertEqual(result, input) + XCTAssertEqual(try jsRoundTripBoolArray([]), []) + } + + func testSumNumberArray() throws { + XCTAssertEqual(try jsSumNumberArray([1.0, 2.0, 3.0, 4.0]), 10.0) + XCTAssertEqual(try jsSumNumberArray([]), 0.0) + XCTAssertEqual(try jsSumNumberArray([42.0]), 42.0) + } + + func testCreateNumberArray() throws { + let result = try jsCreateNumberArray() + XCTAssertEqual(result, [1.0, 2.0, 3.0, 4.0, 5.0]) + } } diff --git a/Tests/BridgeJSRuntimeTests/ImportArrayAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportArrayAPIs.swift new file mode 100644 index 000000000..104304d5b --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ImportArrayAPIs.swift @@ -0,0 +1,17 @@ +@_spi(BridgeJS) import JavaScriptKit + +@JSFunction func jsRoundTripIntArray(_ items: [Int]) throws(JSException) -> [Int] +@JSFunction func jsArrayLength(_ items: [Int]) throws(JSException) -> Int + +@JSClass struct ArrayHost { + @JSGetter var numbers: [Int] + @JSGetter var labels: [String] + @JSSetter func setNumbers(_ value: [Int]) throws(JSException) + @JSSetter func setLabels(_ value: [String]) throws(JSException) + @JSFunction init(_ numbers: [Int], _ labels: [String]) throws(JSException) + @JSFunction func concatNumbers(_ values: [Int]) throws(JSException) -> [Int] + @JSFunction func concatLabels(_ values: [String]) throws(JSException) -> [String] + @JSFunction func firstLabel(_ values: [String]) throws(JSException) -> String +} + +@JSFunction func makeArrayHost(_ numbers: [Int], _ labels: [String]) throws(JSException) -> ArrayHost diff --git a/Tests/BridgeJSRuntimeTests/ImportClosureAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportClosureAPIs.swift deleted file mode 100644 index bb913300b..000000000 --- a/Tests/BridgeJSRuntimeTests/ImportClosureAPIs.swift +++ /dev/null @@ -1,11 +0,0 @@ -@_spi(Experimental) import JavaScriptKit - -@JSFunction func jsApplyInt(_ value: Int, _ transform: @escaping (Int) -> Int) throws(JSException) -> Int - -@JSFunction func jsMakeAdder(_ base: Int) throws(JSException) -> (Int) -> Int - -@JSFunction func jsMapString(_ value: String, _ transform: @escaping (String) -> String) throws(JSException) -> String - -@JSFunction func jsMakePrefixer(_ `prefix`: String) throws(JSException) -> (String) -> String - -@JSFunction func jsCallTwice(_ value: Int, _ callback: @escaping (Int) -> Void) throws(JSException) -> Int diff --git a/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift index 82908701c..41929772e 100644 --- a/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift @@ -1,4 +1,4 @@ -@_spi(Experimental) import JavaScriptKit +import JavaScriptKit @JS struct Point { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs new file mode 100644 index 000000000..0d5560fae --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs @@ -0,0 +1,311 @@ +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["ClosureSupportImports"]} + */ +export function getImports(importsContext) { + return { + jsApplyVoid: (fn) => { + fn(); + }, + jsApplyBool: (fn) => { + return fn(); + }, + jsApplyInt: (v, fn) => { + return fn(v); + }, + jsApplyDouble: (v, fn) => { + return fn(v); + }, + jsApplyString: (v, fn) => { + return fn(v); + }, + jsApplyJSValue: (v, fn) => { + return fn(v); + }, + jsApplyJSObject: (v, fn) => { + return fn(v); + }, + jsApplyArrayInt: (v, fn) => { + return fn(v); + }, + jsApplyArrayDouble: (v, fn) => { + return fn(v); + }, + jsApplyArrayString: (v, fn) => { + return fn(v); + }, + jsApplyArrayJSValue: (v, fn) => { + return fn(v); + }, + jsApplyArrayJSObject: (v, fn) => { + return fn(v); + }, + jsMakeIntToInt: (base) => { + return (v) => base + v; + }, + jsMakeDoubleToDouble: (base) => { + return (v) => base + v; + }, + jsMakeStringToString: (prefix) => { + return (name) => `${prefix}${name}`; + }, + jsCallTwice: (v, fn) => { + fn(v); + fn(v); + return v; + }, + jsCallBinary: (fn) => fn(1, 2), + jsCallTriple: (fn) => fn(1, 2, 3), + jsCallTripleMut: (fn) => { + fn(1, 2, 3); + fn(4, 5, 6); + }, + jsCallTwiceMut: (fn) => { + fn(); + fn(); + }, + jsHeapCount: () => { + globalThis.gc?.(); + return globalThis.swift?.memory?._heapValueById?.size ?? -1; + }, + jsCallAfterRelease: (fn) => { + try { + fn(); + fn(); + return "null"; + } catch (e) { + return e?.message ?? "error"; + } + }, + jsOptionalInvoke: (fn) => { + if (fn == null) { return false; } + return fn(); + }, + jsStoreClosure: (fn) => { globalThis.__storedClosure = fn; }, + jsCallStoredClosure: () => { return globalThis.__storedClosure?.(); }, + + runJsClosureSupportTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsClosureSupportTests(exports); + }, + }; +} + +import assert from "node:assert"; + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export function runJsClosureSupportTests(exports) { + const upperTransform = (text) => text.toUpperCase(); + const processor = new exports.TextProcessor(upperTransform); + + assert.equal(processor.process("hello"), "HELLO"); + + const multiParamTransform = (count, text, ratio) => { + return `${text.toUpperCase()}-${count}-${ratio.toFixed(2)}`; + }; + assert.equal(processor.processWithCustom("world", multiParamTransform), "WORLD-42-3.14"); + assert.equal(processor.process("test"), "TEST"); + + const greeterForClosure = new exports.Greeter("World"); + const greeterCaller = new exports.Greeter("Caller"); + const customGreeting = (greeter) => `Custom greeting for ${greeter.name}: ${greeter.greet()}`; + const greetResult = greeterCaller.greetWith(greeterForClosure, customGreeting); + assert.equal(greetResult, "Custom greeting for World: Hello, World!"); + greeterForClosure.release(); + greeterCaller.release(); + + assert.equal(exports.formatName("ada", (name) => name.toUpperCase()), "ADA"); + assert.equal(exports.formatName("grace", (name) => `Dr. ${name}`), "Dr. grace"); + + const addDr = exports.makeFormatter("Dr."); + assert.equal(addDr("Ada"), "Dr. Ada"); + assert.equal(addDr("Grace"), "Dr. Grace"); + + const addProf = exports.makeFormatter("Prof."); + assert.equal(addProf("Hopper"), "Prof. Hopper"); + + const add10 = exports.makeAdder(10); + assert.equal(add10(5), 15); + assert.equal(add10(32), 42); + + const add100 = exports.makeAdder(100); + assert.equal(add100(23), 123); + + const storedTransform = processor.getTransform(); + assert.equal(storedTransform("hello"), "HELLO"); + assert.equal(storedTransform("world"), "WORLD"); + + const greeterForFormatter = new exports.Greeter("Formatter"); + const greeterFormatter = greeterForFormatter.makeFormatter(" [suffix]"); + assert.equal(greeterFormatter("test"), "Hello, Formatter! - test - [suffix]"); + assert.equal(greeterFormatter("data"), "Hello, Formatter! - data - [suffix]"); + greeterForFormatter.release(); + + const greeterCreator = exports.Greeter.makeCreator("Default"); + const createdG1 = greeterCreator("Alice"); + assert.equal(createdG1.name, "Alice"); + assert.equal(createdG1.greet(), "Hello, Alice!"); + const createdG2 = greeterCreator(""); + assert.equal(createdG2.name, "Default"); + assert.equal(createdG2.greet(), "Hello, Default!"); + createdG1.release(); + createdG2.release(); + + const greeterHost = new exports.Greeter("Host"); + const greeterGreeter = greeterHost.makeCustomGreeter(); + const guest1 = new exports.Greeter("Guest1"); + const guest2 = new exports.Greeter("Guest2"); + assert.equal(greeterGreeter(guest1), "Host greets Guest1: Hello, Guest1!"); + assert.equal(greeterGreeter(guest2), "Host greets Guest2: Hello, Guest2!"); + greeterHost.release(); + guest1.release(); + guest2.release(); + + const greeterForMethod = new exports.Greeter("Method"); + const greeterParam = new exports.Greeter("Param"); + const methodResult = greeterForMethod.greetWith(greeterParam, (g) => { + return `Custom: ${g.name} says ${g.greet()}`; + }); + assert.equal(methodResult, "Custom: Param says Hello, Param!"); + greeterForMethod.release(); + greeterParam.release(); + + const optResult1 = processor.processOptionalString((value) => { + return value !== null ? `Got: ${value}` : `Got: null`; + }); + assert.equal(optResult1, "Got: test | Got: null"); + + const optResult2 = processor.processOptionalInt((value) => { + return value !== null ? `Number: ${value}` : `Number: null`; + }); + assert.equal(optResult2, "Number: 42 | Number: null"); + + const optResult3 = processor.processOptionalGreeter((greeter) => { + return greeter !== null ? `Greeter: ${greeter.name}` : `Greeter: null`; + }); + assert.equal(optResult3, "Greeter: Alice | Greeter: null"); + + const optFormatter = processor.makeOptionalStringFormatter(); + assert.equal(optFormatter("world"), "Got: world"); + assert.equal(optFormatter(null), "Got: nil"); + + const optCreator = processor.makeOptionalGreeterCreator(); + const opt1 = optCreator(); + assert.equal(opt1, null); + const opt2 = optCreator(); + assert.notEqual(opt2, null); + assert.equal(opt2.name, "Greeter2"); + assert.equal(opt2.greet(), "Hello, Greeter2!"); + opt2.release(); + const opt3 = optCreator(); + assert.equal(opt3, null); + const opt4 = optCreator(); + assert.notEqual(opt4, null); + assert.equal(opt4.name, "Greeter4"); + opt4.release(); + + const dirResult = processor.processDirection((dir) => { + switch (dir) { + case exports.Direction.North: return "Going North"; + case exports.Direction.South: return "Going South"; + case exports.Direction.East: return "Going East"; + case exports.Direction.West: return "Going West"; + default: return "Unknown"; + } + }); + assert.equal(dirResult, "Going North"); + + const themeResult = processor.processTheme((theme) => { + return theme === exports.Theme.Dark ? "Dark mode" : "Light mode"; + }); + assert.equal(themeResult, "Dark mode"); + + const statusResult = processor.processHttpStatus((status) => { + return status; + }); + assert.equal(statusResult, exports.HttpStatus.Ok); + + const apiResult = processor.processAPIResult((result) => { + if (result.tag === exports.APIResult.Tag.Success) { + return `API Success: ${result.param0}`; + } + return "API Other"; + }); + assert.equal(apiResult, "API Success: test"); + + const dirChecker = processor.makeDirectionChecker(); + assert.equal(dirChecker(exports.Direction.North), true); + assert.equal(dirChecker(exports.Direction.South), true); + assert.equal(dirChecker(exports.Direction.East), false); + assert.equal(dirChecker(exports.Direction.West), false); + + const themeValidator = processor.makeThemeValidator(); + assert.equal(themeValidator(exports.Theme.Dark), true); + assert.equal(themeValidator(exports.Theme.Light), false); + assert.equal(themeValidator(exports.Theme.Auto), false); + + const statusExtractor = processor.makeStatusCodeExtractor(); + assert.equal(statusExtractor(exports.HttpStatus.Ok), 200); + assert.equal(statusExtractor(exports.HttpStatus.NotFound), 404); + assert.equal(statusExtractor(exports.HttpStatus.ServerError), 500); + assert.equal(statusExtractor(exports.HttpStatus.Unknown), -1); + + const apiHandler = processor.makeAPIResultHandler(); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Success, param0: "done" }), "Success: done"); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Failure, param0: 500 }), "Failure: 500"); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Info }), "Info"); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Flag, param0: true }), "Flag: true"); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Rate, param0: 1.5 }), "Rate: 1.5"); + assert.equal(apiHandler({ tag: exports.APIResult.Tag.Precise, param0: 3.14159 }), "Precise: 3.14159"); + + const optDirResult = processor.processOptionalDirection((dir) => { + return dir !== null ? `Dir: ${dir}` : "Dir: null"; + }); + assert.equal(optDirResult, `Dir: ${exports.Direction.North} | Dir: null`); + + const optThemeResult = processor.processOptionalTheme((theme) => { + return theme !== null ? `Theme: ${theme}` : "Theme: null"; + }); + assert.equal(optThemeResult, `Theme: ${exports.Theme.Light} | Theme: null`); + + const optApiResult = processor.processOptionalAPIResult((result) => { + if (result === null) return "Result: null"; + if (result.tag === exports.APIResult.Tag.Success) { + return `Result: Success(${result.param0})`; + } + return "Result: other"; + }); + assert.equal(optApiResult, "Result: Success(ok) | Result: null"); + + const optDirFormatter = processor.makeOptionalDirectionFormatter(); + assert.equal(optDirFormatter(exports.Direction.North), "N"); + assert.equal(optDirFormatter(exports.Direction.South), "S"); + assert.equal(optDirFormatter(exports.Direction.East), "E"); + assert.equal(optDirFormatter(exports.Direction.West), "W"); + assert.equal(optDirFormatter(null), "nil"); + + processor.release(); + + + const intToInt = exports.ClosureSupportExports.makeIntToInt(10); + assert.equal(intToInt(0), 10); + assert.equal(intToInt(32), 42); + + const doubleToDouble = exports.ClosureSupportExports.makeDoubleToDouble(10.0); + assert.equal(doubleToDouble(0.0), 10.0); + assert.equal(doubleToDouble(32.0), 42.0); + + const stringToString = exports.ClosureSupportExports.makeStringToString("Hello, "); + assert.equal(stringToString("world!"), "Hello, world!"); + + const jsIntToInt = exports.ClosureSupportExports.makeJSIntToInt(10); + assert.equal(jsIntToInt(0), 10); + assert.equal(jsIntToInt(32), 42); + + const jsDoubleToDouble = exports.ClosureSupportExports.makeJSDoubleToDouble(10.0); + assert.equal(jsDoubleToDouble(0.0), 10.0); + assert.equal(jsDoubleToDouble(32.0), 42.0); + + const jsStringToString = exports.ClosureSupportExports.makeJSStringToString("Hello, "); + assert.equal(jsStringToString("world!"), "Hello, world!"); +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs new file mode 100644 index 000000000..58215560c --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -0,0 +1,246 @@ +// @ts-check + +import assert from 'node:assert'; +import { + StatusValues, + ThemeValues, + HttpStatusValues, + TSDirection, + TSTheme, + APIResultValues, + APIOptionalResultValues, + AllTypesResultValues, + OptionalAllTypesResultValues, +} from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; + +import { ImportedFoo } from './Types.mjs'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["OptionalSupportImports"]} + */ +export function getImports(importsContext) { + return { + jsRoundTripOptionalNumberNull: (v) => { + return v ?? null; + }, + jsRoundTripOptionalNumberUndefined: (v) => { + return v === undefined ? undefined : v; + }, + jsRoundTripOptionalStringNull: (v) => { + return v ?? null; + }, + jsRoundTripOptionalStringUndefined: (v) => { + return v === undefined ? undefined : v; + }, + runJsOptionalSupportTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsOptionalSupportTests(exports); + }, + }; +} + +/** + * Optional value bridging coverage for BridgeJS runtime tests. + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +export function runJsOptionalSupportTests(exports) { + assert.equal(exports.roundTripOptionalString(null), null); + assert.equal(exports.roundTripOptionalInt(null), null); + assert.equal(exports.roundTripOptionalBool(null), null); + assert.equal(exports.roundTripOptionalFloat(null), null); + assert.equal(exports.roundTripOptionalDouble(null), null); + + assert.equal(exports.roundTripOptionalString('Hello'), 'Hello'); + assert.equal(exports.roundTripOptionalInt(42), 42); + assert.equal(exports.roundTripOptionalBool(true), true); + assert.equal(exports.roundTripOptionalFloat(3.141592502593994), 3.141592502593994); // Float32 precision + assert.equal(exports.roundTripOptionalDouble(2.718), 2.718); + + assert.equal(exports.roundTripOptionalSyntax(null), null); + assert.equal(exports.roundTripOptionalSyntax('Test'), 'Test'); + assert.equal(exports.roundTripOptionalMixSyntax(null), null); + assert.equal(exports.roundTripOptionalMixSyntax('Mix'), 'Mix'); + assert.equal(exports.roundTripOptionalSwiftSyntax(null), null); + assert.equal(exports.roundTripOptionalSwiftSyntax('Swift'), 'Swift'); + assert.equal(exports.roundTripOptionalWithSpaces(null), null); + assert.equal(exports.roundTripOptionalWithSpaces(1.618), 1.618); + assert.equal(exports.roundTripOptionalTypeAlias(null), null); + assert.equal(exports.roundTripOptionalTypeAlias(25), 25); + assert.equal(exports.roundTripOptionalStatus(exports.Status.Success), StatusValues.Success); + assert.equal(exports.roundTripOptionalTheme(exports.Theme.Light), ThemeValues.Light); + assert.equal(exports.roundTripOptionalHttpStatus(exports.HttpStatus.Ok), HttpStatusValues.Ok); + assert.equal(exports.roundTripOptionalTSDirection(TSDirection.North), TSDirection.North); + assert.equal(exports.roundTripOptionalTSTheme(TSTheme.Light), TSTheme.Light); + assert.equal(exports.roundTripOptionalNetworkingAPIMethod(exports.Networking.API.Method.Get), exports.Networking.API.Method.Get); + + const pVal = 3.141592653589793; + const p1 = { tag: APIResultValues.Tag.Precise, param0: pVal }; + const cl1 = { tag: exports.ComplexResult.Tag.Location, param0: 37.7749, param1: -122.4194, param2: 'San Francisco' }; + + assert.deepEqual(exports.roundTripOptionalAPIResult(p1), p1); + assert.deepEqual(exports.roundTripOptionalComplexResult(cl1), cl1); + + const apiSuccess = { tag: exports.APIResult.Tag.Success, param0: 'test success' }; + const apiFailure = { tag: exports.APIResult.Tag.Failure, param0: 404 }; + const apiInfo = { tag: exports.APIResult.Tag.Info }; + + assert.equal(exports.compareAPIResults(apiSuccess, apiFailure), 'r1:success:test success,r2:failure:404'); + assert.equal(exports.compareAPIResults(null, apiInfo), 'r1:nil,r2:info'); + assert.equal(exports.compareAPIResults(apiFailure, null), 'r1:failure:404,r2:nil'); + assert.equal(exports.compareAPIResults(null, null), 'r1:nil,r2:nil'); + + const optionalGreeter = new exports.Greeter('Schrödinger'); + const optionalGreeter2 = exports.roundTripOptionalClass(optionalGreeter); + assert.equal(optionalGreeter2?.greet() ?? '', 'Hello, Schrödinger!'); + assert.equal(optionalGreeter2?.name ?? '', 'Schrödinger'); + assert.equal(optionalGreeter2?.prefix ?? '', 'Hello'); + assert.equal(exports.roundTripOptionalClass(null), null); + optionalGreeter.release(); + optionalGreeter2?.release(); + + const optionalsHolder = new exports.OptionalPropertyHolder(null); + + assert.equal(optionalsHolder.optionalName, null); + assert.equal(optionalsHolder.optionalAge, null); + assert.equal(optionalsHolder.optionalGreeter, null); + + optionalsHolder.optionalName = 'Alice'; + optionalsHolder.optionalAge = 25; + assert.equal(optionalsHolder.optionalName, 'Alice'); + assert.equal(optionalsHolder.optionalAge, 25); + + const testPropertyGreeter = new exports.Greeter('Bob'); + optionalsHolder.optionalGreeter = testPropertyGreeter; + assert.equal(optionalsHolder.optionalGreeter.greet(), 'Hello, Bob!'); + assert.equal(optionalsHolder.optionalGreeter.name, 'Bob'); + + optionalsHolder.optionalName = null; + optionalsHolder.optionalAge = null; + optionalsHolder.optionalGreeter = null; + assert.equal(optionalsHolder.optionalName, null); + assert.equal(optionalsHolder.optionalAge, null); + assert.equal(optionalsHolder.optionalGreeter, null); + testPropertyGreeter.release(); + optionalsHolder.release(); + + const optGreeter = new exports.Greeter('Optionaly'); + assert.equal(exports.roundTripOptionalGreeter(null), null); + const optGreeterReturned = exports.roundTripOptionalGreeter(optGreeter); + assert.equal(optGreeterReturned.name, 'Optionaly'); + assert.equal(optGreeterReturned.greet(), 'Hello, Optionaly!'); + + const appliedOptional = exports.applyOptionalGreeter(null, (g) => g ?? optGreeter); + assert.equal(appliedOptional.name, 'Optionaly'); + + const holderOpt = exports.makeOptionalHolder(null, undefined); + assert.equal(holderOpt.nullableGreeter, null); + assert.equal(holderOpt.undefinedNumber, undefined); + holderOpt.nullableGreeter = optGreeter; + holderOpt.undefinedNumber = 123.5; + assert.equal(holderOpt.nullableGreeter.name, 'Optionaly'); + assert.equal(holderOpt.undefinedNumber, 123.5); + holderOpt.release(); + optGreeterReturned.release(); + optGreeter.release(); + + const aor1 = { tag: APIOptionalResultValues.Tag.Success, param0: 'hello world' }; + const aor2 = { tag: APIOptionalResultValues.Tag.Success, param0: null }; + const aor3 = { tag: APIOptionalResultValues.Tag.Failure, param0: 404, param1: true }; + const aor4 = { tag: APIOptionalResultValues.Tag.Failure, param0: 404, param1: null }; + const aor5 = { tag: APIOptionalResultValues.Tag.Failure, param0: null, param1: null }; + const aor6 = { tag: APIOptionalResultValues.Tag.Status, param0: true, param1: 200, param2: 'OK' }; + const aor7 = { tag: APIOptionalResultValues.Tag.Status, param0: true, param1: null, param2: 'Partial' }; + const aor8 = { tag: APIOptionalResultValues.Tag.Status, param0: null, param1: null, param2: 'Zero' }; + const aor9 = { tag: APIOptionalResultValues.Tag.Status, param0: false, param1: 500, param2: null }; + const aor10 = { tag: APIOptionalResultValues.Tag.Status, param0: null, param1: 0, param2: 'Zero' }; + + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor1), aor1); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor2), aor2); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor3), aor3); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor4), aor4); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor5), aor5); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor6), aor6); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor7), aor7); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor8), aor8); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor9), aor9); + assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor10), aor10); + assert.equal(exports.roundTripOptionalAPIOptionalResult(null), null); + + // Optional TypedPayloadResult roundtrip + const tpr_precision = { tag: exports.TypedPayloadResult.Tag.Precision, param0: Math.fround(0.1) }; + assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_precision), tpr_precision); + const tpr_direction = { tag: exports.TypedPayloadResult.Tag.Direction, param0: exports.Direction.North }; + assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_direction), tpr_direction); + const tpr_optPrecisionSome = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: Math.fround(0.001) }; + assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_optPrecisionSome), tpr_optPrecisionSome); + const tpr_optPrecisionNull = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: null }; + assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_optPrecisionNull), tpr_optPrecisionNull); + const tpr_empty = { tag: exports.TypedPayloadResult.Tag.Empty }; + assert.deepEqual(exports.roundTripOptionalTypedPayloadResult(tpr_empty), tpr_empty); + assert.equal(exports.roundTripOptionalTypedPayloadResult(null), null); + + // Optional AllTypesResult roundtrip + const atr_struct = { tag: AllTypesResultValues.Tag.StructPayload, param0: { street: "100 Main St", city: "Boston", zipCode: 2101 } }; + assert.deepEqual(exports.roundTripOptionalAllTypesResult(atr_struct), atr_struct); + const atr_array = { tag: AllTypesResultValues.Tag.ArrayPayload, param0: [10, 20, 30] }; + assert.deepEqual(exports.roundTripOptionalAllTypesResult(atr_array), atr_array); + const atr_empty = { tag: AllTypesResultValues.Tag.Empty }; + assert.deepEqual(exports.roundTripOptionalAllTypesResult(atr_empty), atr_empty); + assert.equal(exports.roundTripOptionalAllTypesResult(null), null); + + // OptionalAllTypesResult — optional struct, class, JSObject, nested enum, array as associated value payloads + const oatr_structSome = { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: { street: "200 Oak St", city: "Denver", zipCode: null } }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_structSome), oatr_structSome); + + const oatr_structNone = { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_structNone), oatr_structNone); + + const oatr_classSome = { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: new exports.Greeter("OptEnumUser") }; + const oatr_classSome_result = exports.roundTripOptionalPayloadResult(oatr_classSome); + assert.equal(oatr_classSome_result.tag, OptionalAllTypesResultValues.Tag.OptClass); + assert.equal(oatr_classSome_result.param0.name, "OptEnumUser"); + + const oatr_classNone = { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_classNone), oatr_classNone); + + const oatr_jsObjectSome = { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: { key: "value" } }; + const oatr_jsObjectSome_result = exports.roundTripOptionalPayloadResult(oatr_jsObjectSome); + assert.equal(oatr_jsObjectSome_result.tag, OptionalAllTypesResultValues.Tag.OptJSObject); + assert.equal(oatr_jsObjectSome_result.param0.key, "value"); + + const oatr_jsObjectNone = { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_jsObjectNone), oatr_jsObjectNone); + + const oatr_nestedEnumSome = { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: { tag: APIResultValues.Tag.Failure, param0: 404 } }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_nestedEnumSome), oatr_nestedEnumSome); + + const oatr_nestedEnumNone = { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_nestedEnumNone), oatr_nestedEnumNone); + + const oatr_arraySome = { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: [1, 2, 3] }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_arraySome), oatr_arraySome); + + const oatr_arrayNone = { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_arrayNone), oatr_arrayNone); + + const oatr_jsClassSome = { tag: OptionalAllTypesResultValues.Tag.OptJsClass, param0: new ImportedFoo("optEnumFoo") }; + const oatr_jsClassSome_result = exports.roundTripOptionalPayloadResult(oatr_jsClassSome); + assert.equal(oatr_jsClassSome_result.tag, OptionalAllTypesResultValues.Tag.OptJsClass); + assert.equal(oatr_jsClassSome_result.param0.value, "optEnumFoo"); + + const oatr_jsClassNone = { tag: OptionalAllTypesResultValues.Tag.OptJsClass, param0: null }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_jsClassNone), oatr_jsClassNone); + + const oatr_empty = { tag: OptionalAllTypesResultValues.Tag.Empty }; + assert.deepEqual(exports.roundTripOptionalPayloadResult(oatr_empty), oatr_empty); + + // Optional OptionalAllTypesResult roundtrip + assert.deepEqual(exports.roundTripOptionalPayloadResultOpt(oatr_structSome), oatr_structSome); + assert.deepEqual(exports.roundTripOptionalPayloadResultOpt(oatr_structNone), oatr_structNone); + assert.deepEqual(exports.roundTripOptionalPayloadResultOpt(oatr_empty), oatr_empty); + assert.equal(exports.roundTripOptionalPayloadResultOpt(null), null); + + exports.takeOptionalJSObject(null); + assert.doesNotThrow(() => exports.takeOptionalJSObject({ key: "value" })); +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/SwiftClassSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/SwiftClassSupportTests.mjs new file mode 100644 index 000000000..0368cb74a --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/SwiftClassSupportTests.mjs @@ -0,0 +1,13 @@ +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["SwiftClassSupportImports"]} + */ +export function getImports(importsContext) { + return { + jsRoundTripGreeter: (greeter) => { + return greeter; + }, + jsRoundTripOptionalGreeter: (greeter) => { + return greeter; + }, + }; +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/Types.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/Types.mjs new file mode 100644 index 000000000..b4c2079d8 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/Types.mjs @@ -0,0 +1,6 @@ +export class ImportedFoo { + /** @param {string} value */ + constructor(value) { + this.value = value; + } +} diff --git a/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSClassCompileTests.swift b/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSClassCompileTests.swift new file mode 100644 index 000000000..05a23d9de --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSClassCompileTests.swift @@ -0,0 +1,11 @@ +import JavaScriptKit + +@JSClass(from: .global) internal struct MyJSClassInternal { + @JSFunction init() throws(JSException) +} +@JSClass(from: .global) public struct MyJSClassPublic { + @JSFunction init() throws(JSException) +} +@JSClass(from: .global) package struct MyJSClassPackage { + @JSFunction init() throws(JSException) +} diff --git a/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSFunctionCompileTests.swift b/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSFunctionCompileTests.swift new file mode 100644 index 000000000..e74c84d51 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/MacroCompileTests/JSFunctionCompileTests.swift @@ -0,0 +1,7 @@ +import JavaScriptKit + +@JSFunction package func jsFunctionWithPackageAccess() throws(JSException) +@JSFunction public func jsFunctionWithPublicAccess() throws(JSException) +@JSFunction internal func jsFunctionWithInternalAccess() throws(JSException) +@JSFunction fileprivate func jsFunctionWithFilePrivateAccess() throws(JSException) +@JSFunction private func jsFunctionWithPrivateAccess() throws(JSException) diff --git a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift new file mode 100644 index 000000000..a99bb0bb1 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -0,0 +1,231 @@ +import XCTest +import JavaScriptKit +import JavaScriptEventLoop + +@JSClass struct OptionalSupportImports { + @JSFunction static func jsRoundTripOptionalNumberNull(_ value: Int?) throws -> Int? + @JSFunction static func jsRoundTripOptionalNumberUndefined(_ value: JSUndefinedOr) throws -> JSUndefinedOr + @JSFunction static func jsRoundTripOptionalStringNull(_ name: String?) throws -> String? + @JSFunction static func jsRoundTripOptionalStringUndefined( + _ name: JSUndefinedOr + ) throws -> JSUndefinedOr + + @JSFunction static func runJsOptionalSupportTests() throws(JSException) +} + +final class OptionalSupportTests: XCTestCase { + func testRunJsOptionalSupportTests() throws { + try OptionalSupportImports.runJsOptionalSupportTests() + } + + private func roundTripTest(_ fn: (T?) throws -> T?, _ some: T) throws { + try XCTAssertNil(fn(nil)) + try XCTAssertEqual(fn(some), some) + } + private func roundTripTest(_ fn: (JSUndefinedOr) throws -> JSUndefinedOr, _ some: T) throws { + let undefined = try fn(.undefined) + if case .value = undefined { + XCTFail("Expected undefined") + } + let value = try fn(.value(some)) + switch value { + case .value(let value): + XCTAssertEqual(value, some) + case .undefined: + XCTFail("Expected defined value") + } + } + + func testRoundTripOptionalStringNull() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringNull, "hello") + } + + func testRoundTripOptionalStringUndefined() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringUndefined, "hi") + } + + func testRoundTripOptionalNumberNull() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalNumberNull, 42) + } + + func testRoundTripOptionalNumberUndefined() throws { + try roundTripTest(OptionalSupportImports.jsRoundTripOptionalNumberUndefined, 42) + } +} + +// MARK: - Optional Bridging + +@JS func roundTripOptionalString(name: String?) -> String? { + name +} + +@JS func roundTripOptionalInt(value: Int?) -> Int? { + value +} + +@JS func roundTripOptionalBool(flag: Bool?) -> Bool? { + flag +} + +@JS func roundTripOptionalFloat(number: Float?) -> Float? { + number +} + +@JS func roundTripOptionalDouble(precision: Double?) -> Double? { + precision +} + +@JS func roundTripOptionalSyntax(name: Optional) -> Optional { + name +} + +@JS func roundTripOptionalMixSyntax(name: String?) -> Optional { + name +} + +@JS func roundTripOptionalSwiftSyntax(name: Swift.Optional) -> Swift.Optional { + name +} + +@JS func roundTripOptionalWithSpaces(value: Optional) -> Optional { + value +} + +typealias OptionalAge = Int? +@JS func roundTripOptionalTypeAlias(age: OptionalAge) -> OptionalAge { + age +} + +@JS func roundTripOptionalStatus(value: Status?) -> Status? { + value +} + +@JS func roundTripOptionalTheme(value: Theme?) -> Theme? { + value +} + +@JS func roundTripOptionalHttpStatus(value: HttpStatus?) -> HttpStatus? { + value +} + +@JS func roundTripOptionalTSDirection(value: TSDirection?) -> TSDirection? { + value +} + +@JS func roundTripOptionalTSTheme(value: TSTheme?) -> TSTheme? { + value +} + +@JS func roundTripOptionalNetworkingAPIMethod(_ method: Networking.API.Method?) -> Networking.API.Method? { + method +} + +@JS func roundTripOptionalAPIResult(value: APIResult?) -> APIResult? { + value +} + +@JS func roundTripOptionalTypedPayloadResult(_ result: TypedPayloadResult?) -> TypedPayloadResult? { + result +} + +@JS func takeOptionalJSObject(_ value: JSObject?) {} + +@JS func compareAPIResults(_ r1: APIResult?, _ r2: APIResult?) -> String { + let r1Str: String + switch r1 { + case .none: r1Str = "nil" + case .some(.success(let msg)): r1Str = "success:\(msg)" + case .some(.failure(let code)): r1Str = "failure:\(code)" + case .some(.info): r1Str = "info" + case .some(.flag(let b)): r1Str = "flag:\(b)" + case .some(.rate(let r)): r1Str = "rate:\(r)" + case .some(.precise(let p)): r1Str = "precise:\(p)" + } + + let r2Str: String + switch r2 { + case .none: r2Str = "nil" + case .some(.success(let msg)): r2Str = "success:\(msg)" + case .some(.failure(let code)): r2Str = "failure:\(code)" + case .some(.info): r2Str = "info" + case .some(.flag(let b)): r2Str = "flag:\(b)" + case .some(.rate(let r)): r2Str = "rate:\(r)" + case .some(.precise(let p)): r2Str = "precise:\(p)" + } + + return "r1:\(r1Str),r2:\(r2Str)" +} + +@JS func roundTripOptionalComplexResult(_ result: ComplexResult?) -> ComplexResult? { + result +} + +@JS func roundTripOptionalAllTypesResult(_ result: AllTypesResult?) -> AllTypesResult? { + result +} + +@JS +enum OptionalAllTypesResult { + case optStruct(Address?) + case optClass(Greeter?) + case optJSObject(JSObject?) + case optNestedEnum(APIResult?) + case optArray([Int]?) + case optJsClass(Foo?) + case empty +} + +@JS func roundTripOptionalPayloadResult(_ result: OptionalAllTypesResult) -> OptionalAllTypesResult { + result +} + +@JS func roundTripOptionalPayloadResultOpt(_ result: OptionalAllTypesResult?) -> OptionalAllTypesResult? { + result +} + +@JS func roundTripOptionalClass(value: Greeter?) -> Greeter? { + value +} + +@JS func roundTripOptionalGreeter(_ value: Greeter?) -> Greeter? { + value +} + +@JS func applyOptionalGreeter(_ value: Greeter?, _ transform: (Greeter?) -> Greeter?) -> Greeter? { + transform(value) +} + +@JS class OptionalHolder { + @JS var nullableGreeter: Greeter? + @JS var undefinedNumber: JSUndefinedOr + + @JS init(nullableGreeter: Greeter?, undefinedNumber: JSUndefinedOr) { + self.nullableGreeter = nullableGreeter + self.undefinedNumber = undefinedNumber + } +} + +@JS func makeOptionalHolder(nullableGreeter: Greeter?, undefinedNumber: JSUndefinedOr) -> OptionalHolder { + OptionalHolder(nullableGreeter: nullableGreeter, undefinedNumber: undefinedNumber) +} + +@JS class OptionalPropertyHolder { + @JS var optionalName: String? + @JS var optionalAge: Int? = nil + @JS var optionalGreeter: Greeter? = nil + + @JS init(optionalName: String?) { + self.optionalName = optionalName + } +} + +@JS +enum APIOptionalResult { + case success(String?) + case failure(Int?, Bool?) + case status(Bool?, Int?, String?) +} + +@JS func roundTripOptionalAPIOptionalResult(result: APIOptionalResult?) -> APIOptionalResult? { + result +} diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index 5c9fed511..6c0079dd1 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -1,4 +1,4 @@ -@_spi(Experimental) import JavaScriptKit +import JavaScriptKit @JS struct PointerFields { var raw: UnsafeRawPointer @@ -40,6 +40,16 @@ } } +@JS public struct PublicPoint { + public var x: Int + public var y: Int + + @JS public init(x: Int, y: Int) { + self.x = x + self.y = y + } +} + @JS struct Address { var street: String var city: String @@ -168,6 +178,10 @@ return data } +@JS public func roundTripPublicPoint(_ point: PublicPoint) -> PublicPoint { + point +} + @JS func roundTripContact(_ contact: Contact) -> Contact { return contact } @@ -214,3 +228,48 @@ @JS func testContainerWithStruct(_ point: DataPoint) -> Container { return Container(location: point, config: nil) } + +// Struct with JSObject fields +@JS struct JSObjectContainer { + var object: JSObject + var optionalObject: JSObject? +} + +@JS func roundTripJSObjectContainer(_ container: JSObjectContainer) -> JSObjectContainer { + return container +} + +// Struct with @JSClass fields (Foo is defined in ExportAPITests.swift) +@JS struct FooContainer { + var foo: Foo + var optionalFoo: Foo? +} + +@JS func roundTripFooContainer(_ container: FooContainer) -> FooContainer { + return container +} + +@JS struct ArrayMembers { + var ints: [Int] + var optStrings: [String]? + + @JS func sumValues(_ values: [Int]) -> Int { + values.reduce(0, +) + } + + @JS func firstString(_ values: [String]) -> String? { + values.first + } +} + +@JS func roundTripArrayMembers(_ value: ArrayMembers) -> ArrayMembers { + value +} + +@JS func arrayMembersSum(_ value: ArrayMembers, _ values: [Int]) -> Int { + value.sumValues(values) +} + +@JS func arrayMembersFirst(_ value: ArrayMembers, _ values: [String]) -> String? { + value.firstString(values) +} diff --git a/Tests/BridgeJSRuntimeTests/SwiftClassSupportTests.swift b/Tests/BridgeJSRuntimeTests/SwiftClassSupportTests.swift new file mode 100644 index 000000000..d9a68b1cc --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/SwiftClassSupportTests.swift @@ -0,0 +1,60 @@ +import XCTest +import JavaScriptKit + +@JSClass struct SwiftClassSupportImports { + @JSFunction static func jsRoundTripGreeter(_ greeter: Greeter) throws(JSException) -> Greeter + @JSFunction static func jsRoundTripOptionalGreeter(_ greeter: Greeter?) throws(JSException) -> Greeter? +} + +@JSFunction(from: .global) func gc() throws(JSException) -> Void + +final class SwiftClassSupportTests: XCTestCase { + func testRoundTripGreeter() throws { + let greeter = try SwiftClassSupportImports.jsRoundTripGreeter(Greeter(name: "Hello")) + XCTAssertEqual(greeter.name, "Hello") + } + + func testRoundTripOptionalGreeter() throws { + let greeter1 = try SwiftClassSupportImports.jsRoundTripOptionalGreeter(nil) + XCTAssertNil(greeter1) + + let greeter2 = try SwiftClassSupportImports.jsRoundTripOptionalGreeter(Greeter(name: "Hello")) + XCTAssertEqual(greeter2?.name, "Hello") + } + + func testSwiftClassToJSObject() throws { + let greeter = Greeter(name: "BridgeJS") + let jsGreeter = try XCTUnwrap(greeter.jsValue.object) + XCTAssertEqual(jsGreeter["name"].string, "BridgeJS") + } + + func testJSWrapperIsDeallocatedAfterFinalization() async throws { + weak var weakGreeter: Greeter? + var wrapperObject: JSObject? + do { + let greeter: Greeter = Greeter(name: "Hello") + weakGreeter = greeter + // Create a JS wrapper object but don't keep a reference to it + wrapperObject = try XCTUnwrap(greeter.jsValue.object) + } + // Here, the wrapper object is still alive so the greeter should still be alive + XCTAssertNotNil(weakGreeter) + + // Release the strong reference to the greeter + wrapperObject = nil + _ = wrapperObject + + // Trigger garbage collection to call the finalizer of the JS wrapper object + for _ in 0..<100 { + try gc() + // Tick the event loop to allow the garbage collector to run finalizers + // registered by FinalizationRegistry. + try await Task.sleep(for: .milliseconds(0)) + if weakGreeter == nil { + break + } + } + // Here, the greeter should be deallocated + XCTAssertNil(weakGreeter) + } +} diff --git a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts index 983d6052d..ff69f5de9 100644 --- a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts +++ b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts @@ -2,6 +2,10 @@ export function jsRoundTripVoid(): void export function jsRoundTripNumber(v: number): number export function jsRoundTripBool(v: boolean): boolean export function jsRoundTripString(v: string): string +export type JSValue = any +export function jsRoundTripJSValue(v: JSValue): JSValue +export function jsRoundTripJSValueArray(v: JSValue[]): JSValue[] +export function jsRoundTripOptionalJSValueArray(v: JSValue[] | null): JSValue[] | null export function jsThrowOrVoid(shouldThrow: boolean): void export function jsThrowOrNumber(shouldThrow: boolean): number export function jsThrowOrBool(shouldThrow: boolean): boolean @@ -31,3 +35,18 @@ export class $WeirdClass { constructor(); "method-with-dashes"(): string; } + +export class StaticBox { + constructor(value: number); + value(): number; + static create(value: number): StaticBox; + static value(): number; + static makeDefault(): StaticBox; + static "with-dashes"(): StaticBox; +} + +export function jsRoundTripNumberArray(values: number[]): number[]; +export function jsRoundTripStringArray(values: string[]): string[]; +export function jsRoundTripBoolArray(values: boolean[]): boolean[]; +export function jsSumNumberArray(values: number[]): number; +export function jsCreateNumberArray(): number[]; diff --git a/Tests/JavaScriptKitTests/JavaScriptKitTests.swift b/Tests/JavaScriptKitTests/JavaScriptKitTests.swift index b69334ce5..280a17b62 100644 --- a/Tests/JavaScriptKitTests/JavaScriptKitTests.swift +++ b/Tests/JavaScriptKitTests/JavaScriptKitTests.swift @@ -523,5 +523,9 @@ class JavaScriptKitTests: XCTestCase { } } +#if arch(wasm32) @_extern(c, "llvm.wasm.memory.grow.i32") func growMemory(_ memory: Int32, _ pages: Int32) -> Int32 +#else +func growMemory(_ memory: Int32, _ pages: Int32) -> Int32 { return 0 } +#endif diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 12307d605..e55266e9c 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -1,17 +1,59 @@ // @ts-check import { - DirectionValues, StatusValues, ThemeValues, HttpStatusValues, TSDirection, TSTheme, APIResultValues, ComplexResultValues, APIOptionalResultValues, StaticCalculatorValues, StaticPropertyEnumValues + DirectionValues, StatusValues, ThemeValues, HttpStatusValues, TSDirection, TSTheme, APIResultValues, ComplexResultValues, APIOptionalResultValues, StaticCalculatorValues, StaticPropertyEnumValues, PrecisionValues, TypedPayloadResultValues, AllTypesResultValues, OptionalAllTypesResultValues } from '../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; +import { ImportedFoo } from './BridgeJSRuntimeTests/JavaScript/Types.mjs'; +import { runJsOptionalSupportTests } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; +import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs'; +import { getImports as getSwiftClassSupportImports } from './BridgeJSRuntimeTests/JavaScript/SwiftClassSupportTests.mjs'; +import { getImports as getOptionalSupportImports } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; /** @type {import('../.build/plugins/PackageToJS/outputs/PackageTests/test.d.ts').SetupOptionsFn} */ export async function setupOptions(options, context) { Error.stackTraceLimit = 100; setupTestGlobals(globalThis); + class StaticBox { + constructor(value) { + this._value = value; + } + value() { + return this._value; + } + static create(value) { + return new StaticBox(value); + } + static value() { + return 99; + } + static makeDefault() { + return new StaticBox(0); + } + static ["with-dashes"]() { + return new StaticBox(7); + } + } + return { ...options, getImports: (importsContext) => { + const ArrayHost = class { + constructor(numbers, labels) { + this.numbers = numbers; + this.labels = labels; + } + concatNumbers(values) { + return [...this.numbers, ...values]; + } + concatLabels(values) { + return [...this.labels, ...values]; + } + firstLabel(values) { + const merged = [...values, ...this.labels]; + return merged.length > 0 ? merged[0] : ""; + } + }; return { "jsRoundTripVoid": () => { return; @@ -25,6 +67,45 @@ export async function setupOptions(options, context) { "jsRoundTripString": (v) => { return v; }, + "jsRoundTripDictionary": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryBool": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryDouble": (dict) => { + return { ...dict }; + }, + "jsRoundTripDictionaryJSObject": (dict) => { + return dict; + }, + "jsRoundTripDictionaryJSValue": (dict) => { + return dict; + }, + "jsRoundTripNestedDictionary": (dict) => { + return Object.fromEntries(Object.entries(dict).map(([k, v]) => [k, [...v]])); + }, + "jsRoundTripOptionalDictionary": (dict) => { + return dict ?? null; + }, + "jsRoundTripUndefinedDictionary": (dict) => { + return dict; + }, + "jsRoundTripJSValue": (v) => { + return v; + }, + "jsRoundTripJSValueArray": (values) => { + return values; + }, + "jsRoundTripOptionalJSValueArray": (values) => { + return values ?? null; + }, + "jsRoundTripIntArray": (items) => { + return items; + }, + "jsArrayLength": (items) => { + return items.length; + }, "jsThrowOrVoid": (shouldThrow) => { if (shouldThrow) { throw new Error("TestError"); @@ -51,9 +132,16 @@ export async function setupOptions(options, context) { "jsRoundTripFeatureFlag": (flag) => { return flag; }, + "jsEchoJSValue": (v) => { + return v; + }, "$jsWeirdFunction": () => { return 42; }, + ArrayHost, + makeArrayHost: (numbers, labels) => { + return new ArrayHost(numbers, labels); + }, JsGreeter: class { /** * @param {string} name @@ -78,6 +166,7 @@ export async function setupOptions(options, context) { return "ok"; } }, + StaticBox, Foo: ImportedFoo, runAsyncWorks: async () => { const exports = importsContext.getExports(); @@ -87,26 +176,35 @@ export async function setupOptions(options, context) { BridgeJSRuntimeTests_runAsyncWorks(exports); return; }, - jsApplyInt: (v, fn) => { - return fn(v); + jsTranslatePoint: (point, dx, dy) => { + return { x: (point.x | 0) + (dx | 0), y: (point.y | 0) + (dy | 0) }; }, - jsMakeAdder: (base) => { - return (v) => base + v; + jsRoundTripNumberArray: (values) => { + return values; }, - jsMapString: (value, fn) => { - return fn(value); + jsRoundTripStringArray: (values) => { + return values; }, - jsMakePrefixer: (prefix) => { - return (name) => `${prefix}${name}`; + jsRoundTripBoolArray: (values) => { + return values; }, - jsCallTwice: (v, fn) => { - fn(v); - fn(v); - return v; + jsSumNumberArray: (values) => { + return values.reduce((a, b) => a + b, 0); }, - jsTranslatePoint: (point, dx, dy) => { - return { x: (point.x | 0) + (dx | 0), y: (point.y | 0) + (dy | 0) }; - } + jsCreateNumberArray: () => { + return [1, 2, 3, 4, 5]; + }, + roundTripArrayMembers: (value) => { + return value; + }, + runJsOptionalSupportTests: () => { + const exports = importsContext.getExports(); + if (!exports) { throw new Error("No exports!?"); } + runJsOptionalSupportTests(exports); + }, + ClosureSupportImports: getClosureSupportImports(importsContext), + SwiftClassSupportImports: getSwiftClassSupportImports(importsContext), + OptionalSupportImports: getOptionalSupportImports(importsContext), }; }, addToCoreImports(importObject, importsContext) { @@ -142,13 +240,6 @@ export async function setupOptions(options, context) { import assert from "node:assert"; -class ImportedFoo { - /** @param {string} value */ - constructor(value) { - this.value = value; - } -} - /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { exports.roundTripVoid(); @@ -189,6 +280,21 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { ]) { assert.equal(exports.roundTripString(v), v); } + const dict = { a: 1, b: 2 }; + assert.deepEqual(exports.roundTripDictionaryExport(dict), dict); + const optDict = { hello: "world" }; + assert.deepEqual(exports.roundTripOptionalDictionaryExport(optDict), optDict); + assert.equal(exports.roundTripOptionalDictionaryExport(null), null); + const arrayStruct = { ints: [1, 2, 3], optStrings: ["a", "b"] }; + const arrayStructRoundTrip = exports.roundTripArrayMembers(arrayStruct); + assert.deepEqual(arrayStructRoundTrip.ints, [1, 2, 3]); + assert.deepEqual(arrayStructRoundTrip.optStrings, ["a", "b"]); + assert.equal(exports.arrayMembersSum(arrayStruct, [10, 20]), 30); + assert.equal(exports.arrayMembersFirst(arrayStruct, ["x", "y"]), "x"); + const jsValueArray = [true, 42, "ok", { nested: 1 }, null, undefined]; + assert.deepEqual(exports.roundTripJSValueArray(jsValueArray), jsValueArray); + assert.deepEqual(exports.roundTripOptionalJSValueArray(jsValueArray), jsValueArray); + assert.equal(exports.roundTripOptionalJSValueArray(null), null); for (const p of [1, 4, 1024, 65536, 2147483647]) { assert.equal(exports.roundTripUnsafeRawPointer(p), p); @@ -231,6 +337,11 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(g2.prefix, "Hello"); g2.release(); + // release should be idempotent + const g3 = new exports.Greeter("Idempotent"); + g3.release(); + g3.release(); + g.release(); const foo = exports.makeImportedFoo("hello"); @@ -436,6 +547,20 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { const anyObject = {}; assert.equal(exports.roundTripJSObject(anyObject), anyObject); + const symbolValue = Symbol("roundTrip"); + const bigIntValue = 12345678901234567890n; + const objectValue = { nested: true }; + const jsValues = [true, 42, "hello", objectValue, null, undefined, symbolValue, bigIntValue]; + for (const value of jsValues) { + const result = exports.roundTripJSValue(value); + assert.strictEqual(result, value); + } + + assert.strictEqual(exports.roundTripOptionalJSValue(null), null); + assert.strictEqual(exports.roundTripOptionalJSValue(undefined), null); + assert.strictEqual(exports.roundTripOptionalJSValue(objectValue), objectValue); + assert.strictEqual(exports.roundTripOptionalJSValue(symbolValue), symbolValue); + try { exports.throwsSwiftError(true); assert.fail("Expected error"); @@ -527,6 +652,11 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(converter.toString(123), "123"); converter.release(); + assert.equal(exports.Utils.StringUtils.uppercase("hello"), "HELLO"); + assert.equal(exports.Utils.StringUtils.uppercase(""), ""); + assert.equal(exports.Utils.StringUtils.lowercase("WORLD"), "world"); + assert.equal(exports.Utils.StringUtils.lowercase("HeLLo"), "hello"); + const httpServer = new exports.Networking.API.HTTPServer(); httpServer.call(exports.Networking.API.Method.Get); httpServer.call(exports.Networking.API.Method.Post); @@ -611,102 +741,62 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.deepEqual(exports.makeAPINetworkingResultSuccess("Connected"), { tag: exports.API.NetworkingResult.Tag.Success, param0: "Connected" }); assert.deepEqual(exports.makeAPINetworkingResultFailure("Timeout", 408), { tag: exports.API.NetworkingResult.Tag.Failure, param0: "Timeout", param1: 408 }); - assert.equal(exports.roundTripOptionalString(null), null); - assert.equal(exports.roundTripOptionalInt(null), null); - assert.equal(exports.roundTripOptionalBool(null), null); - assert.equal(exports.roundTripOptionalFloat(null), null); - assert.equal(exports.roundTripOptionalDouble(null), null); - - assert.equal(exports.roundTripOptionalString("Hello"), "Hello"); - assert.equal(exports.roundTripOptionalInt(42), 42); - assert.equal(exports.roundTripOptionalBool(true), true); - assert.equal(exports.roundTripOptionalFloat(3.141592502593994), 3.141592502593994); // Float32 precision - assert.equal(exports.roundTripOptionalDouble(2.718), 2.718); - - assert.equal(exports.roundTripOptionalSyntax(null), null); - assert.equal(exports.roundTripOptionalSyntax("Test"), "Test"); - assert.equal(exports.roundTripOptionalMixSyntax(null), null); - assert.equal(exports.roundTripOptionalMixSyntax("Mix"), "Mix"); - assert.equal(exports.roundTripOptionalSwiftSyntax(null), null); - assert.equal(exports.roundTripOptionalSwiftSyntax("Swift"), "Swift"); - assert.equal(exports.roundTripOptionalWithSpaces(null), null); - assert.equal(exports.roundTripOptionalWithSpaces(1.618), 1.618); - assert.equal(exports.roundTripOptionalTypeAlias(null), null); - assert.equal(exports.roundTripOptionalTypeAlias(25), 25); - assert.equal(exports.roundTripOptionalStatus(exports.Status.Success), StatusValues.Success); - assert.equal(exports.roundTripOptionalTheme(exports.Theme.Light), ThemeValues.Light); - assert.equal(exports.roundTripOptionalHttpStatus(exports.HttpStatus.Ok), HttpStatusValues.Ok); - assert.equal(exports.roundTripOptionalTSDirection(TSDirection.North), TSDirection.North); - assert.equal(exports.roundTripOptionalTSTheme(TSTheme.Light), TSTheme.Light); - assert.equal(exports.roundTripOptionalNetworkingAPIMethod(exports.Networking.API.Method.Get), exports.Networking.API.Method.Get); - assert.deepEqual(exports.roundTripOptionalAPIResult(p1), p1); - assert.deepEqual(exports.roundTripOptionalComplexResult(cl1), cl1); - - const apiSuccess = { tag: exports.APIResult.Tag.Success, param0: "test success" }; - const apiFailure = { tag: exports.APIResult.Tag.Failure, param0: 404 }; - const apiInfo = { tag: exports.APIResult.Tag.Info }; - - assert.equal(exports.compareAPIResults(apiSuccess, apiFailure), "r1:success:test success,r2:failure:404"); - assert.equal(exports.compareAPIResults(null, apiInfo), "r1:nil,r2:info"); - assert.equal(exports.compareAPIResults(apiFailure, null), "r1:failure:404,r2:nil"); - assert.equal(exports.compareAPIResults(null, null), "r1:nil,r2:nil"); - - const optionalGreeter = new exports.Greeter("Schrödinger"); - const optionalGreeter2 = exports.roundTripOptionalClass(optionalGreeter); - assert.equal(optionalGreeter2?.greet() ?? "", "Hello, Schrödinger!"); - assert.equal(optionalGreeter2?.name ?? "", "Schrödinger"); - assert.equal(optionalGreeter2?.prefix ?? "", "Hello"); - assert.equal(exports.roundTripOptionalClass(null), null); - optionalGreeter.release(); - optionalGreeter2?.release(); - - const optionalsHolder = new exports.OptionalPropertyHolder(null); - - assert.equal(optionalsHolder.optionalName, null); - assert.equal(optionalsHolder.optionalAge, null); - assert.equal(optionalsHolder.optionalGreeter, null); - - optionalsHolder.optionalName = "Alice"; - optionalsHolder.optionalAge = 25; - assert.equal(optionalsHolder.optionalName, "Alice"); - assert.equal(optionalsHolder.optionalAge, 25); - - const testPropertyGreeter = new exports.Greeter("Bob"); - optionalsHolder.optionalGreeter = testPropertyGreeter; - assert.equal(optionalsHolder.optionalGreeter.greet(), "Hello, Bob!"); - assert.equal(optionalsHolder.optionalGreeter.name, "Bob"); - - optionalsHolder.optionalName = null; - optionalsHolder.optionalAge = null; - optionalsHolder.optionalGreeter = null; - assert.equal(optionalsHolder.optionalName, null); - assert.equal(optionalsHolder.optionalAge, null); - assert.equal(optionalsHolder.optionalGreeter, null); - testPropertyGreeter.release(); - optionalsHolder.release(); - - const aor1 = { tag: APIOptionalResultValues.Tag.Success, param0: "hello world" }; - const aor2 = { tag: APIOptionalResultValues.Tag.Success, param0: null }; - const aor3 = { tag: APIOptionalResultValues.Tag.Failure, param0: 404, param1: true }; - const aor4 = { tag: APIOptionalResultValues.Tag.Failure, param0: 404, param1: null }; - const aor5 = { tag: APIOptionalResultValues.Tag.Failure, param0: null, param1: null }; - const aor6 = { tag: APIOptionalResultValues.Tag.Status, param0: true, param1: 200, param2: "OK" }; - const aor7 = { tag: APIOptionalResultValues.Tag.Status, param0: true, param1: null, param2: "Partial" }; - const aor8 = { tag: APIOptionalResultValues.Tag.Status, param0: null, param1: null, param2: "Zero" }; - const aor9 = { tag: APIOptionalResultValues.Tag.Status, param0: false, param1: 500, param2: null }; - const aor10 = { tag: APIOptionalResultValues.Tag.Status, param0: null, param1: 0, param2: "Zero" }; - - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor1), aor1); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor2), aor2); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor3), aor3); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor4), aor4); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor5), aor5); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor6), aor6); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor7), aor7); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor8), aor8); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor9), aor9); - assert.deepEqual(exports.roundTripOptionalAPIOptionalResult(aor10), aor10); - assert.equal(exports.roundTripOptionalAPIOptionalResult(null), null); + // TypedPayloadResult — rawValueEnum and caseEnum as associated value payloads + assert.equal(exports.Precision.Rough, 0.1); + assert.equal(exports.Precision.Fine, 0.001); + + const tpr_precision = { tag: exports.TypedPayloadResult.Tag.Precision, param0: Math.fround(0.1) }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_precision), tpr_precision); + + const tpr_direction = { tag: exports.TypedPayloadResult.Tag.Direction, param0: exports.Direction.North }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_direction), tpr_direction); + + const tpr_dirSouth = { tag: exports.TypedPayloadResult.Tag.Direction, param0: exports.Direction.South }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_dirSouth), tpr_dirSouth); + + const tpr_optPrecisionSome = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: Math.fround(0.001) }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_optPrecisionSome), tpr_optPrecisionSome); + + const tpr_optPrecisionNull = { tag: exports.TypedPayloadResult.Tag.OptPrecision, param0: null }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_optPrecisionNull), tpr_optPrecisionNull); + + const tpr_optDirectionSome = { tag: exports.TypedPayloadResult.Tag.OptDirection, param0: exports.Direction.East }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_optDirectionSome), tpr_optDirectionSome); + + const tpr_optDirectionNull = { tag: exports.TypedPayloadResult.Tag.OptDirection, param0: null }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_optDirectionNull), tpr_optDirectionNull); + + const tpr_empty = { tag: exports.TypedPayloadResult.Tag.Empty }; + assert.deepEqual(exports.roundTripTypedPayloadResult(tpr_empty), tpr_empty); + + // AllTypesResult — struct, class, JSObject, nested enum, array as associated value payloads + const atr_struct = { tag: AllTypesResultValues.Tag.StructPayload, param0: { street: "100 Main St", city: "Boston", zipCode: 2101 } }; + assert.deepEqual(exports.roundTripAllTypesResult(atr_struct), atr_struct); + + const atr_class = { tag: AllTypesResultValues.Tag.ClassPayload, param0: new exports.Greeter("EnumUser") }; + const atr_class_result = exports.roundTripAllTypesResult(atr_class); + assert.equal(atr_class_result.tag, AllTypesResultValues.Tag.ClassPayload); + assert.equal(atr_class_result.param0.name, "EnumUser"); + + const atr_jsObject = { tag: AllTypesResultValues.Tag.JsObjectPayload, param0: { custom: "data", value: 42 } }; + const atr_jsObject_result = exports.roundTripAllTypesResult(atr_jsObject); + assert.equal(atr_jsObject_result.tag, AllTypesResultValues.Tag.JsObjectPayload); + assert.equal(atr_jsObject_result.param0.custom, "data"); + assert.equal(atr_jsObject_result.param0.value, 42); + + const atr_nestedEnum = { tag: AllTypesResultValues.Tag.NestedEnum, param0: { tag: APIResultValues.Tag.Success, param0: "nested!" } }; + assert.deepEqual(exports.roundTripAllTypesResult(atr_nestedEnum), atr_nestedEnum); + + const atr_array = { tag: AllTypesResultValues.Tag.ArrayPayload, param0: [10, 20, 30] }; + assert.deepEqual(exports.roundTripAllTypesResult(atr_array), atr_array); + + const atr_jsClass = { tag: AllTypesResultValues.Tag.JsClassPayload, param0: new ImportedFoo("enumFoo") }; + const atr_jsClass_result = exports.roundTripAllTypesResult(atr_jsClass); + assert.equal(atr_jsClass_result.tag, AllTypesResultValues.Tag.JsClassPayload); + assert.equal(atr_jsClass_result.param0.value, "enumFoo"); + + const atr_empty = { tag: AllTypesResultValues.Tag.Empty }; + assert.deepEqual(exports.roundTripAllTypesResult(atr_empty), atr_empty); assert.equal(exports.MathUtils.add(2147483647, 0), 2147483647); assert.equal(exports.StaticCalculator.roundtrip(42), 42); @@ -717,6 +807,11 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.StaticUtils.Nested.roundtrip("hello world"), "hello world"); assert.equal(exports.StaticUtils.Nested.roundtrip("test"), "test"); + assert.equal(exports.Services.Graph.GraphOperations.createGraph(5), 50); + assert.equal(exports.Services.Graph.GraphOperations.createGraph(0), 0); + assert.equal(exports.Services.Graph.GraphOperations.nodeCount(42), 42); + assert.equal(exports.Services.Graph.GraphOperations.nodeCount(0), 0); + // Test default parameters assert.equal(exports.testStringDefault(), "Hello World"); assert.equal(exports.testStringDefault("Custom Message"), "Custom Message"); @@ -780,202 +875,8 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { cd5.release(); testProtocolSupport(exports); - testClosureSupport(exports); testArraySupport(exports); } -/** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ -function testClosureSupport(exports) { - const upperTransform = (text) => text.toUpperCase(); - const processor = new exports.TextProcessor(upperTransform); - - assert.equal(processor.process("hello"), "HELLO"); - - const multiParamTransform = (count, text, ratio) => { - return `${text.toUpperCase()}-${count}-${ratio.toFixed(2)}`; - }; - assert.equal(processor.processWithCustom("world", multiParamTransform), "WORLD-42-3.14"); - assert.equal(processor.process("test"), "TEST"); - - const greeterForClosure = new exports.Greeter("World"); - const greeterCaller = new exports.Greeter("Caller"); - const customGreeting = (greeter) => `Custom greeting for ${greeter.name}: ${greeter.greet()}`; - const greetResult = greeterCaller.greetWith(greeterForClosure, customGreeting); - assert.equal(greetResult, "Custom greeting for World: Hello, World!"); - greeterForClosure.release(); - greeterCaller.release(); - - assert.equal(exports.formatName("ada", (name) => name.toUpperCase()), "ADA"); - assert.equal(exports.formatName("grace", (name) => `Dr. ${name}`), "Dr. grace"); - - const addDr = exports.makeFormatter("Dr."); - assert.equal(addDr("Ada"), "Dr. Ada"); - assert.equal(addDr("Grace"), "Dr. Grace"); - - const addProf = exports.makeFormatter("Prof."); - assert.equal(addProf("Hopper"), "Prof. Hopper"); - - const add10 = exports.makeAdder(10); - assert.equal(add10(5), 15); - assert.equal(add10(32), 42); - - const add100 = exports.makeAdder(100); - assert.equal(add100(23), 123); - - const storedTransform = processor.getTransform(); - assert.equal(storedTransform("hello"), "HELLO"); - assert.equal(storedTransform("world"), "WORLD"); - - const greeterForFormatter = new exports.Greeter("Formatter"); - const greeterFormatter = greeterForFormatter.makeFormatter(" [suffix]"); - assert.equal(greeterFormatter("test"), "Hello, Formatter! - test - [suffix]"); - assert.equal(greeterFormatter("data"), "Hello, Formatter! - data - [suffix]"); - greeterForFormatter.release(); - - const greeterCreator = exports.Greeter.makeCreator("Default"); - const createdG1 = greeterCreator("Alice"); - assert.equal(createdG1.name, "Alice"); - assert.equal(createdG1.greet(), "Hello, Alice!"); - const createdG2 = greeterCreator(""); - assert.equal(createdG2.name, "Default"); - assert.equal(createdG2.greet(), "Hello, Default!"); - createdG1.release(); - createdG2.release(); - - const greeterHost = new exports.Greeter("Host"); - const greeterGreeter = greeterHost.makeCustomGreeter(); - const guest1 = new exports.Greeter("Guest1"); - const guest2 = new exports.Greeter("Guest2"); - assert.equal(greeterGreeter(guest1), "Host greets Guest1: Hello, Guest1!"); - assert.equal(greeterGreeter(guest2), "Host greets Guest2: Hello, Guest2!"); - greeterHost.release(); - guest1.release(); - guest2.release(); - - const greeterForMethod = new exports.Greeter("Method"); - const greeterParam = new exports.Greeter("Param"); - const methodResult = greeterForMethod.greetWith(greeterParam, (g) => { - return `Custom: ${g.name} says ${g.greet()}`; - }); - assert.equal(methodResult, "Custom: Param says Hello, Param!"); - greeterForMethod.release(); - greeterParam.release(); - - const optResult1 = processor.processOptionalString((value) => { - return value !== null ? `Got: ${value}` : `Got: null`; - }); - assert.equal(optResult1, "Got: test | Got: null"); - - const optResult2 = processor.processOptionalInt((value) => { - return value !== null ? `Number: ${value}` : `Number: null`; - }); - assert.equal(optResult2, "Number: 42 | Number: null"); - - const optResult3 = processor.processOptionalGreeter((greeter) => { - return greeter !== null ? `Greeter: ${greeter.name}` : `Greeter: null`; - }); - assert.equal(optResult3, "Greeter: Alice | Greeter: null"); - - const optFormatter = processor.makeOptionalStringFormatter(); - assert.equal(optFormatter("world"), "Got: world"); - assert.equal(optFormatter(null), "Got: nil"); - - const optCreator = processor.makeOptionalGreeterCreator(); - const opt1 = optCreator(); - assert.equal(opt1, null); - const opt2 = optCreator(); - assert.notEqual(opt2, null); - assert.equal(opt2.name, "Greeter2"); - assert.equal(opt2.greet(), "Hello, Greeter2!"); - opt2.release(); - const opt3 = optCreator(); - assert.equal(opt3, null); - const opt4 = optCreator(); - assert.notEqual(opt4, null); - assert.equal(opt4.name, "Greeter4"); - opt4.release(); - - const dirResult = processor.processDirection((dir) => { - switch (dir) { - case exports.Direction.North: return "Going North"; - case exports.Direction.South: return "Going South"; - case exports.Direction.East: return "Going East"; - case exports.Direction.West: return "Going West"; - default: return "Unknown"; - } - }); - assert.equal(dirResult, "Going North"); - - const themeResult = processor.processTheme((theme) => { - return theme === exports.Theme.Dark ? "Dark mode" : "Light mode"; - }); - assert.equal(themeResult, "Dark mode"); - - const statusResult = processor.processHttpStatus((status) => { - return status; - }); - assert.equal(statusResult, exports.HttpStatus.Ok); - - const apiResult = processor.processAPIResult((result) => { - if (result.tag === exports.APIResult.Tag.Success) { - return `API Success: ${result.param0}`; - } - return "API Other"; - }); - assert.equal(apiResult, "API Success: test"); - - const dirChecker = processor.makeDirectionChecker(); - assert.equal(dirChecker(exports.Direction.North), true); - assert.equal(dirChecker(exports.Direction.South), true); - assert.equal(dirChecker(exports.Direction.East), false); - assert.equal(dirChecker(exports.Direction.West), false); - - const themeValidator = processor.makeThemeValidator(); - assert.equal(themeValidator(exports.Theme.Dark), true); - assert.equal(themeValidator(exports.Theme.Light), false); - assert.equal(themeValidator(exports.Theme.Auto), false); - - const statusExtractor = processor.makeStatusCodeExtractor(); - assert.equal(statusExtractor(exports.HttpStatus.Ok), 200); - assert.equal(statusExtractor(exports.HttpStatus.NotFound), 404); - assert.equal(statusExtractor(exports.HttpStatus.ServerError), 500); - assert.equal(statusExtractor(exports.HttpStatus.Unknown), -1); - - const apiHandler = processor.makeAPIResultHandler(); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Success, param0: "done" }), "Success: done"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Failure, param0: 500 }), "Failure: 500"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Info }), "Info"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Flag, param0: true }), "Flag: true"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Rate, param0: 1.5 }), "Rate: 1.5"); - assert.equal(apiHandler({ tag: exports.APIResult.Tag.Precise, param0: 3.14159 }), "Precise: 3.14159"); - - const optDirResult = processor.processOptionalDirection((dir) => { - return dir !== null ? `Dir: ${dir}` : "Dir: null"; - }); - assert.equal(optDirResult, `Dir: ${exports.Direction.North} | Dir: null`); - - const optThemeResult = processor.processOptionalTheme((theme) => { - return theme !== null ? `Theme: ${theme}` : "Theme: null"; - }); - assert.equal(optThemeResult, `Theme: ${exports.Theme.Light} | Theme: null`); - - const optApiResult = processor.processOptionalAPIResult((result) => { - if (result === null) return "Result: null"; - if (result.tag === exports.APIResult.Tag.Success) { - return `Result: Success(${result.param0})`; - } - return "Result: other"; - }); - assert.equal(optApiResult, "Result: Success(ok) | Result: null"); - - const optDirFormatter = processor.makeOptionalDirectionFormatter(); - assert.equal(optDirFormatter(exports.Direction.North), "N"); - assert.equal(optDirFormatter(exports.Direction.South), "S"); - assert.equal(optDirFormatter(exports.Direction.East), "E"); - assert.equal(optDirFormatter(exports.Direction.West), "W"); - assert.equal(optDirFormatter(null), "nil"); - - processor.release(); -} /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ function testStructSupport(exports) { @@ -984,6 +885,9 @@ function testStructSupport(exports) { const data2 = { x: 0.0, y: 0.0, label: "", optCount: null, optFlag: null }; assert.deepEqual(exports.roundTripDataPoint(data2), data2); + const publicPoint = { x: 9, y: -3 }; + assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); + const pointerFields1 = { raw: 1, mutRaw: 4, opaque: 1024, ptr: 65536, mutPtr: 2 }; assert.deepEqual(exports.roundTripPointerFields(pointerFields1), pointerFields1); @@ -1154,6 +1058,32 @@ function testStructSupport(exports) { optionalRatio: null }; assert.deepEqual(exports.roundTripMeasurementConfig(mc2), mc2); + + // Struct with JSObject field + const containerObj1 = { value: "hello", nested: { x: 1 } }; + const containerObj2 = { items: [1, 2, 3] }; + const container1 = { object: containerObj1, optionalObject: containerObj2 }; + const containerResult1 = exports.roundTripJSObjectContainer(container1); + assert.equal(containerResult1.object, containerObj1); + assert.equal(containerResult1.optionalObject, containerObj2); + + const container2 = { object: containerObj1, optionalObject: null }; + const containerResult2 = exports.roundTripJSObjectContainer(container2); + assert.equal(containerResult2.object, containerObj1); + assert.equal(containerResult2.optionalObject, null); + + // Struct with @JSClass field + const foo1 = new ImportedFoo("first"); + const foo2 = new ImportedFoo("second"); + const fooContainer1 = { foo: foo1, optionalFoo: foo2 }; + const fooContainerResult1 = exports.roundTripFooContainer(fooContainer1); + assert.equal(fooContainerResult1.foo.value, "first"); + assert.equal(fooContainerResult1.optionalFoo.value, "second"); + + const fooContainer2 = { foo: foo1, optionalFoo: null }; + const fooContainerResult2 = exports.roundTripFooContainer(fooContainer2); + assert.equal(fooContainerResult2.foo.value, "first"); + assert.equal(fooContainerResult2.optionalFoo, null); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ @@ -1385,6 +1315,8 @@ function testArraySupport(exports) { assert.deepEqual(exports.roundTripUnsafeRawPointerArray(pointerValues), pointerValues); assert.deepEqual(exports.roundTripUnsafeMutableRawPointerArray(pointerValues), pointerValues); assert.deepEqual(exports.roundTripOpaquePointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafePointerArray(pointerValues), pointerValues); + assert.deepEqual(exports.roundTripUnsafeMutablePointerArray(pointerValues), pointerValues); assert.deepEqual(exports.roundTripUnsafeRawPointerArray([]), []); // Default values @@ -1425,6 +1357,36 @@ function testArraySupport(exports) { assert.equal(result[0].count, 1); helper1.release(); + + // JSObject arrays + const jsObj1 = { a: 1, b: "hello" }; + const jsObj2 = { x: [1, 2, 3], y: { nested: true } }; + const jsObjResult = exports.roundTripJSObjectArray([jsObj1, jsObj2]); + assert.equal(jsObjResult.length, 2); + assert.equal(jsObjResult[0], jsObj1); + assert.equal(jsObjResult[1], jsObj2); + assert.deepEqual(exports.roundTripJSObjectArray([]), []); + + const optJsResult = exports.roundTripOptionalJSObjectArray([jsObj1, null, jsObj2]); + assert.equal(optJsResult.length, 3); + assert.equal(optJsResult[0], jsObj1); + assert.equal(optJsResult[1], null); + assert.equal(optJsResult[2], jsObj2); + + // @JSClass struct arrays + const foo1 = new ImportedFoo("first"); + const foo2 = new ImportedFoo("second"); + const fooResult = exports.roundTripFooArray([foo1, foo2]); + assert.equal(fooResult.length, 2); + assert.equal(fooResult[0].value, "first"); + assert.equal(fooResult[1].value, "second"); + assert.deepEqual(exports.roundTripFooArray([]), []); + + const optFooResult = exports.roundTripOptionalFooArray([foo1, null, foo2]); + assert.equal(optFooResult.length, 3); + assert.equal(optFooResult[0].value, "first"); + assert.equal(optFooResult[1], null); + assert.equal(optFooResult[2].value, "second"); } /** @param {import('./../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ diff --git a/Utilities/build-examples.sh b/Utilities/build-examples.sh index 4d99c8627..bc84e6943 100755 --- a/Utilities/build-examples.sh +++ b/Utilities/build-examples.sh @@ -2,7 +2,7 @@ set -euo pipefail -EXCLUDED_EXAMPLES=("Embedded") +EXCLUDED_EXAMPLES=() for example in Examples/*; do skip_example=false diff --git a/package-lock.json b/package-lock.json index bf7f36315..9366b618d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,8 @@ "rollup": "^4.37.0", "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", - "typescript": "^5.8.2" + "typescript": "^5.8.2", + "vitest": "^4.0.18" } }, "node_modules/@babel/code-frame": { @@ -51,11 +52,454 @@ "integrity": "sha512-54kpBQX69TZ8I1zyDC8sziv/zPT1zoIadv3CmdIZNZ5WDF1houMjAzRZ3dwWvhXObiEBjOxXyS8Ja7vA0EfGEQ==", "dev": true }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", - "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", - "dev": true + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" }, "node_modules/@rollup/plugin-typescript": { "version": "12.1.2", @@ -108,9 +552,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.37.0.tgz", - "integrity": "sha512-l7StVw6WAa8l3vA1ov80jyetOAEo1FtHvZDbzXDO/02Sq/QVvqlHkYoFwDJPIMj0GKiistsBudfx5tGFnwYWDQ==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", + "integrity": "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==", "cpu": [ "arm" ], @@ -122,9 +566,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.37.0.tgz", - "integrity": "sha512-6U3SlVyMxezt8Y+/iEBcbp945uZjJwjZimu76xoG7tO1av9VO691z8PkhzQ85ith2I8R2RddEPeSfcbyPfD4hA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.1.tgz", + "integrity": "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==", "cpu": [ "arm64" ], @@ -136,9 +580,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.37.0.tgz", - "integrity": "sha512-+iTQ5YHuGmPt10NTzEyMPbayiNTcOZDWsbxZYR1ZnmLnZxG17ivrPSWFO9j6GalY0+gV3Jtwrrs12DBscxnlYA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.1.tgz", + "integrity": "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==", "cpu": [ "arm64" ], @@ -150,9 +594,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.37.0.tgz", - "integrity": "sha512-m8W2UbxLDcmRKVjgl5J/k4B8d7qX2EcJve3Sut7YGrQoPtCIQGPH5AMzuFvYRWZi0FVS0zEY4c8uttPfX6bwYQ==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.1.tgz", + "integrity": "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==", "cpu": [ "x64" ], @@ -164,9 +608,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.37.0.tgz", - "integrity": "sha512-FOMXGmH15OmtQWEt174v9P1JqqhlgYge/bUjIbiVD1nI1NeJ30HYT9SJlZMqdo1uQFyt9cz748F1BHghWaDnVA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.1.tgz", + "integrity": "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==", "cpu": [ "arm64" ], @@ -178,9 +622,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.37.0.tgz", - "integrity": "sha512-SZMxNttjPKvV14Hjck5t70xS3l63sbVwl98g3FlVVx2YIDmfUIy29jQrsw06ewEYQ8lQSuY9mpAPlmgRD2iSsA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.1.tgz", + "integrity": "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==", "cpu": [ "x64" ], @@ -192,9 +636,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.37.0.tgz", - "integrity": "sha512-hhAALKJPidCwZcj+g+iN+38SIOkhK2a9bqtJR+EtyxrKKSt1ynCBeqrQy31z0oWU6thRZzdx53hVgEbRkuI19w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.1.tgz", + "integrity": "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==", "cpu": [ "arm" ], @@ -206,9 +650,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.37.0.tgz", - "integrity": "sha512-jUb/kmn/Gd8epbHKEqkRAxq5c2EwRt0DqhSGWjPFxLeFvldFdHQs/n8lQ9x85oAeVb6bHcS8irhTJX2FCOd8Ag==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.1.tgz", + "integrity": "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==", "cpu": [ "arm" ], @@ -220,9 +664,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.37.0.tgz", - "integrity": "sha512-oNrJxcQT9IcbcmKlkF+Yz2tmOxZgG9D9GRq+1OE6XCQwCVwxixYAa38Z8qqPzQvzt1FCfmrHX03E0pWoXm1DqA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", + "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", "cpu": [ "arm64" ], @@ -234,9 +678,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.37.0.tgz", - "integrity": "sha512-pfxLBMls+28Ey2enpX3JvjEjaJMBX5XlPCZNGxj4kdJyHduPBXtxYeb8alo0a7bqOoWZW2uKynhHxF/MWoHaGQ==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", + "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", "cpu": [ "arm64" ], @@ -247,10 +691,24 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.37.0.tgz", - "integrity": "sha512-yCE0NnutTC/7IGUq/PUHmoeZbIwq3KRh02e9SfFh7Vmc1Z7atuJRYWhRME5fKgT8aS20mwi1RyChA23qSyRGpA==", + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.1.tgz", + "integrity": "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.1.tgz", + "integrity": "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==", "cpu": [ "loong64" ], @@ -261,10 +719,24 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.37.0.tgz", - "integrity": "sha512-NxcICptHk06E2Lh3a4Pu+2PEdZ6ahNHuK7o6Np9zcWkrBMuv21j10SQDJW3C9Yf/A/P7cutWoC/DptNLVsZ0VQ==", + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.1.tgz", + "integrity": "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.1.tgz", + "integrity": "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==", "cpu": [ "ppc64" ], @@ -276,9 +748,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.37.0.tgz", - "integrity": "sha512-PpWwHMPCVpFZLTfLq7EWJWvrmEuLdGn1GMYcm5MV7PaRgwCEYJAwiN94uBuZev0/J/hFIIJCsYw4nLmXA9J7Pw==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.1.tgz", + "integrity": "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==", "cpu": [ "riscv64" ], @@ -290,9 +762,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.37.0.tgz", - "integrity": "sha512-DTNwl6a3CfhGTAOYZ4KtYbdS8b+275LSLqJVJIrPa5/JuIufWWZ/QFvkxp52gpmguN95eujrM68ZG+zVxa8zHA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.1.tgz", + "integrity": "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==", "cpu": [ "riscv64" ], @@ -304,103 +776,361 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.37.0.tgz", - "integrity": "sha512-hZDDU5fgWvDdHFuExN1gBOhCuzo/8TMpidfOR+1cPZJflcEzXdCy1LjnklQdW8/Et9sryOPJAKAQRw8Jq7Tg+A==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.1.tgz", + "integrity": "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==", "cpu": [ "s390x" ], "dev": true, "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz", + "integrity": "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz", + "integrity": "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.1.tgz", + "integrity": "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.1.tgz", + "integrity": "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.1.tgz", + "integrity": "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.1.tgz", + "integrity": "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.1.tgz", + "integrity": "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.1.tgz", + "integrity": "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.13.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.14.tgz", + "integrity": "sha512-Zs/Ollc1SJ8nKUAgc7ivOEdIBM8JAKgrqqUYi2J997JuKO7/tpQC+WCetQ1sypiKCQWHdvdg9wBNpUPEWZae7w==", + "dev": true, + "peer": true, + "dependencies": { + "undici-types": "~6.20.0" + } + }, + "node_modules/@vitest/expect": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz", + "integrity": "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.18.tgz", + "integrity": "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.0.18", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.18.tgz", + "integrity": "sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.18.tgz", + "integrity": "sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.18", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.37.0.tgz", - "integrity": "sha512-pKivGpgJM5g8dwj0ywBwe/HeVAUSuVVJhUTa/URXjxvoyTT/AxsLTAbkHkDHG7qQxLoW2s3apEIl26uUe08LVQ==", - "cpu": [ - "x64" - ], + "node_modules/@vitest/snapshot": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.18.tgz", + "integrity": "sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.37.0.tgz", - "integrity": "sha512-E2lPrLKE8sQbY/2bEkVTGDEk4/49UYRVWgj90MY8yPjpnGBQ+Xi1Qnr7b7UIWw1NOggdFQFOLZ8+5CzCiz143w==", - "cpu": [ - "x64" - ], + "node_modules/@vitest/spy": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.18.tgz", + "integrity": "sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "funding": { + "url": "https://opencollective.com/vitest" + } }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.37.0.tgz", - "integrity": "sha512-Jm7biMazjNzTU4PrQtr7VS8ibeys9Pn29/1bm4ph7CP2kf21950LgN+BaE2mJ1QujnvOc6p54eWWiVvn05SOBg==", - "cpu": [ - "arm64" - ], + "node_modules/@vitest/utils": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.18.tgz", + "integrity": "sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.37.0.tgz", - "integrity": "sha512-e3/1SFm1OjefWICB2Ucstg2dxYDkDTZGDYgwufcbsxTHyqQps1UQf33dFEChBNmeSsTOyrjw2JJq0zbG5GF6RA==", - "cpu": [ - "ia32" - ], + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "engines": { + "node": ">=12" + } }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.37.0.tgz", - "integrity": "sha512-LWbXUBwn/bcLx2sSsqy7pK5o+Nr+VCoRoAohfJ5C/aBio9nfJmGQqHAhU6pwxV/RmyTk5AqdySma7uwWGlmeuA==", - "cpu": [ - "x64" - ], + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "engines": { + "node": ">=18" + } }, - "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", "dev": true, "license": "MIT" }, - "node_modules/@types/node": { - "version": "22.13.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.14.tgz", - "integrity": "sha512-Zs/Ollc1SJ8nKUAgc7ivOEdIBM8JAKgrqqUYi2J997JuKO7/tpQC+WCetQ1sypiKCQWHdvdg9wBNpUPEWZae7w==", + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", "dev": true, - "dependencies": { - "undici-types": "~6.20.0" + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" } }, "node_modules/estree-walker": { @@ -410,6 +1140,34 @@ "dev": true, "license": "MIT" }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -472,14 +1230,45 @@ "optional": true }, "node_modules/magic-string": { - "version": "0.30.17", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", - "integrity": "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==", + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0" + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", @@ -487,17 +1276,23 @@ "dev": true, "license": "MIT" }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "optional": true + "dev": true }, "node_modules/picomatch": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", - "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", "engines": { @@ -539,6 +1334,35 @@ "node": ">=18" } }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, "node_modules/prettier": { "version": "3.5.3", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz", @@ -577,14 +1401,14 @@ } }, "node_modules/rollup": { - "version": "4.37.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.37.0.tgz", - "integrity": "sha512-iAtQy/L4QFU+rTJ1YUjXqJOJzuwEghqWzCEYD2FEghT7Gsy1VdABntrO4CLopA5IkflTyqNiLNwPcOJ3S7UKLg==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", + "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@types/estree": "1.0.6" + "@types/estree": "1.0.8" }, "bin": { "rollup": "dist/bin/rollup" @@ -594,26 +1418,31 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.37.0", - "@rollup/rollup-android-arm64": "4.37.0", - "@rollup/rollup-darwin-arm64": "4.37.0", - "@rollup/rollup-darwin-x64": "4.37.0", - "@rollup/rollup-freebsd-arm64": "4.37.0", - "@rollup/rollup-freebsd-x64": "4.37.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.37.0", - "@rollup/rollup-linux-arm-musleabihf": "4.37.0", - "@rollup/rollup-linux-arm64-gnu": "4.37.0", - "@rollup/rollup-linux-arm64-musl": "4.37.0", - "@rollup/rollup-linux-loongarch64-gnu": "4.37.0", - "@rollup/rollup-linux-powerpc64le-gnu": "4.37.0", - "@rollup/rollup-linux-riscv64-gnu": "4.37.0", - "@rollup/rollup-linux-riscv64-musl": "4.37.0", - "@rollup/rollup-linux-s390x-gnu": "4.37.0", - "@rollup/rollup-linux-x64-gnu": "4.37.0", - "@rollup/rollup-linux-x64-musl": "4.37.0", - "@rollup/rollup-win32-arm64-msvc": "4.37.0", - "@rollup/rollup-win32-ia32-msvc": "4.37.0", - "@rollup/rollup-win32-x64-msvc": "4.37.0", + "@rollup/rollup-android-arm-eabi": "4.57.1", + "@rollup/rollup-android-arm64": "4.57.1", + "@rollup/rollup-darwin-arm64": "4.57.1", + "@rollup/rollup-darwin-x64": "4.57.1", + "@rollup/rollup-freebsd-arm64": "4.57.1", + "@rollup/rollup-freebsd-x64": "4.57.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", + "@rollup/rollup-linux-arm-musleabihf": "4.57.1", + "@rollup/rollup-linux-arm64-gnu": "4.57.1", + "@rollup/rollup-linux-arm64-musl": "4.57.1", + "@rollup/rollup-linux-loong64-gnu": "4.57.1", + "@rollup/rollup-linux-loong64-musl": "4.57.1", + "@rollup/rollup-linux-ppc64-gnu": "4.57.1", + "@rollup/rollup-linux-ppc64-musl": "4.57.1", + "@rollup/rollup-linux-riscv64-gnu": "4.57.1", + "@rollup/rollup-linux-riscv64-musl": "4.57.1", + "@rollup/rollup-linux-s390x-gnu": "4.57.1", + "@rollup/rollup-linux-x64-gnu": "4.57.1", + "@rollup/rollup-linux-x64-musl": "4.57.1", + "@rollup/rollup-openbsd-x64": "4.57.1", + "@rollup/rollup-openharmony-arm64": "4.57.1", + "@rollup/rollup-win32-arm64-msvc": "4.57.1", + "@rollup/rollup-win32-ia32-msvc": "4.57.1", + "@rollup/rollup-win32-x64-gnu": "4.57.1", + "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" } }, @@ -639,6 +1468,37 @@ "typescript": "^4.5 || ^5.0" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", @@ -652,6 +1512,50 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -680,6 +1584,191 @@ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", "dev": true + }, + "node_modules/vite": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/vitest": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.18.tgz", + "integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.0.18", + "@vitest/mocker": "4.0.18", + "@vitest/pretty-format": "4.0.18", + "@vitest/runner": "4.0.18", + "@vitest/snapshot": "4.0.18", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.10.0", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.18", + "@vitest/browser-preview": "4.0.18", + "@vitest/browser-webdriverio": "4.0.18", + "@vitest/ui": "4.0.18", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } } } } diff --git a/package.json b/package.json index da7d5356d..509cddde2 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,8 @@ "build:clean": "rm -rf Runtime/lib", "build:ts": "cd Runtime; rollup -c", "prepublishOnly": "npm run build", - "format": "prettier --write Runtime/src" + "format": "prettier --write Runtime/src", + "check:bridgejs-dts": "tsc --project Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json" }, "keywords": [ "Swift", @@ -42,6 +43,7 @@ "rollup": "^4.37.0", "rollup-plugin-dts": "^6.2.1", "tslib": "^2.8.1", - "typescript": "^5.8.2" + "typescript": "^5.8.2", + "vitest": "^4.0.18" } } diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..c13ef64e3 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "strict": true, + "skipLibCheck": true + } +}