diff --git a/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/AsyncCancellationProbe.swift b/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/AsyncCancellationProbe.swift new file mode 100644 index 000000000..a0489fbaa --- /dev/null +++ b/Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/AsyncCancellationProbe.swift @@ -0,0 +1,101 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Synchronization + +public final class AsyncCancellationProbe: Sendable { + private struct State { + var cancelled = false + var waitingToReturn: CheckedContinuation? + var destroyedResults: Int32 = 0 + } + + private let state = Mutex(State()) + + public init() {} + + public func waitForCancellation() async throws -> Int64 { + do { + try await Task.sleep(for: .seconds(60)) + return 1 + } catch { + state.withLock { $0.cancelled = Task.isCancelled } + throw error + } + } + + public func waitForOptionalCancellation() async throws -> Int64? { + try await waitForCancellation() + } + + public func makeOwnedResult() async -> AsyncOwnedResult { + newOwnedResult() + } + + public func makeOwnedResults() async -> [AsyncOwnedResult] { + [newOwnedResult(), newOwnedResult()] + } + + public func makeOwnedTuple() async -> (AsyncOwnedResult, [String: AsyncOwnedResult], Set) { + (newOwnedResult(), ["value": newOwnedResult()], [42]) + } + + private func newOwnedResult() -> AsyncOwnedResult { + AsyncOwnedResult { [self] in state.withLock { $0.destroyedResults += 1 } } + } + + public func returnOwnedResultWhenAllowed() async -> AsyncOwnedResult { + await withCheckedContinuation { continuation in + state.withLock { $0.waitingToReturn = continuation } + } + return newOwnedResult() + } + + public func returnOwnedResultAfterCancellation() async -> AsyncOwnedResult { + _ = try? await waitForCancellation() + return newOwnedResult() + } + + public func returnOwnedResultsAfterCancellation() async -> [AsyncOwnedResult] { + _ = try? await waitForCancellation() + return [newOwnedResult(), newOwnedResult()] + } + + public func wasCancelled() -> Bool { state.withLock { $0.cancelled } } + + public func isWaitingToReturn() -> Bool { state.withLock { $0.waitingToReturn != nil } } + + public func allowReturn() { + let continuation = state.withLock { + let continuation = $0.waitingToReturn + $0.waitingToReturn = nil + return continuation + } + continuation?.resume() + } + + public func destroyedResults() -> Int32 { state.withLock { $0.destroyedResults } } +} + +public final class AsyncOwnedResult: Sendable { + private let onDestroy: @Sendable () -> Void + + fileprivate init(onDestroy: @escaping @Sendable () -> Void) { + self.onDestroy = onDestroy + } + + deinit { + onDestroy() + } +} diff --git a/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/AsyncCancellationTest.java b/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/AsyncCancellationTest.java new file mode 100644 index 000000000..e7a91f379 --- /dev/null +++ b/Samples/SwiftJavaExtractJNISampleApp/src/test/java/com/example/swift/AsyncCancellationTest.java @@ -0,0 +1,169 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +package com.example.swift; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.swift.swiftkit.core.SwiftArena; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; + +import static org.junit.jupiter.api.Assertions.*; + +public class AsyncCancellationTest { + @ParameterizedTest + @ValueSource(strings = {"scalar", "optional"}) + void cancelsSwiftTask(String resultType) throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + Future future = switch (resultType) { + case "scalar" -> probe.waitForCancellation(); + case "optional" -> probe.waitForOptionalCancellation(); + default -> throw new IllegalArgumentException(); + }; + assertTrue(future.cancel(false)); + awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation"); + } + } + + @ParameterizedTest + @ValueSource(strings = {"orTimeout", "completeOnTimeout", "complete", "completeExceptionally"}) + void completionCancelsSwiftTask(String completion) throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + var future = probe.waitForCancellation(); + switch (completion) { + case "orTimeout" -> { + future.orTimeout(10, TimeUnit.MILLISECONDS); + var failure = assertThrows(ExecutionException.class, () -> get(future)); + assertInstanceOf(TimeoutException.class, failure.getCause()); + } + case "completeOnTimeout" -> { + future.completeOnTimeout(42L, 10, TimeUnit.MILLISECONDS); + assertEquals(42L, get(future)); + } + case "complete" -> { + assertTrue(future.complete(42L)); + assertEquals(42L, get(future)); + } + case "completeExceptionally" -> { + var error = new IllegalStateException("Completed by caller"); + assertTrue(future.completeExceptionally(error)); + var failure = assertThrows(ExecutionException.class, () -> get(future)); + assertSame(error, failure.getCause()); + } + default -> throw new IllegalArgumentException(); + } + awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation"); + } + } + + @Test + void closingArenaReleasesResult() throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + try (var resultArena = SwiftArena.ofConfined()) { + var result = get(probe.makeOwnedResult(resultArena)); + assertFalse(result.$cleanup().isDestroyed()); + assertEquals(0, probe.destroyedResults()); + } + awaitCondition(() -> probe.destroyedResults() == 1, "Swift result was not destroyed"); + } + } + + @Test + void closingArenaReleasesTupleResults() throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + try (var resultArena = SwiftArena.ofConfined()) { + assertNotNull(get(probe.makeOwnedTuple(resultArena))); + assertEquals(0, probe.destroyedResults()); + } + awaitCondition(() -> probe.destroyedResults() == 2, "Swift tuple elements were not destroyed"); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void cancelBeforeArenaTakesOwnership(int expectedDestroyed) throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + try (var resultArena = SwiftArena.ofConfined()) { + Future future = switch (expectedDestroyed) { + case 1 -> probe.returnOwnedResultAfterCancellation(resultArena); + case 2 -> probe.returnOwnedResultsAfterCancellation(resultArena); + default -> throw new IllegalArgumentException(); + }; + assertTrue(future.cancel(false)); + awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation"); + } + awaitCondition(() -> probe.destroyedResults() == expectedDestroyed, "Late Swift results were not destroyed"); + } + } + + @Test + void cancelAfterArenaTakesOwnership() throws Exception { + try (var probeArena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(probeArena); + try (var resultArena = SwiftArena.ofConfined()) { + var futureToCancel = new AtomicReference>(); + Future future = probe.returnOwnedResultWhenAllowed(instance -> { + resultArena.register(instance); + futureToCancel.get().cancel(false); + }); + futureToCancel.set(future); + + awaitCondition(probe::isWaitingToReturn, "Swift task did not pause before returning"); + probe.allowReturn(); + + assertThrows(CancellationException.class, () -> get(future)); + assertEquals(0, probe.destroyedResults()); + } + awaitCondition(() -> probe.destroyedResults() == 1, "Swift result was not destroyed"); + } + } + + @Test + void releaseElementsIfArenaIsAlreadyClosed() throws Exception { + try (var arena = SwiftArena.ofConfined()) { + var probe = AsyncCancellationProbe.init(arena); + var closedArena = SwiftArena.ofConfined(); + closedArena.close(); + + var failure = assertThrows(ExecutionException.class, () -> get(probe.makeOwnedResults(closedArena))); + assertEquals("SwiftArena is already closed!", failure.getCause().getMessage()); + awaitCondition(() -> probe.destroyedResults() == 2, "Swift array elements were not destroyed"); + } + } + + private static T get(Future future) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(5, TimeUnit.SECONDS); + } + + private static void awaitCondition(BooleanSupplier condition, String message) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!condition.getAsBoolean()) { + assertTrue(System.nanoTime() - deadline < 0, message); + Thread.sleep(5); + } + } +} diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift index 9ef746282..2fa7eae9f 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift @@ -947,7 +947,7 @@ extension JNISwift2JavaGenerator { } if translatedSignature.requiresSwiftArena { - parameters.append("SwiftArena swiftArena") + parameters.append("SwiftArena \(ArenaParameterName.caller)") } if let importedFunc { TranslatedDocumentation.printDocumentation( @@ -1016,8 +1016,9 @@ extension JNISwift2JavaGenerator { // Indirect return receivers for outParameter in translatedFunctionSignature.result.outParameters { + let initializer = outParameter.allocation.render(type: outParameter.type, printer: &printer) printer.print( - "\(outParameter.type) \(outParameter.name) = \(outParameter.allocation.render(type: outParameter.type));" + "\(outParameter.type) \(outParameter.name) = \(initializer);" ) arguments.append(outParameter.name) } diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaTranslation.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaTranslation.swift index 7bc7c823b..d9a1d2101 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaTranslation.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaTranslation.swift @@ -19,6 +19,11 @@ import SwiftJavaJNICore import SwiftSyntax extension JNISwift2JavaGenerator { + enum ArenaParameterName { + static let caller = "swiftArena" + static let asyncResult = "resultArena$" + } + var javaTranslator: JavaTranslation { JavaTranslation( config: config, @@ -131,6 +136,7 @@ extension JNISwift2JavaGenerator { /// Module-qualified identities of extracted types that are surfaced to Java as `SwiftError` exceptions. let errorTypes: Set var javaIdentifiers: JavaIdentifierFactory + var resultArenaName = ArenaParameterName.caller func translate(enumCase: ExtractedEnumCase) throws -> TranslatedEnumCase { let methodName = "" // TODO: Used for closures, replace with better name? @@ -210,7 +216,12 @@ extension JNISwift2JavaGenerator { let javaName = javaIdentifiers.makeJavaMethodName(decl) // Swift -> Java - var translatedFunctionSignature = try self.translate( + let isAsync = decl.isAsync || decl.isIsolated || decl.isImplicitlyAsync + var signatureTranslation = self + if isAsync && config.effectiveAsyncFuncMode == .completableFuture { + signatureTranslation.resultArenaName = ArenaParameterName.asyncResult + } + var translatedFunctionSignature = try signatureTranslation.translate( functionSignature: decl.functionSignature, methodName: javaName, parentName: parentName, @@ -255,9 +266,7 @@ extension JNISwift2JavaGenerator { } // Handle async methods and isolated methods - if decl.functionSignature.isAsync || decl.functionSignature.isIsolated - || decl.functionSignature.isImplicitlyAsync - { + if isAsync { self.convertToAsync( translatedFunctionSignature: &translatedFunctionSignature, nativeFunctionSignature: &nativeFunctionSignature, @@ -375,6 +384,7 @@ extension JNISwift2JavaGenerator { selfTypeParameter: selfTypeParameter, parameters: parameters, result: resultType, + requiresSwiftArena: resultType.conversion.requiresSwiftArena, exceptions: exceptions, ) } @@ -696,40 +706,27 @@ extension JNISwift2JavaGenerator { originalFunctionSignature: SwiftFunctionSignature, mode: JExtractAsyncFuncMode, ) { - // Update translated function - let nativeFutureType: JavaType + let result = translatedFunctionSignature.result + let nativeResultType = nativeFunctionSignature.result.javaType + let receiver: OutParameter let translatedFutureType: JavaType - let completeMethodID: String - let completeExceptionallyMethodID: String + let conversion: JavaNativeConversionStep switch mode { case .completableFuture: - nativeFutureType = .completableFuture(nativeFunctionSignature.result.javaType) - translatedFutureType = .completableFuture(translatedFunctionSignature.result.javaType) - completeMethodID = "_JNIMethodIDCache.CompletableFuture.complete" - completeExceptionallyMethodID = "_JNIMethodIDCache.CompletableFuture.completeExceptionally" + translatedFutureType = .completableFuture(result.javaType) + receiver = .init( + name: "resultSink$", + type: .SwiftAsyncResultSink(nativeResultType, result.javaType), + allocation: .asyncResultSink(result.conversion) + ) + conversion = .method(.constant(receiver.name), function: "future") case .legacyFuture: - nativeFutureType = .simpleCompletableFuture(nativeFunctionSignature.result.javaType) - translatedFutureType = .future(translatedFunctionSignature.result.javaType) - completeMethodID = "_JNIMethodIDCache.SimpleCompletableFuture.complete" - completeExceptionallyMethodID = "_JNIMethodIDCache.SimpleCompletableFuture.completeExceptionally" - } - - let futureOutParameter = OutParameter( - name: "future$", - type: nativeFutureType, - allocation: .new, - ) - - let result = translatedFunctionSignature.result - translatedFunctionSignature.result = TranslatedResult( - javaType: translatedFutureType, - nativeJavaType: .void, - annotations: result.annotations, - outParameters: result.outParameters + [futureOutParameter], - conversion: .method( - .constant("future$"), + translatedFutureType = .future(result.javaType) + receiver = .init(name: "future$", type: .simpleCompletableFuture(nativeResultType), allocation: .new) + conversion = .method( + .constant(receiver.name), function: "thenApply", arguments: [ .lambda( @@ -738,18 +735,26 @@ extension JNISwift2JavaGenerator { ) ] ) + } + + translatedFunctionSignature.result = TranslatedResult( + javaType: translatedFutureType, + nativeJavaType: .void, + annotations: result.annotations, + outParameters: result.outParameters + [receiver], + conversion: conversion ) - // Update native function nativeFunctionSignature.result.conversion = .asyncCompleteFuture( swiftFunctionResultType: originalFunctionSignature.result.type, nativeFunctionSignature: nativeFunctionSignature, isThrowing: originalFunctionSignature.isThrowing || originalFunctionSignature.isImplicitlyThrowing, - completeMethodID: completeMethodID, - completeExceptionallyMethodID: completeExceptionallyMethodID, + mode: mode ) nativeFunctionSignature.result.javaType = .void - nativeFunctionSignature.result.outParameters.append(.init(name: "result_future", type: nativeFutureType)) + nativeFunctionSignature.result.outParameters.append( + .init(name: mode == .completableFuture ? "result_sink" : "result_future", type: receiver.type) + ) } func translateFunctionParameter( @@ -1039,7 +1044,8 @@ extension JNISwift2JavaGenerator { .member(.constant(resultName), field: "selfPointer"), .member(.constant(resultName), field: "selfTypePointer"), ]), - javaType + javaType, + arena: resultArenaName ) ) } else { @@ -1048,7 +1054,7 @@ extension JNISwift2JavaGenerator { nativeJavaType: .long, annotations: resultAnnotations, outParameters: [], - conversion: .wrapMemoryAddressUnsafe(.placeholder, javaType), + conversion: .wrapMemoryAddressUnsafe(.placeholder, javaType, arena: resultArenaName), ) } @@ -1097,7 +1103,8 @@ extension JNISwift2JavaGenerator { .member(.constant(resultName), field: "selfPointer"), .member(.constant(resultName), field: "selfTypePointer"), ]), - boxJavaType + boxJavaType, + arena: resultArenaName ) ) @@ -1593,7 +1600,7 @@ extension JNISwift2JavaGenerator { arguments: [ .lambda( args: ["pointer"], - body: .wrapMemoryAddressUnsafe(.constant("pointer"), javaType), + body: .wrapMemoryAddressUnsafe(.constant("pointer"), javaType, arena: resultArenaName), ) ], ), @@ -1677,7 +1684,7 @@ extension JNISwift2JavaGenerator { javaType: dictType, nativeJavaType: .long, outParameters: [], - conversion: .wrapMemoryAddressUnsafe(.placeholder, dictType), + conversion: .wrapMemoryAddressUnsafe(.placeholder, dictType, arena: resultArenaName), ) } @@ -1720,7 +1727,7 @@ extension JNISwift2JavaGenerator { javaType: setType, nativeJavaType: .long, outParameters: [], - conversion: .wrapMemoryAddressUnsafe(.placeholder, setType), + conversion: .wrapMemoryAddressUnsafe(.placeholder, setType, arena: resultArenaName), ) } } @@ -1797,6 +1804,7 @@ extension JNISwift2JavaGenerator { var selfTypeParameter: TranslatedParameter? var parameters: [TranslatedParameter] var result: TranslatedResult + var requiresSwiftArena: Bool var exceptions: [JavaExceptionType] // if the result type implied any annotations, @@ -1804,10 +1812,6 @@ extension JNISwift2JavaGenerator { var annotations: [JavaAnnotation] { self.result.annotations } - - var requiresSwiftArena: Bool { - self.result.conversion.requiresSwiftArena - } } /// Represent a Swift API parameter translated to Java. @@ -1836,8 +1840,9 @@ extension JNISwift2JavaGenerator { enum Allocation { case newArray(JavaType, size: Int) case new + case asyncResultSink(JavaNativeConversionStep) - func render(type: JavaType) -> String { + func render(type: JavaType, printer: inout JavaPrinter) -> String { switch self { case .newArray(let javaType, let size): // For array element types like byte[], we need "new byte[size][]" @@ -1852,6 +1857,16 @@ extension JNISwift2JavaGenerator { case .new: return "new \(type)()" + + case .asyncResultSink(let conversion): + let typeName = type.fullyQualifiedClassName! + if conversion.requiresSwiftArena { + let mapper = JavaNativeConversionStep.lambda(args: ["futureResult$", ArenaParameterName.asyncResult], body: conversion) + return "\(typeName).create(\(ArenaParameterName.caller), \(mapper.render(&printer, "futureResult$")))" + } else { + let mapper = JavaNativeConversionStep.lambda(args: ["futureResult$"], body: conversion) + return "\(typeName).create(\(mapper.render(&printer, "futureResult$")))" + } } } } @@ -1902,13 +1917,13 @@ extension JNISwift2JavaGenerator { indirect case typeMetadataAddress(JavaNativeConversionStep) /// Call `new \(Type)(\(placeholder), swiftArena)` - indirect case constructSwiftValue(JavaNativeConversionStep, JavaType) + indirect case constructSwiftValue(JavaNativeConversionStep, JavaType, arena: String) /// Call `new \(Type)(\(placeholder))` indirect case constructJavaClass(JavaNativeConversionStep, JavaType) /// Call the `MyType.wrapMemoryAddressUnsafe` in order to wrap a memory address using the Java binding type - indirect case wrapMemoryAddressUnsafe(JavaNativeConversionStep, JavaType) + indirect case wrapMemoryAddressUnsafe(JavaNativeConversionStep, JavaType, arena: String) indirect case call(JavaNativeConversionStep, function: String) @@ -2014,11 +2029,11 @@ extension JNISwift2JavaGenerator { let inner = inner.render(&printer, placeholder) return "\(inner).$typeMetadataAddress()" - case .constructSwiftValue(let inner, let javaType): + case .constructSwiftValue(let inner, let javaType, let arena): let inner = inner.render(&printer, placeholder) - return "new \(javaType)(\(inner), swiftArena)" + return "new \(javaType)(\(inner), \(arena))" - case .wrapMemoryAddressUnsafe(let inner, let javaType): + case .wrapMemoryAddressUnsafe(let inner, let javaType, let arena): let inner = inner.render(&printer, placeholder) guard case .class(_, _, let typeParameters) = javaType else { fatalError("\(javaType) is not class.") @@ -2029,7 +2044,7 @@ extension JNISwift2JavaGenerator { } else { "" } - return "\(javaType.fullyQualifiedClassName!).\(genericClause)wrapMemoryAddressUnsafe(\(inner), swiftArena)" + return "\(javaType.fullyQualifiedClassName!).\(genericClause)wrapMemoryAddressUnsafe(\(inner), \(arena))" case .constructJavaClass(let inner, let javaType): let inner = inner.render(&printer, placeholder) @@ -2125,7 +2140,7 @@ extension JNISwift2JavaGenerator { return inner.render(&printer, placeholder) case .lambda(let args, let body): - var printer = JavaPrinter() + var printer = JavaPrinter(options: printer.options) printer.printBraceBlock("(\(args.joined(separator: .comma))) ->") { printer in let body = body.render(&printer, placeholder) if !body.isEmpty { diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+NativeTranslation.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+NativeTranslation.swift index 431b69262..231eeea58 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+NativeTranslation.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+NativeTranslation.swift @@ -1417,8 +1417,7 @@ extension JNISwift2JavaGenerator { swiftFunctionResultType: SwiftType, nativeFunctionSignature: NativeFunctionSignature, isThrowing: Bool, - completeMethodID: String, - completeExceptionallyMethodID: String + mode: JExtractAsyncFuncMode ) /// `{ (args) -> return body }` @@ -1916,10 +1915,12 @@ extension JNISwift2JavaGenerator { let swiftFunctionResultType, let nativeFunctionSignature, let isThrowing, - let completeMethodID, - let completeExceptionallyMethodID + let mode ): - var globalRefs: [String] = ["globalFuture"] + let cancellable = mode == .completableFuture + let resultParameter = cancellable ? "result_sink" : "result_future" + let receiver = cancellable ? "globalResultSink" : "globalFuture" + var globalRefs = [receiver] // Global ref all indirect returns for outParameter in nativeFunctionSignature.result.outParameters { @@ -1937,7 +1938,7 @@ extension JNISwift2JavaGenerator { printer.print( """ - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + nonisolated(unsafe) let \(receiver) = environment.interface.NewGlobalRef(environment, \(resultParameter)) """ ) @@ -1972,19 +1973,21 @@ extension JNISwift2JavaGenerator { } else { "await" } - if swiftFunctionResultType.isVoid { - printer.print("\(tryAwaitString) \(placeholderWithoutTry)") - printer.print("environment = try! JavaVirtualMachine.shared().environment()") - printer.print( - "_ = environment.interface.CallBooleanMethodA(environment, globalFuture, \(completeMethodID), [jvalue(l: nil)])" - ) + let isVoid = swiftFunctionResultType.isVoid + let binding = isVoid ? "" : "let swiftResult$ = " + printer.print("\(binding)\(tryAwaitString) \(placeholderWithoutTry)") + printer.print("environment = try! JavaVirtualMachine.shared().environment()") + if cancellable { + printer.print("if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(\(receiver), in: environment) { return }") + } + + let result: String + if isVoid { + result = "nil" } else { - printer.print("let swiftResult$ = \(tryAwaitString) \(placeholderWithoutTry)") - printer.print("environment = try! JavaVirtualMachine.shared().environment()") let inner = nativeFunctionSignature.result.conversion.render(&printer, "swiftResult$") - let result: String if nativeFunctionSignature.result.javaType.isVoid { - // The result was written to the out parameters, so the Java future is completed with Void + // The result was written to the out parameters. result = "nil" } else if nativeFunctionSignature.result.javaType.requiresBoxing { printer.print( @@ -1994,9 +1997,15 @@ extension JNISwift2JavaGenerator { } else { result = inner } + } + if cancellable { printer.print( - "_ = environment.interface.CallBooleanMethodA(environment, globalFuture, \(completeMethodID), [jvalue(l: \(result))])" + "SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(\(receiver), \(result), in: environment)" + ) + } else { + printer.print( + "_ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.SimpleCompletableFuture.complete, [jvalue(l: \(result))])" ) } } @@ -2018,13 +2027,20 @@ extension JNISwift2JavaGenerator { } printer.printBraceBlock("catch") { printer in // We might not be on the same thread after the suspension, so we need to attach the thread again. - printer.print( - """ - let catchEnvironment = try! JavaVirtualMachine.shared().environment() - let exception = catchEnvironment.makeJavaThrowable(for: error) - _ = catchEnvironment.interface.CallBooleanMethodA(catchEnvironment, globalFuture, \(completeExceptionallyMethodID), [jvalue(l: exception)]) - """ - ) + printer.print("let catchEnvironment = try! JavaVirtualMachine.shared().environment()") + if cancellable { + printer.print( + "if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(\(receiver), in: catchEnvironment) { return }" + ) + } + printer.print("let exception = catchEnvironment.makeJavaThrowable(for: error)") + if cancellable { + printer.print("SwiftJavaRuntimeSupport.SwiftAsyncResultSink.fail(\(receiver), exception, in: catchEnvironment)") + } else { + printer.print( + "_ = catchEnvironment.interface.CallBooleanMethodA(catchEnvironment, globalFuture, _JNIMethodIDCache.SimpleCompletableFuture.completeExceptionally, [jvalue(l: exception)])" + ) + } } } else { printDo(printer: &printer) @@ -2050,6 +2066,10 @@ extension JNISwift2JavaGenerator { } } + if cancellable { + printer.print("SwiftJavaRuntimeSupport.SwiftAsyncResultSink.bind(task!, to: \(resultParameter), in: environment)") + } + return "" case .closure(let args, let body): diff --git a/Sources/JExtractSwiftLib/JavaTypes/JavaType+SwiftKit.swift b/Sources/JExtractSwiftLib/JavaTypes/JavaType+SwiftKit.swift index 850768c25..61ef62910 100644 --- a/Sources/JExtractSwiftLib/JavaTypes/JavaType+SwiftKit.swift +++ b/Sources/JExtractSwiftLib/JavaTypes/JavaType+SwiftKit.swift @@ -21,4 +21,11 @@ extension JavaType { .class(package: "org.swift.swiftkit.core", name: "_OutSwiftGenericInstance") } + static func SwiftAsyncResultSink(_ S: JavaType, _ T: JavaType) -> JavaType { + .class( + package: "org.swift.swiftkit.core", + name: "SwiftAsyncResultSink", + typeParameters: [S.boxedType, T.boxedType] + ) + } } diff --git a/Sources/JExtractSwiftLib/TranslatedDocumentation.swift b/Sources/JExtractSwiftLib/TranslatedDocumentation.swift index 89286054b..e21e00687 100644 --- a/Sources/JExtractSwiftLib/TranslatedDocumentation.swift +++ b/Sources/JExtractSwiftLib/TranslatedDocumentation.swift @@ -49,7 +49,7 @@ enum TranslatedDocumentation { if translatedDecl.translatedFunctionSignature.requiresSwiftArena { documentation?.parameters.append( SwiftDocumentation.Parameter( - name: "swiftArena", + name: JNISwift2JavaGenerator.ArenaParameterName.caller, description: "the arena that the the returned object will be attached to" ) ) diff --git a/Sources/SwiftJavaRuntimeSupport/JNIMethodIDCaches.swift b/Sources/SwiftJavaRuntimeSupport/JNIMethodIDCaches.swift index c675ac7c2..7c23afb47 100644 --- a/Sources/SwiftJavaRuntimeSupport/JNIMethodIDCaches.swift +++ b/Sources/SwiftJavaRuntimeSupport/JNIMethodIDCaches.swift @@ -15,37 +15,6 @@ import SwiftJava extension _JNIMethodIDCache { - public enum CompletableFuture { - private static let completeMethod = Method( - name: "complete", - signature: "(Ljava/lang/Object;)Z" - ) - - private static let completeExceptionallyMethod = Method( - name: "completeExceptionally", - signature: "(Ljava/lang/Throwable;)Z" - ) - - private static let cache = _JNIMethodIDCache( - className: "java/util/concurrent/CompletableFuture", - methods: [completeMethod, completeExceptionallyMethod] - ) - - public static var `class`: jclass { - cache.javaClass - } - - /// CompletableFuture.complete(T) - public static var complete: jmethodID { - cache.methods[completeMethod]! - } - - /// CompletableFuture.completeExceptionally(Throwable) - public static var completeExceptionally: jmethodID { - cache.methods[completeExceptionallyMethod]! - } - } - public enum SimpleCompletableFuture { private static let completeMethod = Method( name: "complete", diff --git a/Sources/SwiftJavaRuntimeSupport/JavaSwiftAsyncResultSink.swift b/Sources/SwiftJavaRuntimeSupport/JavaSwiftAsyncResultSink.swift new file mode 100644 index 000000000..980ba7b42 --- /dev/null +++ b/Sources/SwiftJavaRuntimeSupport/JavaSwiftAsyncResultSink.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftJava + +private final class _JNISwiftTask: Sendable { + let task: Task + + init(_ task: Task) { self.task = task } +} + +@JavaClass("org.swift.swiftkit.core.SwiftAsyncResultSink") +public class SwiftAsyncResultSink: JavaObject { + private static let bindTask = _JNIMethodIDCache.Method( + name: "bindTask", + signature: "(J)V" + ) + + private static let isDone = _JNIMethodIDCache.Method( + name: "isDone", + signature: "()Z" + ) + + private static let complete = _JNIMethodIDCache.Method( + name: "complete", + signature: "(Ljava/lang/Object;)V" + ) + + private static let fail = _JNIMethodIDCache.Method( + name: "fail", + signature: "(Ljava/lang/Throwable;)V" + ) + + private static let cache = _JNIMethodIDCache( + className: "org/swift/swiftkit/core/SwiftAsyncResultSink", + methods: [bindTask, isDone, complete, fail] + ) + + public static func bind(_ task: Task, to resultSink: jobject?, in environment: JNIEnvironment) { + let handle = Unmanaged.passRetained(_JNISwiftTask(task)) + environment.interface.CallVoidMethodA( + environment, + resultSink, + cache[bindTask]!, + [jvalue(j: Int64(Int(bitPattern: handle.toOpaque())))] + ) + if environment.interface.ExceptionCheck(environment) != 0 { + handle.release() + } + } + + public static func isDone(_ `self`: jobject?, in environment: JNIEnvironment) -> Bool { + environment.interface.CallBooleanMethodA(environment, `self`, cache[isDone]!, nil) != 0 + } + + public static func complete(_ `self`: jobject?, _ boxedResult: jobject?, in environment: JNIEnvironment) { + environment.interface.CallVoidMethodA(environment, `self`, cache[complete]!, [jvalue(l: boxedResult)]) + } + + public static func fail(_ `self`: jobject?, _ error: jthrowable?, in environment: JNIEnvironment) { + environment.interface.CallVoidMethodA(environment, `self`, cache[fail]!, [jvalue(l: error)]) + } +} + +@JavaImplementation("org.swift.swiftkit.core.SwiftAsyncResultSink") +extension SwiftAsyncResultSink { + @JavaMethod + public static func finishTask( + environment: UnsafeMutablePointer!, + taskPointer: Int64 + ) { + let owner = Unmanaged<_JNISwiftTask>.fromOpaque(UnsafeRawPointer(bitPattern: Int(taskPointer))!).takeRetainedValue() + owner.task.cancel() + } +} diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/ConfinedSwiftMemorySession.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/ConfinedSwiftMemorySession.java index 7363539c2..f511c968b 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/ConfinedSwiftMemorySession.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/ConfinedSwiftMemorySession.java @@ -14,48 +14,35 @@ package org.swift.swiftkit.core; -import java.util.LinkedList; -import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; public class ConfinedSwiftMemorySession implements ClosableSwiftArena { + private final ConfinedResourceList resources = new ConfinedResourceList(); + private boolean closed; - final static int CLOSED = 0; - final static int ACTIVE = 1; - - final AtomicInteger state; - - final ConfinedResourceList resources; - - public ConfinedSwiftMemorySession() { - this.state = new AtomicInteger(ACTIVE); - this.resources = new ConfinedResourceList(); - } - - void checkValid() throws RuntimeException { - if (this.state.get() < ACTIVE) { + private void checkValid() { + if (closed) { throw new RuntimeException("SwiftArena is already closed!"); } } @Override public void close() { - checkValid(); - - // Cleanup all resources - if (this.state.compareAndSet(ACTIVE, CLOSED)) { - this.resources.runCleanup(); - } // else, was already closed; do nothing + synchronized (resources) { + checkValid(); + closed = true; + } + resources.runCleanup(); } @Override public void register(SwiftInstance instance) { - checkValid(); - SwiftInstanceCleanup cleanup = instance.$cleanup(); - this.resources.add(cleanup); + synchronized (resources) { + checkValid(); + resources.add(cleanup); + } } static final class ConfinedResourceList implements SwiftResourceList { diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftArena.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftArena.java index 96353c375..d22349dc4 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftArena.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftArena.java @@ -27,6 +27,7 @@ public interface SwiftArena { /** * Register a Swift object. * Its memory should be considered managed by this arena, and be destroyed when the arena is closed. + * If registration throws, the caller retains responsibility for cleanup. */ void register(SwiftInstance instance); diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftAsyncResultSink.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftAsyncResultSink.java new file mode 100644 index 000000000..2288aaff7 --- /dev/null +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftAsyncResultSink.java @@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +package org.swift.swiftkit.core; + +import java.util.ArrayDeque; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * Result callback for a generated JNI async binding. + */ +public final class SwiftAsyncResultSink { + private final CompletableFuture future = new CompletableFuture<>(); + private final BiConsumer> publish; + + private SwiftAsyncResultSink(BiConsumer> publish) { + this.publish = publish; + } + + public static SwiftAsyncResultSink create(Function convert) { + return new SwiftAsyncResultSink<>((boxedResult, future) -> { + if (!future.isDone()) { + future.complete(convert.apply(boxedResult)); + } + }); + } + + public static SwiftAsyncResultSink create( + SwiftArena arena, + BiFunction convert + ) { + return new SwiftAsyncResultSink<>((boxedResult, future) -> { + var pending = new ArrayDeque(); + try { + // Swift has handed the native values to Java, even if the future is already done. + T result = convert.apply(boxedResult, pending::addLast); + while (!pending.isEmpty()) { + if (future.isDone()) { + return; + } + // A successful registration transfers ownership, even if publication loses to cancellation. + arena.register(pending.getFirst()); + pending.removeFirst(); + } + future.complete(result); + } finally { + pending.forEach(wrapper -> wrapper.$cleanup().run()); + } + }); + } + + public CompletableFuture future() { + return future; + } + + @SuppressWarnings("unused") + private void bindTask(long taskPointer) { + // Once the future is complete, the Swift task no longer needs to produce a result. + future.whenComplete((value, error) -> finishTask(taskPointer)); + } + + private static native void finishTask(long taskPointer); + + @SuppressWarnings("unused") + private boolean isDone() { + return future.isDone(); + } + + void complete(S boxedResult) { + try { + publish.accept(boxedResult, future); + } catch (Throwable failure) { + fail(failure); + } + } + + private void fail(Throwable error) { + // Preserve the failure seen by callers of the former rawFuture.thenApply(convert) stage. + future.completeExceptionally(error instanceof CompletionException ? error : new CompletionException(error)); + } +} diff --git a/SwiftKitCore/src/test/java/org/swift/swiftkit/core/SwiftAsyncResultSinkTest.java b/SwiftKitCore/src/test/java/org/swift/swiftkit/core/SwiftAsyncResultSinkTest.java new file mode 100644 index 000000000..1bc6f2752 --- /dev/null +++ b/SwiftKitCore/src/test/java/org/swift/swiftkit/core/SwiftAsyncResultSinkTest.java @@ -0,0 +1,148 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +package org.swift.swiftkit.core; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SwiftAsyncResultSinkTest { + @Test + void cancellationDuringRegistrationLeavesOnlyRegisteredValueInArena() { + var firstDestroyed = new AtomicInteger(); + var secondDestroyed = new AtomicInteger(); + + try (var arena = SwiftArena.ofConfined()) { + var futureRef = new AtomicReference>(); + SwiftArena testingArena = value -> { + arena.register(value); + // Simulate another thread cancelling the future just after registration. + assertTrue(futureRef.get().cancel(false)); + }; + var callback = SwiftAsyncResultSink.create(testingArena, (addresses, resultArena) -> new OwnedValue[] { + new OwnedValue(addresses[0], resultArena, firstDestroyed::incrementAndGet), + new OwnedValue(addresses[1], resultArena, secondDestroyed::incrementAndGet) + }); + futureRef.set(callback.future()); + + callback.complete(new long[] {1, 2}); + assertTrue(callback.future().isCancelled()); + assertEquals(0, firstDestroyed.get()); + assertEquals(1, secondDestroyed.get()); + } + assertEquals(1, firstDestroyed.get()); + assertEquals(1, secondDestroyed.get()); + } + + @Test + void arenaClosedDuringRegistrationLeavesCleanupToCallback() throws Exception { + var arena = SwiftArena.ofConfined(); + var registering = new CompletableFuture(); + var closed = new CompletableFuture(); + var destruction = new AtomicInteger(); + var callback = SwiftAsyncResultSink.create(arena, (address, resultArena) -> + new OwnedValue(address, resultArena, destruction::incrementAndGet) { + @Override + public SwiftInstanceCleanup $cleanup() { + // Signal that arena registration has started. + registering.complete(null); + // Wait for the test thread to close the arena. + closed.orTimeout(5, TimeUnit.SECONDS).join(); + // Registration will fail when it resumes because the arena is closed. + return super.$cleanup(); + } + }); + var worker = CompletableFuture.runAsync(() -> callback.complete(1L)); + try { + registering.get(5, TimeUnit.SECONDS); + arena.close(); + } finally { + closed.complete(null); + } + worker.get(5, TimeUnit.SECONDS); + assertTrue(callback.future().isCompletedExceptionally()); + assertEquals(1, destruction.get()); + } + + @Test + void conversionFailureDestroysAlreadyWrappedValueExactlyOnce() { + var registered = new AtomicInteger(); + try (var arena = SwiftArena.ofConfined()) { + var callback = SwiftAsyncResultSink.create(arena, (addresses, resultArena) -> { + new OwnedValue(addresses[0], resultArena, registered::incrementAndGet); + throw new IllegalStateException("wrapping result failed"); + }); + callback.complete(new long[] {1, 2, 3}); + assertEquals(1, registered.get()); + } + assertEquals(1, registered.get()); + } + + @Test + void cancellationBeforeCallbackStillDestroysEveryOwnedValue() { + var destruction = new AtomicInteger(); + var registrations = new AtomicInteger(); + SwiftArena arena = (v) -> registrations.incrementAndGet(); + var callback = SwiftAsyncResultSink.create(arena, (addresses, resultArena) -> new OwnedValue[]{ + new OwnedValue(addresses[0], resultArena, destruction::incrementAndGet), + new OwnedValue(addresses[1], resultArena, destruction::incrementAndGet) + }); + + assertTrue(callback.future().cancel(false)); + callback.complete(new long[] {1, 2}); + + assertEquals(2, destruction.get()); + assertEquals(0, registrations.get()); + } + + private static class OwnedValue implements JNISwiftInstance { + private final long address; + private final Runnable destroy; + private final SwiftInstanceCleanup cleanup; + + OwnedValue(long address, SwiftArena arena, Runnable destroy) { + this.address = address; + this.destroy = destroy; + this.cleanup = $createCleanup(); + arena.register(this); + } + + @Override + public long $memoryAddress() { + return address; + } + + @Override + public long $typeMetadataAddress() { + return 12345; + } + + @Override + public SwiftInstanceCleanup $cleanup() { + return cleanup; + } + + @Override + public Runnable $createDestroyFunction() { + return destroy; + } + } +} diff --git a/Tests/JExtractSwiftTests/JNI/JNIActorTests.swift b/Tests/JExtractSwiftTests/JNI/JNIActorTests.swift index 74cda25e8..a1e01bd6e 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIActorTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIActorTests.swift @@ -43,16 +43,16 @@ struct JNIActor1MethodsTests { expectedChunks: [ """ public java.util.concurrent.CompletableFuture hello() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - K.$hello(this.$memoryAddress(), future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + K.$hello(this.$memoryAddress(), resultSink$); + return resultSink$.future(); } """, """ - private static native void $hello(long selfPointer, java.util.concurrent.CompletableFuture result_future); + private static native void $hello(long selfPointer, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ], notExpectedChunks: [ @@ -71,7 +71,7 @@ struct JNIActor1MethodsTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_K__00024hello__JLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_K__00024hello__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... task = Task.immediate { ... @@ -91,16 +91,16 @@ struct JNIActor1MethodsTests { expectedChunks: [ """ public java.util.concurrent.CompletableFuture hi() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - K.$hi(this.$memoryAddress(), future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + K.$hi(this.$memoryAddress(), resultSink$); + return resultSink$.future(); } """, """ - private static native void $hi(long selfPointer, java.util.concurrent.CompletableFuture result_future); + private static native void $hi(long selfPointer, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ], notExpectedChunks: [ @@ -119,7 +119,7 @@ struct JNIActor1MethodsTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_K__00024hi__JLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_K__00024hi__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... task = Task.immediate { ... @@ -235,16 +235,16 @@ struct JNIActor1MethodsTests { expectedChunks: [ """ public java.util.concurrent.CompletableFuture concurrentlyAsync() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - K.$concurrentlyAsync(this.$memoryAddress(), future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + K.$concurrentlyAsync(this.$memoryAddress(), resultSink$); + return resultSink$.future(); } """, """ - private static native void $concurrentlyAsync(long selfPointer, java.util.concurrent.CompletableFuture result_future); + private static native void $concurrentlyAsync(long selfPointer, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ], notExpectedChunks: [ @@ -263,7 +263,7 @@ struct JNIActor1MethodsTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_K__00024concurrentlyAsync__JLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_K__00024concurrentlyAsync__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... task = Task.immediate { ... diff --git a/Tests/JExtractSwiftTests/JNI/JNIAsyncTests.swift b/Tests/JExtractSwiftTests/JNI/JNIAsyncTests.swift index 866c542d4..cb89689ce 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIAsyncTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIAsyncTests.swift @@ -35,16 +35,16 @@ struct JNIAsyncTests { * } */ public static java.util.concurrent.CompletableFuture asyncVoid() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - SwiftModule.$asyncVoid(future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + SwiftModule.$asyncVoid(resultSink$); + return resultSink$.future(); } """, """ - private static native void $asyncVoid(java.util.concurrent.CompletableFuture result_future); + private static native void $asyncVoid(org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] ) @@ -59,9 +59,9 @@ struct JNIAsyncTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_SwiftModule__00024asyncVoid__Ljava_util_concurrent_CompletableFuture_2") - public func Java_com_example_swift_SwiftModule__00024asyncVoid__Ljava_util_concurrent_CompletableFuture_2(environment: UnsafeMutablePointer!, thisClass: jclass, result_future: jobject?) { - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + @_cdecl("Java_com_example_swift_SwiftModule__00024asyncVoid__Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2") + public func Java_com_example_swift_SwiftModule__00024asyncVoid__Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2(environment: UnsafeMutablePointer!, thisClass: jclass, result_sink: jobject?) { + nonisolated(unsafe) let globalResultSink = environment.interface.NewGlobalRef(environment, result_sink) var task: Task? = nil #if swift(>=6.2) if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) { @@ -69,11 +69,12 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } await SwiftModule.asyncVoid() environment = try! JavaVirtualMachine.shared().environment() - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: nil)]) + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, nil, in: environment) } } #endif @@ -82,13 +83,15 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } await SwiftModule.asyncVoid() environment = try! JavaVirtualMachine.shared().environment() - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: nil)]) + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, nil, in: environment) } } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.bind(task!, to: result_sink, in: environment) } """ ] @@ -111,16 +114,16 @@ struct JNIAsyncTests { * } */ public static java.util.concurrent.CompletableFuture async() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - SwiftModule.$async(future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + SwiftModule.$async(resultSink$); + return resultSink$.future(); } """, """ - private static native void $async(java.util.concurrent.CompletableFuture result_future); + private static native void $async(org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] ) @@ -135,9 +138,9 @@ struct JNIAsyncTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_SwiftModule__00024async__Ljava_util_concurrent_CompletableFuture_2") - public func Java_com_example_swift_SwiftModule__00024async__Ljava_util_concurrent_CompletableFuture_2(environment: UnsafeMutablePointer!, thisClass: jclass, result_future: jobject?) { - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + @_cdecl("Java_com_example_swift_SwiftModule__00024async__Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2") + public func Java_com_example_swift_SwiftModule__00024async__Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2(environment: UnsafeMutablePointer!, thisClass: jclass, result_sink: jobject?) { + nonisolated(unsafe) let globalResultSink = environment.interface.NewGlobalRef(environment, result_sink) var task: Task? = nil #if swift(>=6.2) if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) { @@ -145,17 +148,19 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } do { try await SwiftModule.async() environment = try! JavaVirtualMachine.shared().environment() - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: nil)]) + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, nil, in: environment) } catch { let catchEnvironment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: catchEnvironment) { return } let exception = catchEnvironment.makeJavaThrowable(for: error) - _ = catchEnvironment.interface.CallBooleanMethodA(catchEnvironment, globalFuture, _JNIMethodIDCache.CompletableFuture.completeExceptionally, [jvalue(l: exception)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.fail(globalResultSink, exception, in: catchEnvironment) } } } @@ -165,20 +170,23 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } do { try await SwiftModule.async() environment = try! JavaVirtualMachine.shared().environment() - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: nil)]) + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, nil, in: environment) } catch { let catchEnvironment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: catchEnvironment) { return } let exception = catchEnvironment.makeJavaThrowable(for: error) - _ = catchEnvironment.interface.CallBooleanMethodA(catchEnvironment, globalFuture, _JNIMethodIDCache.CompletableFuture.completeExceptionally, [jvalue(l: exception)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.fail(globalResultSink, exception, in: catchEnvironment) } } } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.bind(task!, to: result_sink, in: environment) } """ ] @@ -201,16 +209,16 @@ struct JNIAsyncTests { * } */ public static java.util.concurrent.CompletableFuture async(long i) { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - SwiftModule.$async(i, future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + SwiftModule.$async(i, resultSink$); + return resultSink$.future(); } """, """ - private static native void $async(long i, java.util.concurrent.CompletableFuture result_future); + private static native void $async(long i, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] ) @@ -225,9 +233,9 @@ struct JNIAsyncTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_SwiftModule__00024async__JLjava_util_concurrent_CompletableFuture_2") - public func Java_com_example_swift_SwiftModule__00024async__JLjava_util_concurrent_CompletableFuture_2(environment: UnsafeMutablePointer!, thisClass: jclass, i: jlong, result_future: jobject?) { - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + @_cdecl("Java_com_example_swift_SwiftModule__00024async__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") + public func Java_com_example_swift_SwiftModule__00024async__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2(environment: UnsafeMutablePointer!, thisClass: jclass, i: jlong, result_sink: jobject?) { + nonisolated(unsafe) let globalResultSink = environment.interface.NewGlobalRef(environment, result_sink) var task: Task? = nil #if swift(>=6.2) if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) { @@ -235,12 +243,13 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } let swiftResult$ = await SwiftModule.async(i: Int64(fromJNI: i, in: environment)) environment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } let boxedResult$ = SwiftJavaRuntimeSupport._JNIBoxedConversions.box(swiftResult$.getJNILocalRefValue(in: environment), in: environment) - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: boxedResult$)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, boxedResult$, in: environment) } } #endif // end of swift(>=6.2) @@ -249,14 +258,16 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } let swiftResult$ = await SwiftModule.async(i: Int64(fromJNI: i, in: environment)) environment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } let boxedResult$ = SwiftJavaRuntimeSupport._JNIBoxedConversions.box(swiftResult$.getJNILocalRefValue(in: environment), in: environment) - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: boxedResult$)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, boxedResult$, in: environment) } } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.bind(task!, to: result_sink, in: environment) return } """ @@ -284,16 +295,16 @@ struct JNIAsyncTests { * } */ public static java.util.concurrent.CompletableFuture async(MyClass c, SwiftArena swiftArena) { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - SwiftModule.$async(c.$memoryAddress(), future$); - return future$.thenApply((futureResult$) -> { - return MyClass.wrapMemoryAddressUnsafe(futureResult$, swiftArena); + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create(swiftArena, (futureResult$, resultArena$) -> { + return MyClass.wrapMemoryAddressUnsafe(futureResult$, resultArena$); } ); + SwiftModule.$async(c.$memoryAddress(), resultSink$); + return resultSink$.future(); } """, """ - private static native void $async(long c, java.util.concurrent.CompletableFuture result_future); + private static native void $async(long c, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] ) @@ -312,15 +323,15 @@ struct JNIAsyncTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_SwiftModule__00024async__JLjava_util_concurrent_CompletableFuture_2") - public func Java_com_example_swift_SwiftModule__00024async__JLjava_util_concurrent_CompletableFuture_2(environment: UnsafeMutablePointer!, thisClass: jclass, c: jlong, result_future: jobject?) { + @_cdecl("Java_com_example_swift_SwiftModule__00024async__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") + public func Java_com_example_swift_SwiftModule__00024async__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2(environment: UnsafeMutablePointer!, thisClass: jclass, c: jlong, result_sink: jobject?) { assert(c != 0, "c memory address was null") let cBits$ = Int(Int64(fromJNI: c, in: environment)) let c$ = UnsafeMutablePointer(bitPattern: cBits$) guard let c$ else { fatalError("c memory address was null in call to \\(#function)!") } - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + nonisolated(unsafe) let globalResultSink = environment.interface.NewGlobalRef(environment, result_sink) var task: Task? = nil #if swift(>=6.2) if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) { @@ -328,15 +339,16 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } let swiftResult$ = await SwiftModule.async(c: c$.pointee) environment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } let result$ = UnsafeMutablePointer.allocate(capacity: 1) result$.initialize(to: swiftResult$) let resultBits$ = Int64(Int(bitPattern: result$)) let boxedResult$ = SwiftJavaRuntimeSupport._JNIBoxedConversions.box(resultBits$.getJNILocalRefValue(in: environment), in: environment) - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: boxedResult$)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, boxedResult$, in: environment) } } #endif @@ -345,17 +357,19 @@ struct JNIAsyncTests { var environment = try! JavaVirtualMachine.shared().environment() defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) } let swiftResult$ = await SwiftModule.async(c: c$.pointee) environment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } let result$ = UnsafeMutablePointer.allocate(capacity: 1) result$.initialize(to: swiftResult$) let resultBits$ = Int64(Int(bitPattern: result$)) let boxedResult$ = SwiftJavaRuntimeSupport._JNIBoxedConversions.box(resultBits$.getJNILocalRefValue(in: environment), in: environment) - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: boxedResult$)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, boxedResult$, in: environment) } } + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.bind(task!, to: result_sink, in: environment) return } """ @@ -375,16 +389,16 @@ struct JNIAsyncTests { expectedChunks: [ """ public static java.util.concurrent.CompletableFuture async(java.lang.String s) { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - SwiftModule.$async(s, future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + SwiftModule.$async(s, resultSink$); + return resultSink$.future(); } """, """ - private static native void $async(java.lang.String s, java.util.concurrent.CompletableFuture result_future); + private static native void $async(java.lang.String s, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] ) @@ -401,18 +415,18 @@ struct JNIAsyncTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_SwiftModule__00024async__Ljava_lang_String_2Ljava_util_concurrent_CompletableFuture_2") - public func Java_com_example_swift_SwiftModule__00024async__Ljava_lang_String_2Ljava_util_concurrent_CompletableFuture_2(environment: UnsafeMutablePointer!, thisClass: jclass, s: jstring?, result_future: jobject?) { + @_cdecl("Java_com_example_swift_SwiftModule__00024async__Ljava_lang_String_2Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2") + public func Java_com_example_swift_SwiftModule__00024async__Ljava_lang_String_2Lorg_swift_swiftkit_core_SwiftAsyncResultSink_2(environment: UnsafeMutablePointer!, thisClass: jclass, s: jstring?, result_sink: jobject?) { nonisolated(unsafe) let s = environment.interface.NewGlobalRef(environment, s) - nonisolated(unsafe) let globalFuture = environment.interface.NewGlobalRef(environment, result_future) + nonisolated(unsafe) let globalResultSink = environment.interface.NewGlobalRef(environment, result_sink) ... defer { let deferEnvironment = try! JavaVirtualMachine.shared().environment() - deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalFuture) + deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, globalResultSink) deferEnvironment.interface.DeleteGlobalRef(deferEnvironment, s) } ... - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: swiftResult$.getJNILocalRefValue(in: environment))]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, swiftResult$.getJNILocalRefValue(in: environment), in: environment) ... } """ @@ -520,8 +534,9 @@ struct JNIAsyncTests { """ let swiftResult$ = await SwiftModule.\(functionName)() environment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: environment) { return } ... - _ = environment.interface.CallBooleanMethodA(environment, globalFuture, _JNIMethodIDCache.CompletableFuture.complete, [jvalue(l: nil)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.complete(globalResultSink, nil, in: environment) """ ], notExpectedChunks: [ diff --git a/Tests/JExtractSwiftTests/JNI/JNIClassAsyncSelfCaptureTests.swift b/Tests/JExtractSwiftTests/JNI/JNIClassAsyncSelfCaptureTests.swift index af9575f52..d4ac02bf8 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIClassAsyncSelfCaptureTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIClassAsyncSelfCaptureTests.swift @@ -32,7 +32,7 @@ struct JNIAsyncSelfCaptureTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_MyClass__00024compute__JLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_MyClass__00024compute__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... nonisolated(unsafe) let selfPointerUnsafeSendable$ = selfPointer$ ... @@ -59,7 +59,7 @@ struct JNIAsyncSelfCaptureTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_WorkerBox__00024work__JJLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_WorkerBox__00024work__JJLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... nonisolated(unsafe) let selfPointerExistentialUnsafeSendable$ = selfPointerExistential$ ... diff --git a/Tests/JExtractSwiftTests/JNI/JNIDistributedActorTests.swift b/Tests/JExtractSwiftTests/JNI/JNIDistributedActorTests.swift index 6b16459de..0fe11c0d8 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIDistributedActorTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIDistributedActorTests.swift @@ -34,16 +34,16 @@ struct JNIDistributedActorTests { expectedChunks: [ """ public java.util.concurrent.CompletableFuture hi() { - java.util.concurrent.CompletableFuture future$ = new java.util.concurrent.CompletableFuture(); - D.$hi(this.$memoryAddress(), future$); - return future$.thenApply((futureResult$) -> { + org.swift.swiftkit.core.SwiftAsyncResultSink resultSink$ = org.swift.swiftkit.core.SwiftAsyncResultSink.create((futureResult$) -> { return futureResult$; } ); + D.$hi(this.$memoryAddress(), resultSink$); + return resultSink$.future(); } """, """ - private static native void $hi(long selfPointer, java.util.concurrent.CompletableFuture result_future); + private static native void $hi(long selfPointer, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ], notExpectedChunks: [ @@ -62,7 +62,7 @@ struct JNIDistributedActorTests { detectChunkByInitialLines: 1, expectedChunks: [ """ - @_cdecl("Java_com_example_swift_D__00024hi__JLjava_util_concurrent_CompletableFuture_2") + @_cdecl("Java_com_example_swift_D__00024hi__JLorg_swift_swiftkit_core_SwiftAsyncResultSink_2") ... task = Task.immediate { ... @@ -73,8 +73,9 @@ struct JNIDistributedActorTests { """ catch { let catchEnvironment = try! JavaVirtualMachine.shared().environment() + if SwiftJavaRuntimeSupport.SwiftAsyncResultSink.isDone(globalResultSink, in: catchEnvironment) { return } let exception = catchEnvironment.makeJavaThrowable(for: error) - _ = catchEnvironment.interface.CallBooleanMethodA(catchEnvironment, globalFuture, _JNIMethodIDCache.CompletableFuture.completeExceptionally, [jvalue(l: exception)]) + SwiftJavaRuntimeSupport.SwiftAsyncResultSink.fail(globalResultSink, exception, in: catchEnvironment) } """, ] diff --git a/Tests/JExtractSwiftTests/JNI/JNIIsolatedParameterTests.swift b/Tests/JExtractSwiftTests/JNI/JNIIsolatedParameterTests.swift index 714d23462..107403434 100644 --- a/Tests/JExtractSwiftTests/JNI/JNIIsolatedParameterTests.swift +++ b/Tests/JExtractSwiftTests/JNI/JNIIsolatedParameterTests.swift @@ -41,7 +41,7 @@ struct JNIIsolatedParameterTests { public java.util.concurrent.CompletableFuture run(MyActor actor) { """, """ - private static native void $run(long actor, long selfPointer, java.util.concurrent.CompletableFuture result_future); + private static native void $run(long actor, long selfPointer, org.swift.swiftkit.core.SwiftAsyncResultSink result_sink); """, ] )