Repository navigation
[generator] Bind Kotlin suspend functions as Task-returning methods - #13583
jonathanpeppers wants to merge 14 commits into
Conversation
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
e0feeef to
7b2b727
Compare
7b2b727 to
da9ba1f
Compare
b587d21 to
a08bb04
Compare
…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 <223556219+Copilot@users.noreply.github.com>
…; 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 <223556219+Copilot@users.noreply.github.com>
* 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 <223556219+Copilot@users.noreply.github.com>
…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 <223556219+Copilot@users.noreply.github.com>
…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 <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
…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 <223556219+Copilot@users.noreply.github.com>
…in *Async wrappers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
a08bb04 to
b71bb50
Compare
…pper Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/azp run Xamarin.Android-PR |
|
No pipelines are associated with this pull request. |
Remove `Android.Runtime.KotlinCoroutines` from Mono.Android. The generator now writes an internal `__KotlinCoroutines` type into each binding assembly that has Kotlin `suspend` wrappers. The helper implements the bound `Kotlin.Coroutines.IContinuation` directly, and uses the bound `EmptyCoroutineContext`, `IntrinsicsKt.COROUTINE_SUSPENDED` and, when the binding references kotlinx.coroutines, `JobKt.Job` and `IJob.Cancel`. R8 keeps these types because managed code uses them, so the Kotlin keep rules are removed. Each wrapper converts the result itself, because `JavaConvert` is internal to Mono.Android. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Write the helper from one template, and cancel the Task before the Job so no try/finally is needed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/azp run Xamarin.Android-PR |
|
No pipelines are associated with this pull request. |
The CI NuGet feed does not have the DataStore JVM and Okio packages, so restore failed with NU1101. kotlinx-coroutines-android has a real suspend API, and its dependencies are in the feed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes
1 error · 0 warnings · 0 suggestions on 65636c8079b0632689ab95fc74a0e061b04c2dfa.
The inline finding identifies an unrooted JNI peer in the generated coroutine-marker comparison, which can cause a runtime abort on CoreCLR/NativeAOT.
The metadata-driven suspend detection preserves the existing continuation-based API, and the fixture covers nullable results and generated-name collisions.
CI: license/cla passed, but the current head has no dotnet-android Azure DevOps checks or commit statuses available; pipeline validation is unverified. Reviewed all 23 changed files in full. Static review only; builds and device tests were not run.
Generated by Android PR Reviewer for #13583 · copilot · gpt61 · ~65 AIC · ⌖ ~11 AIC · ⊞ 22.3K
Comment /review to run again
Store COROUTINE_SUSPENDED in a static field, and keep the result alive until IsSameObject returns, so the GC cannot delete their global references during the call. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…n-suspend-as-task
|
@dalexsoto review |
|
In response to @jonathanpeppers's request: The source changes and the follow-up fixes look consistent in the paths I reviewed. I still need the complete KotlinSuspendTests and KotlinInlineClassEndToEndTests changes, the kotlin-suspend-return-type export round-trip, the generated Continuation Java-wrapper path, and the referenced Kotlin/kotlinx member and R8-keep contracts (including GenBase.ContainsName and ParameterList.GetCall). These are reviewer coverage gaps, not defects found in the PR. No API error occurred; those integration reads were not completed within this bounded review interval. |

Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
bf62112faf1fbe4325db588753a6e783851bbff1↑ The build test that binds kotlinx-coroutines-android passes locally, so the helper compiles against the real Kotlin and kotlinx bindings.
↑ Internal CI on the previous head: the only failure from this PR was this test (NU1101, DataStore packages not in the feed), now replaced; the other failures were DNS errors, a missing android-37.0 platform, an MSBuild version check, and PoliCheck findings in unchanged files.
↑ On a Pixel 7, Release with R8: resume, null, exception, and cancellation all work, with no Kotlin keep rules.
↑ The review finding about JNI peer lifetimes in the COROUTINE_SUSPENDED check is fixed and was checked on the device.
↓ Debug was checked on an earlier commit; later commits only changed the helper template and peer lifetimes.
↓ The DataStore on-device run used the earlier Mono.Android design.
↓ The helper's member names (
Instance,COROUTINE_SUSPENDED,Job,Cancel) come from current Kotlin binding packages; other package versions were not checked.↑ Latest main merged; it changed no generator or Kotlin code, and generator tests still pass.
↓ CI on this head not yet inspected.
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. Fortemperatureabove (JNI body omitted):The second lambda converts the Kotlin result to the C# type.
Unitresults call the non-genericInvokeAsyncand return aTask.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: generated
__KotlinCoroutinesThere is no new API in
Mono.Android. When a binding has at least one*Asyncwrapper, the generator also writes__KotlinCoroutines__.cs: an internal class in the binding assembly that the wrappers call. A binding withsuspendfunctions already references the Kotlin standard library binding (Xamarin.Kotlin.StdLib), because the bound methods takeKotlin.Coroutines.IContinuation, so the helper uses the bound Kotlin types:Java.Lang.Objectsubclass implementsKotlin.Coroutines.IContinuation. It gets a normal Java callable wrapper.IntrinsicsKt.COROUTINE_SUSPENDED, theTaskcompletes later, when Kotlin callsresumeWith. Other return values complete it immediately. Akotlin.Result$Failurebecomes the matching managed exception, for exampleJava.Lang.IllegalStateException.Result$Failureis internal in Kotlin, so the helper reads itsexceptionfield through JNI.Task. When the binding referenceskotlinx.coroutines, the continuation context is a newJobfromJobKt.Job, and the token also callsIJob.Cancel, so cancellable Kotlin code (delay,withContext, …) stops. Otherwise, the context isEmptyCoroutineContext.Instance, and the Kotlin work continues.Alternatives:
Mono.Android. That puts Kotlin knowledge intoMono.Android, and it needs ajava.lang.reflect.Proxy, reflection, and Kotlin keep rules in every ProGuard configuration.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 --project <csproj>, MSTest on Microsoft.Testing.Platform):tests\Xamarin.Android.Tools.Bytecode-Tests: Passed 140, Skipped 2. Includes the newKotlinSuspendTests, which reads a Gradle-compiledSuspendFunctions.ktfixture.tests\Java.Interop.Tools.JavaTypeSystem-Tests: Passed 17.tests\generator-Tests: Passed 508. 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
org.jetbrains.kotlinx:kotlinx-coroutines-android1.10.2 with<AndroidMavenLibrary/>, and checks the generatedHandlerDispatcherKt.AwaitFrameAsyncand theJobin__KotlinCoroutines__.cs. Its dependencies are in the CI NuGet feed; the DataStore JVM packages are not.On-device, CoreCLR:
__KotlinCoroutineshelper: a Gradle module with Kotlinsuspendfunctions, bound into an app withNullableenabled. 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. Debug gives the same result. The generated binding code compiles without warnings.Mono.Androidhelper design: the real DataStore library, Release with R8: twoPreferencesKt.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 ran the
MSBuildDeviceIntegrationtest project by hand, not through the test runner, because its Windows teardown runsadb kill-serveron a shared host. 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.