Repository navigation
[generator] Bind Kotlin suspend functions as Task-returning methods - #13583
Open
jonathanpeppers wants to merge 7 commits into
Open
jonathanpeppers wants to merge 7 commits into
jonathanpeppers wants to merge 7 commits into
Conversation
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
JNI peer-lifetime and generated-name collision bugs can cause runtime failures and uncompilable bindings, while the cancellation test does not verify that the Kotlin coroutine actually exits.
3 open issues
What changed in this PR
Adds Task-based bindings for Kotlin suspend functions, connecting Kotlin metadata parsing, C# binding generation, and the .NET for Android runtime.
Changes:
- Preserves suspend-result metadata and generates
*Asyncwrappers with optional cancellation tokens. - Adds a runtime continuation bridge for results, exceptions, and cancellation, plus R8 retention rules.
- Adds bytecode, generator, binding-build, and device integration tests.
| File | Description |
|---|---|
| tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj | Embeds the suspend fixture. |
| tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs | Tests suspend-result metadata extraction. |
| tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt | Adds Kotlin suspend test cases. |
| tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets | Tracks the compiled fixture output. |
| tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs | Exercises results, failures, and cancellation on-device with R8. |
| tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs | Checks generated Task wrappers. |
| tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs | Shares the fixture-loading helper. |
| tests/generator-Tests/generator-Tests.csproj | Embeds the suspend fixture for generator tests. |
| src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs | Supports default parameter values. |
| src/Xamarin.Android.Tools.Bytecode/XmlClassDeclarationBuilder.cs | Exports suspend-result metadata to XML. |
| src/Xamarin.Android.Tools.Bytecode/Methods.cs | Stores suspend-result metadata. |
| src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs | Recognizes suspend functions and their result types. |
| src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs | Checks Task wrappers for DataStore bindings. |
| src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg | Retains reflectively accessed Kotlin members. |
| src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg | Adds Kotlin retention rules for typemap builds. |
| src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg | Adds Kotlin retention rules for CoreCLR builds. |
| src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt | Records the new runtime API. |
| src/Mono.Android/Mono.Android.csproj | Includes the coroutine bridge. |
| src/Mono.Android/Android.Runtime/KotlinCoroutines.cs | Bridges Kotlin continuations to managed Tasks. |
| src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs | Preserves suspend metadata through type processing. |
| src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs | Generates Task-returning suspend wrappers. |
| src/generator/SourceWriters/InterfaceExtensionsClass.cs | Adds suspend wrappers as interface extensions. |
| src/generator/SourceWriters/BoundInterface.cs | Integrates static wrappers and extension generation. |
| src/generator/SourceWriters/BoundClass.cs | Integrates class and nested-interface wrappers. |
| src/generator/Java.Interop.Tools.Generator.ObjectModel/Method.cs | Stores and clones suspend-result metadata. |
| src/generator/Java.Interop.Tools.Generator.Importers/XmlApiImporter.cs | Imports suspend-result metadata for generation. |
Review effort: Balanced
jonathanpeppers
force-pushed
the
jonathanpeppers-kotlin-suspend-as-task
branch
from
November 16, 2026 22:43
e0feeef to
7b2b727
Compare
9 tasks
…thods class-parse records the Kotlin result type of suspend functions in api.xml (kotlin-suspend-return-type); the JavaTypeSystem adjuster passes it through. The generator emits an additive *Async(…, CancellationToken) method that calls the existing Continuation-based method through the new Android.Runtime.KotlinCoroutines helper. KotlinCoroutines creates the Continuation with java.lang.reflect.Proxy, so Mono.Android has no build-time Kotlin dependency. When kotlinx.coroutines is present, a Job is the coroutine context and the CancellationToken cancels it. Co-authored-by: Copilot App <[email protected]>
…; add device test * Java.Lang.Throwable is not a Java.Lang.Object: cancel the Job with a null cause, and convert the Result.Failure exception by peer reference. * Add R8 keep rules for the Kotlin members that KotlinCoroutines finds by name, in all three default ProGuard configurations. * Add an MSBuildDeviceIntegration test that binds a Gradle module with Kotlin suspend functions and awaits the generated *Async methods. Co-authored-by: Copilot App <[email protected]>
* Always cancel the Task when the token is canceled; with kotlinx, also cancel the Job. Not all suspend functions observe the Job. * Unregister (not Dispose) the token registration, so completion never waits for a running cancellation callback. * Treat a missing kotlinx Job member like a missing kotlinx. * Result types: skip inline classes (boxed here) and invalid or non-public types. * Skip methods with an explicit interface; don't emit empty interface extension classes for static-only suspend methods. * Add MethodParameterWriter.DefaultValue instead of a custom writer. * Tests: drop a duplicate XML test; run the device test once, in Release with R8, which covers the keep rules. Co-authored-by: Copilot App <[email protected]>
…sk methods datastore-preferences-core-jvm has real Kotlin suspend APIs. The test binds it with <AndroidMavenLibrary> and checks that PreferencesKt.edit gets a Task-returning EditAsync method. Version 1.2.1 matches the published NuGet packages for its dependencies. Co-authored-by: Copilot App <[email protected]>
…findings
KotlinCoroutines.InvokeAsync<T> hid a nullability mismatch with
#pragma warning disable CS8603: JavaConvert.FromJavaObject<T> returns
T?, and C# cannot tell string from string? at run time. Split the API:
* InvokeAsync<T> where T : notnull returns Task<T>, and throws when
Kotlin breaks its non-null contract.
* InvokeNullableAsync<T> returns Task<T?>.
The generator calls InvokeNullableAsync when the Kotlin result type is
nullable, so NRT bindings now get Task<string?> for String?.
Review fixes:
* Kotlin platform types (T!) are nullable results.
* Generic types fall back to Java.Lang.Object.
* Add the [RestrictTo] warning to *Async wrappers.
* Only add interface extension classes when a wrapper is generated.
* Keep the Result.Failure exception alive while converting it.
* Always cancel the Task, even when Job.cancel throws.
* Treat any kotlinx lookup failure as kotlinx not present.
Tests: run the generator test through the shared adjuster helper, and
cover a nullable primitive result.
Co-authored-by: Copilot App <[email protected]>
Only generated bindings call Android.Runtime.KotlinCoroutines, so:
* Mark it [EditorBrowsable (EditorBrowsableState.Never)], like
ResourceIdManager and GeneratedEnumAttribute.
* Rename InvokeAsync<T>/InvokeNullableAsync<T> to
CallSuspendFunctionAsync<T>/CallNullableSuspendFunctionAsync<T>,
after the JNIEnv.Call*Method pattern.
* Remove the non-generic InvokeAsync. A Unit result uses
CallNullableSuspendFunctionAsync<Java.Lang.Object>, because
Task<T> is a Task.
Co-authored-by: Copilot App <[email protected]>
jonathanpeppers
force-pushed
the
jonathanpeppers-kotlin-suspend-as-task
branch
from
November 23, 2026 17:21
7b2b727 to
da9ba1f
Compare
…tlin-side cancellation * The generated self, cancellationToken and __continuation names now get a '_' prefix when a Kotlin parameter already uses the name. * The device test cancels after the coroutine suspends, and checks that the Kotlin code stops (a finally block sets a flag). Before, the test passed even if the Kotlin Job was not canceled, because the token always cancels the Task. Co-authored-by: Copilot App <[email protected]>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Context: #13582
Note
This PR is stacked on #13582. Review only the commits in this layer.
Many Android libraries, such as DataStore, Room, and Paging, expose Kotlin
suspendfunctions. On the JVM, asuspendfunction takes an extrakotlin.coroutines.Continuationparameter and returnsObject. The binding generator emitted that JVM shape as-is, so C# code could only call it with a hand-writtenContinuationimplementation.Bindings now also get an
*Asyncmethod that returns aTask. The existing method does not change.Kotlin and C# side by side
*Asyncmethods)The result type comes from the Kotlin metadata, not from the erased
Object:UnitTaskInt,Boolean,Long, …Task<int>,Task<bool>,Task<long>, …Int?Task<int?>String/String?Task<string>/Task<string?>PreferencesTask<Preferences>Task<Java.Lang.Object>String!)Task<string?>A real example from
androidx.datastore:datastore-preferences-core-jvm:Generated binding
The generator keeps the existing
Continuation-based method and adds a wrapper next to it. This is the output forWeatherClientabove (JNI method bodies omitted):Interface instance methods get the wrapper as an extension method in the existing
*Extensionsclass. Static interface methods get it on the interface. The generator skips overrides, explicit interface implementations, methods that already usegenerateAsyncWrapper, and names that already exist.Runtime:
Android.Runtime.KotlinCoroutinesNew public API in
Mono.Android. Only generated code calls it, so it is hidden from IntelliSense, likeResourceIdManager:kotlin.coroutines.Continuationis ajava.lang.reflect.Proxywith a managedInvocationHandler.Mono.Androidhas no build-time dependency on Kotlin, and no new package or Java source is needed. The Kotlin classes are found at run time with the app class loader.COROUTINE_SUSPENDED, theTaskcompletes later, when Kotlin callsresumeWith. Other return values complete it immediately. Akotlin.Result$Failurebecomes the matching managed exception, for exampleJava.Lang.IllegalStateException.CallNullableSuspendFunctionAsyncwhen the Kotlin result is nullable.CallSuspendFunctionAsyncthrows if Kotlin returnsnullfor a non-null result. AUnitresult usesCallNullableSuspendFunctionAsync<Java.Lang.Object>, because aTask<T>is also aTask.Task. When the app includeskotlinx.coroutines, the continuation context is a newkotlinx.coroutines.Job, and the token also callsJob.cancel, so cancellable Kotlin code (delay,withContext, …) stops. Withoutkotlinx.coroutines, the context isEmptyCoroutineContext, and the Kotlin work continues.ClassNotFoundException: kotlin.coroutines.EmptyCoroutineContext.An alternative was a separate NuGet package with a Kotlin bridge built on
kotlinx.coroutines. That adds a build-time Kotlin dependency and a new package, and it requireskotlinx.coroutinesin every app.Validation
Standalone tests (
bin\Debug\dotnet\dotnet test):tests\Xamarin.Android.Tools.Bytecode-Tests: Passed 139, Skipped 2. Includes the newKotlinSuspendTests, which reads a Gradle-compiledSuspendFunctions.ktfixture.tests\Java.Interop.Tools.JavaTypeSystem-Tests: Passed 17.tests\generator-Tests: Passed 496. Includes the newKotlinSuspendTests, which runs the fixture through class-parse, the api.xml adjuster, and the generator.Full SDK build (
dotnet-local.cmd build Microsoft.Android.slnx, then-t:BuildExtraApiLevels, then-t:PackDotNet), then:Passed 1/1. The test binds
androidx.datastore:datastore-preferences-core-jvm1.2.1 with<AndroidMavenLibrary/>and checks the generatedPreferencesKt.EditAsync. Version 1.3.0 requiresdatastore-core-jvm1.3.0 exactly, and the newest NuGet packages are 1.2.1.1.On-device, x86_64 API 36 emulator, CoreCLR:
suspendfunctions, bound into an app. This is the same code as the newMSBuildDeviceIntegrationtestKotlinSuspendTests.SuspendFunctionsAsTasks. Release with$(AndroidLinkTool)=r8logssum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True. That covers an asynchronous resume, a synchronous result, anullresult, a Kotlin exception, and cancellation throughkotlinx.coroutines.delay. I ran this with the final code. A Debug build gave the same result on an earlier revision.PreferencesKt.EditAsynccalls and one canceled edit logcount=2 thread=DefaultDispatcher-worker-1 canceled=True. The transform runs on akotlinx.coroutinesDispatchers.IOworker thread, the second edit reads the stored value, and cancellation works.I did not run the
MSBuildDeviceIntegrationtest through NUnit locally: on Windows, its teardown runsadb kill-server, which disconnects other users of a shared host. I built and ran the same project by hand. The test useskotlinx-coroutines-core:1.10.2from Maven (compile only). If the CI Maven mirror does not have it yet, seed it witheng/gradle/mirror-dependencies.ps1 -MavenArtifact.